repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
Sleeya/TechnologyFundamentals
SoftwareTechnologies/ExamPrepTwo/Java Skeleton/src/main/java/todolist/controller/TaskController.java
2262
package todolist.controller; import javassist.NotFoundException; import org.codehaus.groovy.control.messages.ExceptionMessage; import org.omg.IOP.ExceptionDetailMessage; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import todolist.bindingModel.TaskBindingModel; import todolist.entity.Task; import todolist.repository.TaskRepository; import java.util.List; @Controller public class TaskController { @Autowired private TaskRepository taskRepository; @GetMapping("/") public String index(Model model) { List<Task> tasks = this.taskRepository.findAll(); model.addAttribute("tasks", tasks); model.addAttribute("view", "task/index"); return "base-layout"; } @GetMapping("/create") public String create(Model model) { model.addAttribute("view","task/create"); return "base-layout"; } @PostMapping("/create") public String createProcess(Model model, TaskBindingModel taskBindingModel) { Task currentTask = new Task(); currentTask.setTitle(taskBindingModel.getTitle()); currentTask.setComments(taskBindingModel.getComments()); this.taskRepository.saveAndFlush(currentTask); return "redirect:/"; } @GetMapping("/delete/{id}") public String delete(Model model, @PathVariable int id) { if (!this.taskRepository.exists(id)){ return "NotFoundException"; } Task currentTask = this.taskRepository.findOne(id); model.addAttribute("task",currentTask); model.addAttribute("view","task/delete"); return "base-layout"; } @PostMapping("/delete/{id}") public String deleteProcess(Model model, @PathVariable int id) { if (!this.taskRepository.exists(id)){ return "NotFoundException"; } Task currentTask = this.taskRepository.findOne(id); this.taskRepository.delete(currentTask); return "redirect:/"; } }
mit
andrewoma/restless
core/src/main/java/com/github/andrewoma/restless/core/util/RandomIds.java
1777
/* * Copyright (c) 2015 Andrew O'Malley * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.github.andrewoma.restless.core.util; import javax.xml.bind.DatatypeConverter; public class RandomIds { /** * Returns a random 120 bit id, base64 encoded with an alphabet avoid regex special characters. * The chances of collision are similar to UUID.randomUUID() (120 versus 122 bits), but the resulting * string is much smaller and a ThreadLocalRandom is used to prevent contention. */ public static String randomId() { byte[] bytes = new byte[15]; ThreadLocalRandom.current().nextBytes(bytes); return DatatypeConverter.printBase64Binary(bytes).replace('+', '-').replace('/', '_'); } }
mit
atealxt/work-workspaces
HttpForwardDemo/src_restlet/org/restlet/resource/Resource.java
31131
/** * Copyright 2005-2008 Noelios Technologies. * * The contents of this file are subject to the terms of the following open * source licenses: LGPL 3.0 or LGPL 2.1 or CDDL 1.0 (the "Licenses"). You can * select the license that you prefer but you may not use this file except in * compliance with one of these Licenses. * * You can obtain a copy of the LGPL 3.0 license at * http://www.gnu.org/licenses/lgpl-3.0.html * * You can obtain a copy of the LGPL 2.1 license at * http://www.gnu.org/licenses/lgpl-2.1.html * * You can obtain a copy of the CDDL 1.0 license at * http://www.sun.com/cddl/cddl.html * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royaltee free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.noelios.com/products/restlet-engine * * Restlet is a registered trademark of Noelios Technologies. */ package org.restlet.resource; import java.util.ArrayList; import java.util.List; import org.restlet.Application; import org.restlet.Context; import org.restlet.Handler; import org.restlet.data.Dimension; import org.restlet.data.Language; import org.restlet.data.Parameter; import org.restlet.data.ReferenceList; import org.restlet.data.Request; import org.restlet.data.Response; import org.restlet.data.Status; import org.restlet.util.Series; /** * Intended conceptual target of a hypertext reference. "Any information that * can be named can be a resource: a document or image, a temporal service (e.g. * "today's weather in Los Angeles"), a collection of other resources, a * non-virtual object (e.g. a person), and so on. In other words, any concept * that might be the target of an author's hypertext reference must fit within * the definition of a resource. The only thing that is required to be static * for a resource is the semantics of the mapping, since the semantics is what * distinguishes one resource from another." Roy T. Fielding<br> * <br> * Another definition adapted from the URI standard (RFC 3986): a resource is * the conceptual mapping to a representation (also known as entity) or set of * representations, not necessarily the representation which corresponds to that * mapping at any particular instance in time. Thus, a resource can remain * constant even when its content (the representations to which it currently * corresponds) changes over time, provided that the conceptual mapping is not * changed in the process. In addition, a resource is always identified by a * URI.<br> * <br> * This is the point where the RESTful view of your Web application can be * integrated with your domain objects. Those domain objects can be implemented * using any technology, relational databases, object databases, transactional * components like EJB, etc.<br> * <br> * You just have to extend this class to override the REST methods you want to * support like {@link #acceptRepresentation(Representation)} for POST * processing, {@link #storeRepresentation(Representation)} for PUT processing * or {@link #removeRepresentations()} for DELETE processing.<br> * <br> * The common GET method is supported by the modifiable "variants" list property * and the {@link #represent(Variant)} method. This allows an easy and cheap * declaration of the available variants, in the constructor for example. Then * the creation of costly representations is delegated to the * {@link #represent(Variant)} method when actually needed.<br> * <br> * Concurrency note: typically created by Routers, Resource instances are the * final handlers of requests. Unlike the other processors in the Restlet chain, * a Resource instance is not reused by several calls and is only invoked by one * thread. Therefore, it doesn't have to be thread-safe.<br> * * @see <a * href="http://roy.gbiv.com/pubs/dissertation/rest_arch_style.htm#sec_5_2_1_1">Source * dissertation</a> * @see <a * href="http://www.restlet.org/documentation/1.1/tutorial#part12">Tutorial * : Reaching target Resources</a> * @see org.restlet.resource.Representation * @see org.restlet.Finder * @author Jerome Louvel * @author Thierry Boileau * @author Konstantin Laufer (laufer@cs.luc.edu) */ public class Resource extends Handler { /** Indicates if the resource is actually available. */ private boolean available; /** * Indicates if the representations can be modified via the * {@link #handlePost()}, the {@link #handlePut()} or the * {@link #handleDelete()} methods. */ private boolean modifiable; /** Indicates if the best content is automatically negotiated. */ private boolean negotiateContent; /** * Indicates if the representations can be read via the {@link #handleGet()} * method. */ private boolean readable; /** The modifiable list of variants. */ private volatile List<Variant> variants; /** * Initializer block to ensure that the basic properties of the Resource are * initialized consistently across constructors. */ { this.available = true; this.modifiable = false; this.negotiateContent = true; this.readable = true; this.variants = null; } /** * Special constructor used by IoC frameworks. Note that the init() method * MUST be invoked right after the creation of the handler in order to keep * a behavior consistent with the normal three arguments constructor. */ public Resource() { } /** * Normal constructor. This constructor will invoke the parent constructor * by default. * * @param context * The parent context. * @param request * The request to handle. * @param response * The response to return. */ public Resource(Context context, Request request, Response response) { super(context, request, response); } /** * Accepts and processes a representation posted to the resource. The * default behavior is to set the response status to * {@link Status#SERVER_ERROR_INTERNAL}.<br> * <br> * This is the higher-level method that let you process POST requests. * * @param entity * The posted entity. */ public void acceptRepresentation(Representation entity) throws ResourceException { getResponse().setStatus(Status.SERVER_ERROR_INTERNAL); } /** * Indicates if DELETE calls are allowed by checking the "modifiable" * property. * * @return True if the method is allowed. */ @Override public boolean allowDelete() { return isModifiable(); } /** * Indicates if GET calls are allowed by checking the "readable" property. * * @return True if the method is allowed. */ @Override public boolean allowGet() { return isReadable(); } /** * Indicates if POST calls are allowed by checking the "modifiable" * property. * * @return True if the method is allowed. */ @Override public boolean allowPost() { return isModifiable(); } /** * Indicates if PUT calls are allowed by checking the "modifiable" property. * * @return True if the method is allowed. */ @Override public boolean allowPut() { return isModifiable(); } /** * Asks the resource to delete itself and all its representations.The * default behavior is to invoke the {@link #removeRepresentations()} * method. * * @deprecated Use the {@link #removeRepresentations()} method instead. */ @Deprecated public void delete() { try { removeRepresentations(); } catch (ResourceException re) { getResponse().setStatus(re.getStatus(), re); } } /** * Returns the preferred representation according to the client preferences * specified in the request. * * @return The preferred representation. * @deprecated Use the {@link #represent()} method instead. * @see #getPreferredVariant() */ @Deprecated public Representation getPreferredRepresentation() { Representation result = null; try { result = represent(); } catch (ResourceException re) { getResponse().setStatus(re.getStatus(), re); } return result; } /** * Returns the preferred variant according to the client preferences * specified in the request. * * @return The preferred variant. */ public Variant getPreferredVariant() { Variant result = null; final List<Variant> variants = getVariants(); if ((variants != null) && (!variants.isEmpty())) { Language language = null; // Compute the preferred variant. Get the default language // preference from the Application (if any). final Application app = Application.getCurrent(); if (app != null) { language = app.getMetadataService().getDefaultLanguage(); } result = getRequest().getClientInfo().getPreferredVariant(variants, language); } return result; } /** * Returns a full representation for a given variant previously returned via * the getVariants() method. The default implementation directly returns the * variant in case the variants are already full representations. In all * other cases, you will need to override this method in order to provide * your own implementation. <br> * <br> * * This method is very useful for content negotiation when it is too costly * to initilize all the potential representations. It allows a resource to * simply expose the available variants via the getVariants() method and to * actually server the one selected via this method. * * @param variant * The variant whose full representation must be returned. * @return The full representation for the variant. * @see #getVariants() * @deprecated Use the {@link #represent(Variant)} method instead. */ @Deprecated public Representation getRepresentation(Variant variant) { Representation result = null; try { result = represent(variant); } catch (ResourceException re) { getResponse().setStatus(re.getStatus(), re); } return result; } /** * Returns the modifiable list of variants. Creates a new instance if no one * has been set. A variant can be a purely descriptive representation, with * no actual content that can be served. It can also be a full * representation in case a resource has only one variant or if the * initialization cost is very low.<br> * <br> * Note that the order in which the variants are inserted in the list * matters. For example, if the client has no preference defined, or if the * acceptable variants have the same quality level for the client, the first * acceptable variant in the list will be returned.<br> * <br> * It is recommended to not override this method and to simply use it at * construction time to initialize the list of available variants. * Overriding it may reconstruct the list for each call which can be * expensive. * * @return The list of variants. * @see #getRepresentation(Variant) */ public List<Variant> getVariants() { // Lazy initialization with double-check. List<Variant> v = this.variants; if (v == null) { synchronized (this) { v = this.variants; if (v == null) { this.variants = v = new ArrayList<Variant>(); } } } return v; } /** * Handles a DELETE call by invoking the {@link #removeRepresentations()} * method. It also automatically support conditional DELETEs. */ @Override public void handleDelete() { boolean canDelete = true; if (getRequest().getConditions().hasSome()) { Variant preferredVariant = null; if (isNegotiateContent()) { preferredVariant = getPreferredVariant(); } else { final List<Variant> variants = getVariants(); if (variants.size() == 1) { preferredVariant = variants.get(0); } else { getResponse().setStatus( Status.CLIENT_ERROR_PRECONDITION_FAILED); canDelete = false; } } // The conditions have to be checked // even if there is no preferred variant. if (canDelete) { final Status status = getRequest().getConditions().getStatus( getRequest().getMethod(), getRepresentation(preferredVariant)); if (status != null) { getResponse().setStatus(status); canDelete = false; } } } if (canDelete) { delete(); } } /** * Handles a GET call by automatically returning the best representation * available. The content negotiation is automatically supported based on * the client's preferences available in the request. This feature can be * turned off using the "negotiateContent" property.<br> * <br> * If the resource's "available" property is set to false, the method * immediately returns with a {@link Status#CLIENT_ERROR_NOT_FOUND} status.<br> * <br> * The negotiated representation is obtained by calling the * {@link #getPreferredVariant()}. If a variant is sucessfully selected, * then the {@link #represent(Variant)} method is called to get the actual * representation corresponding to the metadata in the variant.<br> * <br> * If no variant matching the client preferences is available, the response * status is set to {@link Status#CLIENT_ERROR_NOT_ACCEPTABLE} and the list * of available representations is returned in the response entity as a * textual list of URIs (only if the variants have an identifier properly * set).<br> * <br> * If the content negotiation is turned off and only one variant is defined * in the "variants" property, then its representation is returned by * calling the {@link #represent(Variant)} method. If several variants are * available, then the list of available representations is returned in the * response entity as a textual list of URIs (only if the variants have an * identifier properly set).<br> * <br> * If no variant is defined in the "variants" property, the response status * is set to {@link Status#CLIENT_ERROR_NOT_FOUND}. <br> * If it is disabled and multiple variants are available for the target * resource, then a 300 (Multiple Choices) status will be returned with the * list of variants URI if available. Conditional GETs are also * automatically supported. */ @Override public void handleGet() { if (!isAvailable()) { // Resource not existing or not available to the current client getResponse().setStatus(Status.CLIENT_ERROR_NOT_FOUND); } else { // The variant that may need to meet the request conditions Representation selectedRepresentation = null; final List<Variant> variants = getVariants(); if ((variants == null) || (variants.isEmpty())) { // Resource not found getResponse().setStatus(Status.CLIENT_ERROR_NOT_FOUND); getLogger() .warning( "A resource should normally have at least one variant added by calling getVariants().add() in the constructor. Check your resource \"" + getRequest().getResourceRef() + "\"."); } else if (isNegotiateContent()) { final Variant preferredVariant = getPreferredVariant(); if (preferredVariant == null) { // No variant was found matching the client preferences getResponse().setStatus(Status.CLIENT_ERROR_NOT_ACCEPTABLE); // The list of all variants is transmitted to the client final ReferenceList refs = new ReferenceList(variants .size()); for (final Variant variant : variants) { if (variant.getIdentifier() != null) { refs.add(variant.getIdentifier()); } } getResponse().setEntity(refs.getTextRepresentation()); } else { // Set the variant dimensions used for content negotiation getResponse().getDimensions().clear(); getResponse().getDimensions().add(Dimension.CHARACTER_SET); getResponse().getDimensions().add(Dimension.ENCODING); getResponse().getDimensions().add(Dimension.LANGUAGE); getResponse().getDimensions().add(Dimension.MEDIA_TYPE); // Set the negotiated representation as response entity getResponse() .setEntity(getRepresentation(preferredVariant)); } selectedRepresentation = getResponse().getEntity(); } else { if (variants.size() == 1) { getResponse().setEntity(getRepresentation(variants.get(0))); selectedRepresentation = getResponse().getEntity(); } else { final ReferenceList variantRefs = new ReferenceList(); for (final Variant variant : variants) { if (variant.getIdentifier() != null) { variantRefs.add(variant.getIdentifier()); } else { getLogger() .warning( "A resource with multiple variants should provide an identifier for each variant when content negotiation is turned off"); } } if (variantRefs.size() > 0) { // Return the list of variants getResponse().setStatus( Status.REDIRECTION_MULTIPLE_CHOICES); getResponse().setEntity( variantRefs.getTextRepresentation()); } else { getResponse().setStatus(Status.CLIENT_ERROR_NOT_FOUND); } } } if (selectedRepresentation == null) { if ((getResponse().getStatus() == null) || (getResponse().getStatus().isSuccess() && !Status.SUCCESS_NO_CONTENT .equals(getResponse().getStatus()))) { getResponse().setStatus(Status.CLIENT_ERROR_NOT_FOUND); } else { // Keep the current status as the developer might prefer a // special status like 'method not authorized'. } } else { // The given representation (even if null) must meet the request // conditions (if any). if (getRequest().getConditions().hasSome()) { final Status status = getRequest().getConditions() .getStatus(getRequest().getMethod(), selectedRepresentation); if (status != null) { getResponse().setStatus(status); getResponse().setEntity(null); } } } } } /** * Handles a POST call by invoking the * {@link #acceptRepresentation(Representation)} method. It also logs a * trace if there is no entity posted. */ @Override public void handlePost() { if (!getRequest().isEntityAvailable()) { getLogger() .fine( "POST request received without any entity. Continuing processing."); } post(getRequest().getEntity()); } /** * Handles a PUT call by invoking the * {@link #storeRepresentation(Representation)} method. It also handles * conditional PUTs and forbids partial PUTs as they are not supported yet. * Finally, it prevents PUT with no entity by setting the response status to * {@link Status#CLIENT_ERROR_BAD_REQUEST} following the HTTP * specifications. */ @SuppressWarnings("unchecked") @Override public void handlePut() { boolean canPut = true; if (getRequest().getConditions().hasSome()) { Variant preferredVariant = null; if (isNegotiateContent()) { preferredVariant = getPreferredVariant(); } else { final List<Variant> variants = getVariants(); if (variants.size() == 1) { preferredVariant = variants.get(0); } else { getResponse().setStatus( Status.CLIENT_ERROR_PRECONDITION_FAILED); canPut = false; } } // The conditions have to be checked // even if there is no preferred variant. if (canPut) { final Status status = getRequest().getConditions().getStatus( getRequest().getMethod(), getRepresentation(preferredVariant)); if (status != null) { getResponse().setStatus(status); canPut = false; } } } if (canPut) { // Check the Content-Range HTTP Header // in order to prevent usage of partial PUTs final Object oHeaders = getRequest().getAttributes().get( "org.restlet.http.headers"); if (oHeaders != null) { final Series<Parameter> headers = (Series<Parameter>) oHeaders; if (headers.getFirst("Content-Range", true) != null) { getResponse() .setStatus( new Status( Status.SERVER_ERROR_NOT_IMPLEMENTED, "The Content-Range header is not understood")); canPut = false; } } } if (canPut) { put(getRequest().getEntity()); // HTTP spec says that PUT may return // the list of allowed methods updateAllowedMethods(); } } /** * Initialize the resource with its context. If you override this method, * make sure that you don't forget to call super.init() first, otherwise * your Resource won't behave properly. * * @param context * The parent context. * @param request * The request to handle. * @param response * The response to return. */ @Override public void init(Context context, Request request, Response response) { super.init(context, request, response); } /** * Indicates if the resource is actually available. By default this property * is true but it can be set to false if the resource doesn't exist at all * or if it isn't visible to a specific client. The {@link #handleGet()} * method will set the response's status to * {@link Status#CLIENT_ERROR_NOT_FOUND} if this property is false. * * @return True if the resource is available. */ public boolean isAvailable() { return this.available; } /** * Indicates if the representations can be modified via the * {@link #handlePost()}, the {@link #handlePut()} or the * {@link #handleDelete()} methods. * * @return True if representations can be modified. */ public boolean isModifiable() { return this.modifiable; } /** * Indicates if the best content is automatically negotiated. Default value * is true. * * @return True if the best content is automatically negotiated. */ public boolean isNegotiateContent() { return this.negotiateContent; } /** * Indicates if the representations can be read via the {@link #handleGet()} * method. * * @return True if the representations can be read. */ public boolean isReadable() { return this.readable; } /** * Posts a representation to the resource. The default behavior is to invoke * the {@link #acceptRepresentation(Representation)} method. * * @param entity * The representation posted. * @deprecated Use the {@link #acceptRepresentation(Representation)} method * instead. */ @Deprecated public void post(Representation entity) { try { acceptRepresentation(entity); } catch (ResourceException re) { getResponse().setStatus(re.getStatus(), re); } } /** * Puts a representation in the resource. The default behavior is to invoke * the {@link #storeRepresentation(Representation)} method. * * @param entity * The representation put. * @deprecated Use the {@link #storeRepresentation(Representation)} method * instead. */ @Deprecated public void put(Representation entity) { try { storeRepresentation(entity); } catch (ResourceException re) { getResponse().setStatus(re.getStatus(), re); } } /** * Removes all the representations of the resource and effectively the * resource itself. The default behavior is to set the response status to * {@link Status#SERVER_ERROR_INTERNAL}.<br> * <br> * This is the higher-level method that let you process DELETE requests. */ public void removeRepresentations() throws ResourceException { getResponse().setStatus(Status.SERVER_ERROR_INTERNAL); } /** * Returns the preferred representation according to the client preferences * specified in the request. By default it calls the * {@link #represent(Variant)} method with the preferred variant returned by * {@link #getPreferredVariant()}. * * @return The preferred representation. * @see #getPreferredVariant() * @throws ResourceException */ public Representation represent() throws ResourceException { return represent(getPreferredVariant()); } /** * Returns a full representation for a given variant previously returned via * the getVariants() method. The default implementation directly returns the * variant in case the variants are already full representations. In all * other cases, you will need to override this method in order to provide * your own implementation. <br> * <br> * * This method is very useful for content negotiation when it is too costly * to initialize all the potential representations. It allows a resource to * simply expose the available variants via the getVariants() method and to * actually server the one selected via this method. * * @param variant * The variant whose full representation must be returned. * @return The full representation for the variant. * @see #getVariants() */ public Representation represent(Variant variant) throws ResourceException { Representation result = null; if (variant instanceof Representation) { result = (Representation) variant; } return result; } /** * Indicates if the resource is actually available. By default this property * is true but it can be set to false if the resource doesn't exist at all * or if it isn't visible to a specific client. The {@link #handleGet()} * method will set the response's status to * {@link Status#CLIENT_ERROR_NOT_FOUND} if this property is false. * * @param available * True if the resource is actually available. */ public void setAvailable(boolean available) { this.available = available; } /** * Indicates if the representations can be modified via the * {@link #handlePost()}, the {@link #handlePut()} or the * {@link #handleDelete()} methods. * * @param modifiable * Indicates if the representations can be modified. */ public void setModifiable(boolean modifiable) { this.modifiable = modifiable; } /** * Indicates if the returned representation is automatically negotiated. * Default value is true. * * @param negotiateContent * True if content negotiation is enabled. */ public void setNegotiateContent(boolean negotiateContent) { this.negotiateContent = negotiateContent; } /** * Indicates if the representations can be read via the {@link #handleGet()} * method. * * @param readable * Indicates if the representations can be read. */ public void setReadable(boolean readable) { this.readable = readable; } /** * Sets the modifiable list of variants. * * @param variants * The modifiable list of variants. */ public void setVariants(List<Variant> variants) { this.variants = variants; } /** * Stores a representation put to the resource and replaces all existing * representations of the resource. If the resource doesn't exist yet, it * should create it and use the entity as its initial representation. The * default behavior is to set the response status to * {@link Status#SERVER_ERROR_INTERNAL}.<br> * <br> * This is the higher-level method that let you process PUT requests. * * @param entity */ public void storeRepresentation(Representation entity) throws ResourceException { getResponse().setStatus(Status.SERVER_ERROR_INTERNAL); } }
mit
Anastaszor/magic-nexus
src/org/magicnexus/classes/mtgjson/cli/command/ListExtensionsCommand.java
713
package org.magicnexus.classes.mtgjson.cli.command; import org.magicnexus.classes.mtgjson.MtgjsonApplication; import org.magicnexus.classes.mtgjson.data.MtgjsonDatabase; import org.magicnexus.interfaces.ui.cli.IUiCommand; public class ListExtensionsCommand implements IUiCommand { private MtgjsonApplication application = null; public ListExtensionsCommand(MtgjsonApplication application) { this.application = application; } @Override public void execute() throws Exception { MtgjsonDatabase db = new MtgjsonDatabase(application.getMtgjsonDirectory()); MtgjsonExtensionList el = db.getExtensionList(); application.writeln(String.join(",\n", el.getAvailableExtensionsCodes())); } }
mit
geomatico/dataportal
dataportal/src/main/java/org/dataportal/Messages.java
1025
package org.dataportal; import java.util.Locale; import java.util.MissingResourceException; import java.util.ResourceBundle; public class Messages { private static final String BUNDLE_NAME = "messages"; //$NON-NLS-1$ private static final String DEFAULT_LANGUAGE = "en"; //$NON-NLS-1$ private static Locale locale = new Locale(DEFAULT_LANGUAGE); private static ResourceBundle resource_bundle = ResourceBundle.getBundle( BUNDLE_NAME, locale); /** * @return the locale */ public static Locale getLocale() { return locale; } /** * @param locale * the lang to set */ public static void setLang(String language) { if (language == null) locale = new Locale(DEFAULT_LANGUAGE); else locale = new Locale(language); resource_bundle = ResourceBundle.getBundle(BUNDLE_NAME, locale); } private Messages() { } public static String getString(String key) { try { return resource_bundle.getString(key); } catch (MissingResourceException e) { return '!' + key + '!'; } } }
mit
zutnop/telekom-workflow-engine
telekom-workflow-engine/src/main/java/ee/telekom/workflow/util/AbstractDao.java
849
package ee.telekom.workflow.util; import javax.sql.DataSource; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcDaoSupport; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; public class AbstractDao{ private NamedParameterJdbcDaoSupport daoSupport; public void setDataSource( DataSource dataSource ){ daoSupport = new NamedParameterJdbcDaoSupport(); daoSupport.setDataSource( dataSource ); } public DataSource getDataSource(){ return daoSupport.getDataSource(); } protected JdbcTemplate getJdbcTemplate(){ return daoSupport.getJdbcTemplate(); } protected NamedParameterJdbcTemplate getNamedParameterJdbcTemplate(){ return daoSupport.getNamedParameterJdbcTemplate(); } }
mit
glipecki/watson
watson-rest/src/main/java/net/lipecki/watson/category/ModifyCategoryController.java
1477
package net.lipecki.watson.category; import lombok.extern.slf4j.Slf4j; import net.lipecki.watson.event.Event; import net.lipecki.watson.rest.Api; import org.springframework.transaction.annotation.Transactional; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @Slf4j @RestController @RequestMapping(Api.V1) public class ModifyCategoryController { private final ModifyCategoryCommand modifyCategoryCommand; public ModifyCategoryController(final ModifyCategoryCommand modifyCategoryCommand) { this.modifyCategoryCommand = modifyCategoryCommand; } @PutMapping("/category/{uuid}") @Transactional public Event modifyProduct( @PathVariable final String uuid, @Validated @RequestBody final ModifyCategoryDto dto) { log.info("Request to modify category [uuid={}, dto={}]", uuid, dto); return modifyCategoryCommand.modifyCategory( ModifyCategoryData .builder() .uuid(uuid) .name(dto.getName()) .parentUuid(dto.getParentUuid()) .build() ); } }
mit
lyle8341/design_pattern
src/com/lyle/structure/适配器模式/WindowImpl.java
403
package com.lyle.structure.适配器模式; /** * @ClassName: WindowImpl * @Description: 子类选择性实现需要的方法 * @author: Lyle * @date: 2017年2月3日 上午10:05:49 */ public class WindowImpl extends WindowAdapter { @Override public void open() { System.out.println("WindowImpl.open()"); } @Override public void close() { System.out.println("WindowImpl.close()"); } }
mit
epam/NGB
server/catgenome/src/main/java/com/epam/catgenome/dao/BiologicalDataItemDao.java
28299
/* * MIT License * * Copyright (c) 2016-2022 EPAM Systems * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.epam.catgenome.dao; import static com.epam.catgenome.dao.BiologicalDataItemDao.BiologicalDataItemParameters.getRowMapper; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Collections; import java.util.Date; import java.util.List; import com.epam.catgenome.component.MessageHelper; import com.epam.catgenome.constant.MessagesConstants; import com.epam.catgenome.entity.BiologicalDataItem; import com.epam.catgenome.entity.BiologicalDataItemFormat; import com.epam.catgenome.entity.BiologicalDataItemResourceType; import com.epam.catgenome.entity.FeatureFile; import com.epam.catgenome.entity.bam.BamFile; import com.epam.catgenome.entity.bed.BedFile; import com.epam.catgenome.entity.externaldb.ExternalDB; import com.epam.catgenome.entity.externaldb.ExternalDBType; import com.epam.catgenome.entity.gene.GeneFile; import com.epam.catgenome.entity.heatmap.Heatmap; import com.epam.catgenome.entity.heatmap.HeatmapDataType; import com.epam.catgenome.entity.lineage.LineageTree; import com.epam.catgenome.entity.maf.MafFile; import com.epam.catgenome.entity.pathway.NGBPathway; import com.epam.catgenome.entity.pathway.PathwayDatabaseSource; import com.epam.catgenome.entity.reference.Reference; import com.epam.catgenome.entity.seg.SegFile; import com.epam.catgenome.entity.vcf.VcfFile; import com.epam.catgenome.entity.wig.WigFile; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.StringUtils; import org.jetbrains.annotations.NotNull; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Required; import org.springframework.jdbc.core.RowMapper; import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcDaoSupport; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.Assert; /** * Source: BiologicalDataItemDao * Created: 17.12.15, 13:12 * Project: CATGenome Browser * Make: IntelliJ IDEA 14.1.4, JDK 1.8 * * <p> * A DAO class, managing BiologicalDataItem entities and containing common logic for it's ancestors retrieval * </p> */ public class BiologicalDataItemDao extends NamedParameterJdbcDaoSupport { private String biologicalDataItemSequenceName; private String insertBiologicalDataItemQuery; private String updateOwnerQuery; private String loadBiologicalDataItemsByIdsQuery; private String deleteBiologicalDataItemQuery; private String loadBiologicalDataItemsByNameStrictQuery; private String loadBiologicalDataItemsByNamesStrictQuery; private String loadBiologicalDataItemsByNameQuery; private String loadBiologicalDataItemsByNameCaseInsensitiveQuery; @Autowired private DaoHelper daoHelper; /** * Persists a BiologicalDataItem instance into the database * @param item BiologicalDataItem to persist */ @Transactional(propagation = Propagation.MANDATORY) public void createBiologicalDataItem(BiologicalDataItem item) { if (!item.getFormat().isIndex() || (item.getFormat().isIndex() && !StringUtils.isEmpty(item.getName()))) { Assert.isTrue(!StringUtils.isEmpty(item.getName()), "File name is required for registration."); List<BiologicalDataItem> items = loadFilesByNameStrict(item.getName()); Assert.isTrue(items.isEmpty(), MessageHelper .getMessage(MessagesConstants.ERROR_FILE_NAME_EXISTS, item.getName())); item.setId(daoHelper.createId(biologicalDataItemSequenceName)); } else { item.setId(daoHelper.createId(biologicalDataItemSequenceName)); item.setName("INDEX " + item.getId()); } final MapSqlParameterSource params = new MapSqlParameterSource(); params.addValue(BiologicalDataItemParameters.BIO_DATA_ITEM_ID.name(), item.getId()); params.addValue(BiologicalDataItemParameters.NAME.name(), item.getName()); params.addValue(BiologicalDataItemParameters.TYPE.name(), item.getType().getId()); params.addValue(BiologicalDataItemParameters.PATH.name(), item.getPath()); params.addValue(BiologicalDataItemParameters.SOURCE.name(), item.getSource()); params.addValue(BiologicalDataItemParameters.FORMAT.name(), item.getFormat().getId()); params.addValue(BiologicalDataItemParameters.CREATED_DATE.name(), item.getCreatedDate()); params.addValue(BiologicalDataItemParameters.BUCKET_ID.name(), item.getBucketId()); params.addValue(BiologicalDataItemParameters.PRETTY_NAME.name(), item.getPrettyName()); params.addValue(BiologicalDataItemParameters.OWNER.name(), item.getOwner()); getNamedParameterJdbcTemplate().update(insertBiologicalDataItemQuery, params); } /** * Loads a List of BiologicalDataItem from the database by their IDs * @param ids List of IDs of BiologicalDataItem instances * @return List of BiologicalDataItem, matching specified IDs */ @Transactional(propagation = Propagation.SUPPORTS) public List<BiologicalDataItem> loadBiologicalDataItemsByIds(List<Long> ids) { if (ids == null || ids.isEmpty()) { return Collections.emptyList(); } String query = DaoHelper.getQueryFilledWithIdArray(loadBiologicalDataItemsByIdsQuery, ids); return getNamedParameterJdbcTemplate().query(query, getRowMapper()); } @Transactional(propagation = Propagation.MANDATORY) public Long createBioItemId() { return daoHelper.createId(biologicalDataItemSequenceName); } /** * Deletes a BiologicalDataItem instance from the database by it's ID * @param bioDataItemId ID of BiologicalDataItem instance to delete */ @Transactional(propagation = Propagation.MANDATORY) public void deleteBiologicalDataItem(final long bioDataItemId) { getJdbcTemplate().update(deleteBiologicalDataItemQuery, bioDataItemId); } /** * Update owner for given bioItemId */ @Transactional(propagation = Propagation.MANDATORY) public void updateOwner(long bioItemId, String newOwner) { Assert.isTrue(StringUtils.isNotBlank(newOwner), "Owner cannot be empty"); final MapSqlParameterSource params = new MapSqlParameterSource(); params.addValue(BiologicalDataItemParameters.BIO_DATA_ITEM_ID.name(), bioItemId); params.addValue(BiologicalDataItemParameters.OWNER.name(), newOwner); getNamedParameterJdbcTemplate().update(updateOwnerQuery, params); } /** * An enum of BiologicalDataItem's ancestor's fields */ /** * Finds files with a specified file name, checks name for strict, case sensitive equality * @param name search query * @return {@code List} of files with a matching name */ @Transactional(propagation = Propagation.SUPPORTS) public List<BiologicalDataItem> loadFilesByNameStrict(final String name) { final MapSqlParameterSource params = new MapSqlParameterSource(); params.addValue(BiologicalDataItemParameters.NAME.name(), name); return getNamedParameterJdbcTemplate().query(loadBiologicalDataItemsByNameStrictQuery, params, getRowMapper()); } @Transactional(propagation = Propagation.SUPPORTS) public List<BiologicalDataItem> loadFilesByNameCaseInsensitive(final String name) { final MapSqlParameterSource params = new MapSqlParameterSource(); params.addValue(BiologicalDataItemParameters.NAME.name(), name.toLowerCase()); return getNamedParameterJdbcTemplate().query(loadBiologicalDataItemsByNameCaseInsensitiveQuery, params, getRowMapper()); } @Transactional(propagation = Propagation.SUPPORTS) public List<BiologicalDataItem> loadFilesByNamesStrict(final List<String> names) { if (CollectionUtils.isEmpty(names)) { return Collections.emptyList(); } String query = DaoHelper.getQueryFilledWithStringArray(loadBiologicalDataItemsByNamesStrictQuery, names); return getJdbcTemplate().query(query, getRowMapper()); } /** * Finds files with names matching a specified file name, performs substring, case insensitive search * @param name search query * @return {@code List} of files with a matching name */ @Transactional(propagation = Propagation.SUPPORTS) public List<BiologicalDataItem> loadFilesByName(final String name) { final MapSqlParameterSource params = new MapSqlParameterSource(); params.addValue(BiologicalDataItemParameters.NAME.name(), "%" + name.toLowerCase() + "%"); return getNamedParameterJdbcTemplate().query(loadBiologicalDataItemsByNameQuery, params, getRowMapper()); } public enum BiologicalDataItemParameters { BIO_DATA_ITEM_ID, NAME, TYPE, PATH, SOURCE, FORMAT, CREATED_DATE, BUCKET_ID, PRETTY_NAME, OWNER, VCF_ID, VCF_REFERENCE_GENOME_ID, VCF_COMPRESSED, VCF_MULTI_SAMPLE, GENE_ITEM_ID, GENE_REFERENCE_GENOME_ID, GENE_COMPRESSED, GENE_EXTERNAL_DB_TYPE_ID, GENE_EXTERNAL_DB_ID, GENE_EXTERNAL_DB_ORGANISM, REFERENCE_GENOME_ID, REFERENCE_GENOME_SIZE, REFERENCE_GENE_ITEM_ID, REFERENCE_GENE_ITEM_NAME, REFERENCE_GENE_BIO_DATA_ITEM_ID, REFERENCE_GENE_TYPE, REFERENCE_GENE_PATH, REFERENCE_GENE_FORMAT, REFERENCE_GENE_CREATED_DATE, REFERENCE_GENE_REFERENCE_GENOME_ID, REFERENCE_GENE_COMPRESSED, BAM_ID, BAM_REFERENCE_GENOME_ID, BED_GRAPH_ID, BED_GRAPH_REFERENCE_GENOME_ID, BED_ID, BED_REFERENCE_GENOME_ID, BED_COMPRESSED, SEG_ID, SEG_REFERENCE_GENOME_ID, SEG_COMPRESSED, MAF_ID, MAF_REFERENCE_GENOME_ID, MAF_COMPRESSED, MAF_REAL_PATH, VG_ID, VG_REFERENCE_GENOME_ID, VG_REAL_PATH, HEATMAP_ID, HEATMAP_CELL_VALUE_TYPE, HEATMAP_ROW_TREE_PATH, HEATMAP_COLUMN_TREE_PATH, HEATMAP_CELL_ANNOTATION_PATH, HEATMAP_LABEL_ANNOTATION_PATH, LINEAGE_TREE_ID, DESCRIPTION, NODES_PATH, EDGES_PATH, PATHWAY_ID, PATHWAY_DESC, DATABASE_SOURCE, INDEX_ID, INDEX_NAME, INDEX_TYPE, INDEX_PATH, INDEX_FORMAT, INDEX_BUCKET_ID, INDEX_CREATED_DATE; /** * Returns a universal row mapper for all BiologicalDataItem's ancestor entities * @return a universal row mapper */ public static RowMapper<BiologicalDataItem> getRowMapper() { return (rs, rowNum) -> mapRow(rs, true); } public static RowMapper<BiologicalDataItem> getRowMapper(final boolean loadIndex) { return (rs, rowNum) -> mapRow(rs, loadIndex); } private static BiologicalDataItem mapRow(ResultSet rs, boolean loadIndex) throws SQLException { long longVal = rs.getLong(FORMAT.name()); BiologicalDataItemFormat format = rs.wasNull() ? null : BiologicalDataItemFormat.getById(longVal); BiologicalDataItem index = null; if (loadIndex) { long indexId = rs.getLong(INDEX_ID.name()); if (!rs.wasNull()) { index = new BiologicalDataItem(); index.setId(indexId); index.setName(rs.getString(INDEX_NAME.name())); index.setType(BiologicalDataItemResourceType.getById(rs.getLong(INDEX_TYPE.name()))); index.setPath(rs.getString(INDEX_PATH.name())); index.setFormat(BiologicalDataItemFormat.getById(rs.getLong(INDEX_FORMAT.name()))); index.setCreatedDate(new Date(rs.getTimestamp(INDEX_CREATED_DATE.name()).getTime())); } } BiologicalDataItem dataItem; if (format != null) { dataItem = mapSpecialFields(rs, format, index); } else { dataItem = mapBioDataItem(rs); } dataItem.setName(rs.getString(NAME.name())); longVal = rs.getLong(TYPE.name()); dataItem.setType(rs.wasNull() ? null : BiologicalDataItemResourceType.getById(longVal)); dataItem.setPath(rs.getString(PATH.name())); dataItem.setSource(rs.getString(SOURCE.name())); dataItem.setFormat(format); dataItem.setCreatedDate(new Date(rs.getTimestamp(CREATED_DATE.name()).getTime())); dataItem.setPrettyName(rs.getString(PRETTY_NAME.name())); dataItem.setOwner(rs.getString(OWNER.name())); return dataItem; } @NotNull private static BiologicalDataItem mapSpecialFields(ResultSet rs, BiologicalDataItemFormat format, BiologicalDataItem index) throws SQLException { BiologicalDataItem dataItem; switch (format) { case REFERENCE: dataItem = mapReference(rs); break; case VCF: dataItem = mapVcfFile(rs, index); break; case GENE: case FEATURE_COUNTS: dataItem = mapGeneFile(rs, index, format); break; case BAM: dataItem = mapBamFile(rs, index); break; case WIG: dataItem = mapWigFile(rs, index); break; case BED: dataItem = mapBedFile(rs, index); break; case SEG: dataItem = mapSegFile(rs, index); break; case MAF: dataItem = mapMafFile(rs, index); break; case HEATMAP: dataItem = mapHeatMap(rs); break; case LINEAGE_TREE: dataItem = mapLineageTree(rs); break; case PATHWAY: dataItem = mapPathway(rs); break; default: dataItem = mapBioDataItem(rs); } return dataItem; } private static BiologicalDataItem mapHeatMap(final ResultSet rs) throws SQLException { final Heatmap heatmap = Heatmap.builder().build(); heatmap.setId(rs.getLong(HEATMAP_ID.name())); heatmap.setHeatmapId(rs.getLong(HEATMAP_ID.name())); heatmap.setBioDataItemId(rs.getLong(BIO_DATA_ITEM_ID.name())); heatmap.setCellAnnotationPath(rs.getString(HEATMAP_CELL_ANNOTATION_PATH.name())); heatmap.setLabelAnnotationPath(rs.getString(HEATMAP_LABEL_ANNOTATION_PATH.name())); heatmap.setCellValueType(HeatmapDataType.getById(rs.getInt(HEATMAP_CELL_VALUE_TYPE.name()))); heatmap.setRowTreePath(rs.getString(HEATMAP_ROW_TREE_PATH.name())); heatmap.setColumnTreePath(rs.getString(HEATMAP_COLUMN_TREE_PATH.name())); return heatmap; } private static BiologicalDataItem mapLineageTree(final ResultSet rs) throws SQLException { final LineageTree lineageTree = LineageTree.builder().build(); lineageTree.setId(rs.getLong(LINEAGE_TREE_ID.name())); lineageTree.setLineageTreeId(rs.getLong(LINEAGE_TREE_ID.name())); lineageTree.setBioDataItemId(rs.getLong(BIO_DATA_ITEM_ID.name())); lineageTree.setDescription(rs.getString(DESCRIPTION.name())); lineageTree.setNodesPath(rs.getString(NODES_PATH.name())); lineageTree.setEdgesPath(rs.getString(EDGES_PATH.name())); return lineageTree; } private static BiologicalDataItem mapPathway(final ResultSet rs) throws SQLException { final NGBPathway pathway = NGBPathway.builder().build(); pathway.setId(rs.getLong(PATHWAY_ID.name())); pathway.setPathwayId(rs.getLong(PATHWAY_ID.name())); pathway.setPathwayDesc(rs.getString(PATHWAY_DESC.name())); final long databaseSource = rs.getLong(DATABASE_SOURCE.name()); if (!rs.wasNull()) { pathway.setDatabaseSource(PathwayDatabaseSource.getById(databaseSource)); } pathway.setBioDataItemId(rs.getLong(BIO_DATA_ITEM_ID.name())); return pathway; } private static BiologicalDataItem mapBioDataItem(ResultSet rs) throws SQLException { BiologicalDataItem dataItem = new BiologicalDataItem(); dataItem.setId(rs.getLong(BIO_DATA_ITEM_ID.name())); return dataItem; } @NotNull private static BiologicalDataItem mapMafFile(ResultSet rs, BiologicalDataItem index) throws SQLException { MafFile mafFile = new MafFile(); mafFile.setId(rs.getLong(MAF_ID.name())); mafFile.setBioDataItemId(rs.getLong(BIO_DATA_ITEM_ID.name())); mafFile.setCompressed(rs.getBoolean(MAF_COMPRESSED.name())); mafFile.setReferenceId(rs.getLong(MAF_REFERENCE_GENOME_ID.name())); mafFile.setRealPath(rs.getString(MAF_REAL_PATH.name())); mafFile.setIndex(index); return mafFile; } @NotNull private static BiologicalDataItem mapSegFile(ResultSet rs, BiologicalDataItem index) throws SQLException { SegFile segFile = new SegFile(); segFile.setId(rs.getLong(SEG_ID.name())); segFile.setBioDataItemId(rs.getLong(BIO_DATA_ITEM_ID.name())); segFile.setCompressed(rs.getBoolean(SEG_COMPRESSED.name())); segFile.setReferenceId(rs.getLong(SEG_REFERENCE_GENOME_ID.name())); segFile.setIndex(index); return segFile; } @NotNull private static BiologicalDataItem mapBedFile(ResultSet rs, BiologicalDataItem index) throws SQLException { BedFile bedFile = new BedFile(); bedFile.setId(rs.getLong(BED_ID.name())); bedFile.setBioDataItemId(rs.getLong(BIO_DATA_ITEM_ID.name())); bedFile.setCompressed(rs.getBoolean(BED_COMPRESSED.name())); bedFile.setReferenceId(rs.getLong(BED_REFERENCE_GENOME_ID.name())); bedFile.setIndex(index); return bedFile; } @NotNull private static BiologicalDataItem mapWigFile(ResultSet rs, BiologicalDataItem index) throws SQLException { WigFile wigFile = new WigFile(); wigFile.setId(rs.getLong(BED_GRAPH_ID.name())); wigFile.setBioDataItemId(rs.getLong(BIO_DATA_ITEM_ID.name())); wigFile.setReferenceId(rs.getLong(BED_GRAPH_REFERENCE_GENOME_ID.name())); wigFile.setIndex(index); return wigFile; } @NotNull private static BiologicalDataItem mapBamFile(ResultSet rs, BiologicalDataItem index) throws SQLException { BamFile bamFile = new BamFile(); bamFile.setId(rs.getLong(BAM_ID.name())); bamFile.setBioDataItemId(rs.getLong(BIO_DATA_ITEM_ID.name())); bamFile.setReferenceId(rs.getLong(BAM_REFERENCE_GENOME_ID.name())); bamFile.setIndex(index); return bamFile; } @NotNull private static BiologicalDataItem mapGeneFile(ResultSet rs, BiologicalDataItem index, BiologicalDataItemFormat format) throws SQLException { GeneFile geneFile = new GeneFile(); geneFile.setFormat(format); geneFile.setId(rs.getLong(GENE_ITEM_ID.name())); geneFile.setBioDataItemId(rs.getLong(BIO_DATA_ITEM_ID.name())); geneFile.setCompressed(rs.getBoolean(GENE_COMPRESSED.name())); geneFile.setReferenceId(rs.getLong(GENE_REFERENCE_GENOME_ID.name())); long longVal = rs.getLong(GENE_EXTERNAL_DB_TYPE_ID.name()); if (!rs.wasNull()) { geneFile.setExternalDBType(ExternalDBType.getById(longVal)); } longVal = rs.getLong(GENE_EXTERNAL_DB_ID.name()); if (!rs.wasNull()) { geneFile.setExternalDB(ExternalDB.getById(longVal)); } geneFile.setExternalDBOrganism(rs.getString(GENE_EXTERNAL_DB_ORGANISM.name())); geneFile.setIndex(index); return geneFile; } @NotNull private static BiologicalDataItem mapVcfFile(ResultSet rs, BiologicalDataItem index) throws SQLException { VcfFile vcfFile = new VcfFile(); vcfFile.setId(rs.getLong(VCF_ID.name())); vcfFile.setBioDataItemId(rs.getLong(BIO_DATA_ITEM_ID.name())); vcfFile.setCompressed(rs.getBoolean(VCF_COMPRESSED.name())); vcfFile.setMultiSample(rs.getBoolean(VCF_MULTI_SAMPLE.name())); vcfFile.setReferenceId(rs.getLong(VCF_REFERENCE_GENOME_ID.name())); vcfFile.setIndex(index); return vcfFile; } @NotNull private static BiologicalDataItem mapReference(ResultSet rs) throws SQLException { Reference reference = new Reference(); reference.setBioDataItemId(rs.getLong(BIO_DATA_ITEM_ID.name())); reference.setSize(rs.getLong(REFERENCE_GENOME_SIZE.name())); reference.setId(rs.getLong(REFERENCE_GENOME_ID.name())); long longVal = rs.getLong(REFERENCE_GENE_ITEM_ID.name()); if (!rs.wasNull()) { GeneFile geneFile = new GeneFile(); geneFile.setId(longVal); geneFile.setName(rs.getString(REFERENCE_GENE_ITEM_NAME.name())); geneFile.setBioDataItemId(rs.getLong(REFERENCE_GENE_BIO_DATA_ITEM_ID.name())); longVal = rs.getLong(REFERENCE_GENE_TYPE.name()); geneFile.setType(rs.wasNull() ? null : BiologicalDataItemResourceType.getById(longVal)); geneFile.setPath(rs.getString(REFERENCE_GENE_PATH.name())); longVal = rs.getLong(REFERENCE_GENE_FORMAT.name()); geneFile.setFormat(rs.wasNull() ? null : BiologicalDataItemFormat.getById(longVal)); geneFile.setCreatedDate(new Date(rs.getTimestamp(REFERENCE_GENE_CREATED_DATE.name()).getTime())); geneFile.setReferenceId(rs.getLong(REFERENCE_GENE_REFERENCE_GENOME_ID.name())); geneFile.setCompressed(rs.getBoolean(REFERENCE_GENE_COMPRESSED.name())); reference.setGeneFile(geneFile); } return reference; } } /** * Enum, containing common FeatureFile's ancestor's fields */ public enum FeatureFileParameters { REFERENCE_GENOME_ID, INDEX_ID, COMPRESSED, MULTI_SAMPLE, EXTERNAL_DB_TYPE_ID, EXTERNAL_DB_ID, EXTERNAL_DB_ORGANISM; /** * Creates a MapSqlParameterSource with common FeatureFile's ancestor's fields for future use in DB queries * @param idFieldName a name of ID fields of FeatureFile's ancestor's * @param featureFile a FeatureFile's ancestor's entity, which fields to add to parameters * @return a MapSqlParameterSource with common FeatureFile's ancestor's fields */ public static MapSqlParameterSource getLinkedTableParameters(String idFieldName, FeatureFile featureFile) { MapSqlParameterSource params = new MapSqlParameterSource(); params.addValue(idFieldName, featureFile.getId()); params.addValue(BiologicalDataItemParameters.BIO_DATA_ITEM_ID.name(), featureFile.getBioDataItemId()); params.addValue(REFERENCE_GENOME_ID.name(), featureFile.getReferenceId()); params.addValue(INDEX_ID.name(), featureFile.getIndex() != null ? featureFile.getIndex().getId() : null); params.addValue(COMPRESSED.name(), featureFile.getCompressed()); if (featureFile instanceof VcfFile) { VcfFile vcfFile = (VcfFile) featureFile; params.addValue(MULTI_SAMPLE.name(), vcfFile.getMultiSample()); } if (featureFile instanceof GeneFile) { GeneFile geneFile = (GeneFile) featureFile; params.addValue(EXTERNAL_DB_TYPE_ID.name(), geneFile.getExternalDBType() != null ? geneFile.getExternalDBType().getId() : null); params.addValue(EXTERNAL_DB_ID.name(), geneFile.getExternalDB() != null ? geneFile.getExternalDB().getId() : null); params.addValue(EXTERNAL_DB_ORGANISM.name(), geneFile.getExternalDBOrganism()); } return params; } } @Required public void setInsertBiologicalDataItemQuery(String insertBiologicalDataItemQuery) { this.insertBiologicalDataItemQuery = insertBiologicalDataItemQuery; } @Required public void setLoadBiologicalDataItemsByIdsQuery(String loadBiologicalDataItemsByIdsQuery) { this.loadBiologicalDataItemsByIdsQuery = loadBiologicalDataItemsByIdsQuery; } @Required public void setBiologicalDataItemSequenceName(String biologicalDataItemSequenceName) { this.biologicalDataItemSequenceName = biologicalDataItemSequenceName; } @Required public void setDeleteBiologicalDataItemQuery(String deleteBiologicalDataItemQuery) { this.deleteBiologicalDataItemQuery = deleteBiologicalDataItemQuery; } @Required public void setLoadBiologicalDataItemsByNameStrictQuery( String loadBiologicalDataItemsByNameStrictQuery) { this.loadBiologicalDataItemsByNameStrictQuery = loadBiologicalDataItemsByNameStrictQuery; } @Required public void setLoadBiologicalDataItemsByNameQuery(String loadBiologicalDataItemsByNameQuery) { this.loadBiologicalDataItemsByNameQuery = loadBiologicalDataItemsByNameQuery; } @Required public void setLoadBiologicalDataItemsByNamesStrictQuery(String loadBiologicalDataItemsByNamesStrictQuery) { this.loadBiologicalDataItemsByNamesStrictQuery = loadBiologicalDataItemsByNamesStrictQuery; } @Required public void setLoadBiologicalDataItemsByNameCaseInsensitiveQuery( String loadBiologicalDataItemsByNameCaseInsensitiveQuery) { this.loadBiologicalDataItemsByNameCaseInsensitiveQuery = loadBiologicalDataItemsByNameCaseInsensitiveQuery; } @Required public void setUpdateOwnerQuery(String updateOwnerQuery) { this.updateOwnerQuery = updateOwnerQuery; } }
mit
mkjasinski/wsinf-books
src/test/java/com/marcinjasinski/wsinf/books/BooksApplicationTests.java
512
package com.marcinjasinski.wsinf.books; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = BooksApplication.class) @WebAppConfiguration public class BooksApplicationTests { @Test public void contextLoads() { } }
mit
kacpidev/marionext
src/Event/MarioEvent.java
155
package Event; /* * abstrakcyjna klasa bazowa dla wszystkich eventów wystêpuj¹cych w grze * * @author Kacper */ public abstract class MarioEvent { }
mit
manythumbed/laughinglen
system/src/main/java/laughinglen/domain/Root.java
1004
package laughinglen.domain; import com.google.common.collect.Lists; import laughinglen.domain.store.EventStream; import laughinglen.domain.store.Version; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.List; public abstract class Root { final List<Event> changes = Lists.newArrayList(); Version version = Version.ZERO; final void storeSucceeded(final Version stored) { version = stored; changes.clear(); } protected final void update(final EventStream stream) { version = stream.version; stream.events.forEach(this::apply); } private void apply(final Event event) { try { final Method handler = this.getClass().getDeclaredMethod("handle", event.getClass()); handler.setAccessible(true); handler.invoke(this, event); } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException ignored) { } } protected final void record(final Event event) { apply(event); changes.add(event); } }
mit
porscheinformatik/anti-mapper
src/test/java/at/porscheinformatik/antimapper/MergeIntoTreeSetTest.java
8673
package at.porscheinformatik.antimapper; import static at.porscheinformatik.antimapper.TestUtils.*; import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.*; import java.util.Collection; import java.util.Collections; import java.util.SortedSet; import java.util.TreeSet; import org.junit.Test; public class MergeIntoTreeSetTest extends AbstractMapperTest { @Test public void testNullIntoNullTreeSet() { Collection<String> dtos = null; SortedSet<char[]> entities = null; SortedSet<char[]> result = this.mergeAll(dtos, BOARDING_PASS).intoTreeSet(entities); assertThat(describeResult(result), result, nullValue()); } @Test public void testNullIntoNullTreeSetOrEmpty() { Collection<String> dtos = null; SortedSet<char[]> entities = null; SortedSet<char[]> result = this.mergeAll(dtos, BOARDING_PASS, Hint.OR_EMPTY).intoTreeSet(entities, CHAR_ARRAY_COMPARATOR); assertThat(describeResult(result), result, is(Collections.emptySortedSet())); assertThat(describeResult(result), result.comparator(), is(CHAR_ARRAY_COMPARATOR)); // check modifiable result.add("Z".toCharArray()); assertThat(describeResult(result), result, hasItem(is("Z".toCharArray()))); } @Test public void testNullIntoEmptyTreeSet() { Collection<String> dtos = null; SortedSet<char[]> entities = TestUtils.toSortedSet(CHAR_ARRAY_COMPARATOR); SortedSet<char[]> result = this.mergeAll(dtos, BOARDING_PASS).intoTreeSet(entities); assertThat(describeResult(result), result, is(Collections.emptySet())); assertThat(describeResult(result), result, sameInstance(entities)); assertThat(describeResult(result), result.comparator(), is(CHAR_ARRAY_COMPARATOR)); // check modifiable result.add("Z".toCharArray()); assertThat(describeResult(result), result, hasItem(is("Z".toCharArray()))); } @Test public void testNullIntoTreeSet() { Collection<String> dtos = null; SortedSet<char[]> entities = toSortedSet(CHAR_ARRAY_COMPARATOR, "a".toCharArray(), "a".toCharArray(), "!b".toCharArray(), "c1".toCharArray(), "c2".toCharArray(), null, null, "a".toCharArray()); SortedSet<char[]> result = this.mergeAll(dtos, BOARDING_PASS).intoTreeSet(entities); assertThat(describeResult(result), result, matchesCollection( toList(is("!a".toCharArray()), is("!b".toCharArray()), is("!c1".toCharArray()), is("!c2".toCharArray())))); assertThat(describeResult(result), result, sameInstance(entities)); assertThat(describeResult(result), result.comparator(), is(CHAR_ARRAY_COMPARATOR)); // check modifiable result.add("Z".toCharArray()); assertThat(describeResult(result), result, hasItem(is("Z".toCharArray()))); } @Test public void testIntoNullTreeSet() { Collection<String> dtos = toList("A", "C2", "C1", null, "A"); SortedSet<char[]> entities = null; SortedSet<char[]> result = this.mergeAll(dtos, BOARDING_PASS).intoTreeSet(entities, CHAR_ARRAY_COMPARATOR); assertThat(describeResult(result), result, matchesCollection(toList(is("A".toCharArray()), is("C2".toCharArray()), is("C1".toCharArray())))); assertThat(describeResult(result), result.comparator(), is(CHAR_ARRAY_COMPARATOR)); // check modifiable result.add("Z".toCharArray()); assertThat(describeResult(result), result, hasItem(is("Z".toCharArray()))); } @Test public void testEmptyIntoNullTreeSet() { Collection<String> dtos = Collections.emptyList(); SortedSet<char[]> entities = null; SortedSet<char[]> result = this.mergeAll(dtos, BOARDING_PASS).intoTreeSet(entities, CHAR_ARRAY_COMPARATOR); assertThat(describeResult(result), result, is(Collections.emptySet())); assertThat(describeResult(result), result.comparator(), is(CHAR_ARRAY_COMPARATOR)); // check modifiable result.add("Z".toCharArray()); assertThat(describeResult(result), result, hasItem(is("Z".toCharArray()))); } @Test public void testEmptyIntoEmptyTreeSet() { Collection<String> dtos = Collections.emptyList(); SortedSet<char[]> entities = new TreeSet<>(CHAR_ARRAY_COMPARATOR); SortedSet<char[]> result = this.mergeAll(dtos, BOARDING_PASS).intoTreeSet(entities); assertThat(describeResult(result), result, is(Collections.emptySet())); assertThat(describeResult(result), result, sameInstance(entities)); assertThat(describeResult(result), result.comparator(), is(CHAR_ARRAY_COMPARATOR)); // check modifiable result.add("Z".toCharArray()); assertThat(describeResult(result), result, hasItem(is("Z".toCharArray()))); } @Test public void testEmptyIntoTreeSet() { Collection<String> dtos = Collections.emptyList(); SortedSet<char[]> entities = toSortedSet(CHAR_ARRAY_COMPARATOR, "a".toCharArray(), "a".toCharArray(), "!b".toCharArray(), "c1".toCharArray(), "c2".toCharArray(), null, null, "a".toCharArray()); SortedSet<char[]> result = this.mergeAll(dtos, BOARDING_PASS).intoTreeSet(entities); assertThat(describeResult(result), result, matchesCollection( toList(is("!a".toCharArray()), is("!b".toCharArray()), is("!c1".toCharArray()), is("!c2".toCharArray())))); assertThat(describeResult(result), result, sameInstance(entities)); assertThat(describeResult(result), result.comparator(), is(CHAR_ARRAY_COMPARATOR)); // check modifiable result.add("Z".toCharArray()); assertThat(describeResult(result), result, hasItem(is("Z".toCharArray()))); } @Test public void testIntoEmptyTreeSet() { Collection<String> dtos = toList("A", "C2", "C1", null, "A"); SortedSet<char[]> entities = new TreeSet<>(CHAR_ARRAY_COMPARATOR); SortedSet<char[]> result = this.mergeAll(dtos, BOARDING_PASS).intoTreeSet(entities); assertThat(describeResult(result), result, matchesCollection(toList(is("A".toCharArray()), is("C2".toCharArray()), is("C1".toCharArray())))); assertThat(describeResult(result), result, sameInstance(entities)); assertThat(describeResult(result), result.comparator(), is(CHAR_ARRAY_COMPARATOR)); // check modifiable result.add("Z".toCharArray()); assertThat(describeResult(result), result, hasItem(is("Z".toCharArray()))); } @Test public void testIntoTreeSet() { Collection<String> dtos = toList("A", "C2", "C1", null, "A"); SortedSet<char[]> entities = toSortedSet(CHAR_ARRAY_COMPARATOR, "a".toCharArray(), "a".toCharArray(), "!b".toCharArray(), "c1".toCharArray(), "c2".toCharArray(), null, null, "a".toCharArray()); SortedSet<char[]> result = this.mergeAll(dtos, BOARDING_PASS).intoTreeSet(entities); assertThat(describeResult(result), result, matchesCollection( toList(is("A".toCharArray()), is("C2".toCharArray()), is("!b".toCharArray()), is("C1".toCharArray())))); assertThat(describeResult(result), result, sameInstance(entities)); assertThat(describeResult(result), result.comparator(), is(CHAR_ARRAY_COMPARATOR)); // check modifiable result.add("Z".toCharArray()); assertThat(describeResult(result), result, hasItem(is("Z".toCharArray()))); } @Test public void testIntoTreeSetKeepNullAndUnmodifiable() { Collection<String> dtos = toList("A", "C2", "C1", null, "A"); SortedSet<char[]> entities = Collections .unmodifiableSortedSet(toSortedSet(CHAR_ARRAY_COMPARATOR, "a".toCharArray(), "a".toCharArray(), "!b".toCharArray(), "c1".toCharArray(), "c2".toCharArray(), null, "a".toCharArray())); SortedSet<char[]> result = this.mergeAll(dtos, Hint.KEEP_NULL, Hint.UNMODIFIABLE, BOARDING_PASS).intoTreeSet(entities); assertThat(describeResult(result), result, matchesCollection(toList(is("A".toCharArray()), is("C2".toCharArray()), is("!b".toCharArray()), is("C1".toCharArray()), nullValue()))); assertThat(describeResult(result), result.comparator(), is(CHAR_ARRAY_COMPARATOR)); try { result.add("Z".toCharArray()); fail(); } catch (UnsupportedOperationException e) { // expected } } }
mit
caligin/containment-unit
src/test/java/org/anima/ptsd/ConnectionsTest.java
1957
package org.anima.ptsd; import java.net.Inet4Address; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; import org.junit.Assert; import org.junit.Test; public class ConnectionsTest { @Test public void blocksUntilAvailable() throws Exception { final InetAddress localhost = Inet4Address.getLocalHost(); final int port = availablePort(localhost); new Thread(new Runnable() { @Override public void run() { softenedSleep(1000l); ServerSocket serverSocket = null; Socket connection = null; try { serverSocket = new ServerSocket(port, 1, localhost); connection = serverSocket.accept(); } catch (Exception e) { throw new RuntimeException(e); } finally { Softening.close(connection); Softening.close(serverSocket); } } }).start(); final boolean available = Connections.awaitAvailable(localhost, port, 3, 500); Assert.assertTrue(available); } private static void softenedSleep(long intervalMillis) { try { Thread.sleep(intervalMillis); } catch (InterruptedException ex) { throw new RuntimeException(ex); } } @Test public void throwsIfNotConnectedAfterMaxRetries() throws Exception { InetAddress localhost = Inet4Address.getLocalHost(); final int port = availablePort(localhost); final boolean available = Connections.awaitAvailable(localhost, port, 1, 500); Assert.assertFalse(available); } public static int availablePort(InetAddress onInterface) throws Exception { try (ServerSocket serverSocket = new ServerSocket(0, 1, onInterface)) { return serverSocket.getLocalPort(); } } }
mit
tbepler/LRPaGe
src/bepler/lrpage/ebnf/parser/nodes/PrecDeclAbstractNode.java
810
package bepler.lrpage.ebnf.parser.nodes; import bepler.lrpage.ebnf.parser.Symbols; import bepler.lrpage.ebnf.parser.Visitor; import bepler.lrpage.ebnf.parser.framework.Node; import bepler.lrpage.ebnf.parser.framework.Symbol; /** * This class was generated by the LRPaGe parser generator v1.0 using the com.sun.codemodel library. * * <P>LRPaGe is available from https://github.com/tbepler/LRPaGe. * <P>CodeModel is available from https://codemodel.java.net/. * */ public abstract class PrecDeclAbstractNode implements Node<Visitor> { @Override public Symbol symbol() { return Symbols.PRECDECL; } @Override public PrecDeclAbstractNode replace() { return this; } @Override public String toString() { return symbol().toString(); } }
mit
avedensky/JavaRushTasks
4.JavaCollections/src/com/javarush/task/task37/task3705/Solution.java
2350
package com.javarush.task.task37.task3705; import java.util.HashMap; import java.util.Hashtable; import java.util.Map; /* Ambiguous behavior for NULL Измени реализацию метода getExpectedMap, он должен вернуть объект такого класса, для которого будет противоположное поведение при добавлении ссылки null. См. пример вывода в методе main. Остальной код не менять. Требования: 1. Метод getExpectedMap не должен возвращать объект типа Hashtable. 2. Метод getExpectedMap должен возвращать стандартную реализацию Map удовлетворяющую условию задачи. 3. Метод main класса Solution должен выводить данные на экран. 4. Метод getExpectedMap должен быть статическим. */ public class Solution { public static void main(String[] args) { Map expectedMap = getExpectedMap(); System.out.println("****** check the key \"s\" whether it IS NOT in the map"); checkObject(expectedMap, "s"); System.out.println("\n****** check the key \"s\" whether it IS in the map"); expectedMap.put("s", "vvv"); checkObject(expectedMap, "s"); System.out.println("\n****** ambiguous behavior for NULL"); expectedMap.put(null, null); checkObject(expectedMap, null); /* expected output for NULL ****** ambiguous behavior for NULL map contains the value for key = null map does NOT contain the value for key = null */ } public static Map getExpectedMap() { return new HashMap(); } public static void checkObject(Map map, Object key) { String s1 = map.containsKey(key) ? "map contains the value for key = " + key : "map does NOT contain the value for key = " + key; System.out.println(s1); //if value is null, it means that the map doesn't contain the value Object value = map.get(key); String s2 = value != null ? "map contains the value for key = " + key : "map does NOT contain the value for key = " + key; System.out.println(s2); } }
mit
a2800276/javautils
crypto/test/util/crypto/KeyPairTest.java
2245
package util.crypto; import org.testng.annotations.Test; import java.io.ByteArrayInputStream; import java.security.interfaces.RSAPrivateCrtKey; import static org.testng.Assert.*; /** * Test KeyPair s * Created by a2800276 on 2015-11-02. */ public class KeyPairTest { // @Test // public void testExtractRSAPublicFromPrivate() throws Exception { // java.security.KeyPair pair = KeyPair.generateKeyPair(KeyPair.Algorithm.RSA); // KeyPair.PrivateKey pk = new KeyPair.PrivateKey(pair.getPrivate()); // KeyPair.PublicKey pub = pk.getPublicKey(); // assertEquals(pair.getPublic(), pub.pub); // } // @Test public void testStore() throws Exception { // KeyPair pair = KeyPair.generateKeyPair(KeyPair.Algorithm.RSA); // FileOutputStream fos = new FileOutputStream("tim.x509"); // pair.getPublicKey().storeX509(fos); // } @Test public void testDSALong() throws Exception { KeyPair pair = KeyPair.generateDSAKeyPair(Constants.DSA_DEFAULT_KEYSIZE * 2); byte[] mes = {}; Signature.sign(Signature.Algorithm.SHA1withDSA, pair.getPrivateKey(), mes); } @Test public void smallRSAKey() throws Exception { KeyPair pair = KeyPair.generateRSAKeyPair(512); } @Test public void testExtractPublicRSAFromPrivate() throws Exception { KeyPair pair = KeyPair.generateRSAKeyPair(512); assertEquals(KeyPair.getPublicKeyFromRSACRTPrivateKey((RSAPrivateCrtKey) pair.getPrivateKey().getJCAPrivateKey()), pair.getPublicKey().getJCAPublicKey()); } @Test public void testLoadPrivateKeyFromPKCS8() throws Exception { KeyPair pair = KeyPair.generateKeyPair(KeyPair.Algorithm.P256); byte[] pkcs8 = pair.getPrivateKey().toPKCS8(); ByteArrayInputStream is = new ByteArrayInputStream(pkcs8); KeyPair.PrivateKey pk = KeyPair.PrivateKey.loadPKCS8(is); } @Test public void testConstructorBytes() throws Exception { KeyPair pair = KeyPair.generateKeyPair(KeyPair.Algorithm.P521); KeyPair pair2 = KeyPair.generateKeyPair(KeyPair.Algorithm.P521); KeyPair pair3 = new KeyPair(pair.getPrivateKey().toPKCS8(), pair.getPublicKey().toX509()); assertTrue(pair.equals(pair3)); assertTrue(pair3.equals(pair)); assertTrue(pair.equals(pair)); assertNotEquals(pair, pair2); } }
mit
georghinkel/ttc2017smartGrids
solutions/ModelJoin/src/main/java/COSEM/COSEMObjects/impl/MaxCreditLimitImpl.java
3502
/** */ package COSEM.COSEMObjects.impl; import COSEM.COSEMObjects.COSEMObjectsPackage; import COSEM.COSEMObjects.MaxCreditLimit; import COSEM.InterfaceClasses.impl.DataImpl; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.impl.ENotificationImpl; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Max Credit Limit</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * </p> * <ul> * <li>{@link COSEM.COSEMObjects.impl.MaxCreditLimitImpl#getValue <em>Value</em>}</li> * </ul> * * @generated */ public class MaxCreditLimitImpl extends DataImpl implements MaxCreditLimit { /** * The default value of the '{@link #getValue() <em>Value</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getValue() * @generated * @ordered */ protected static final double VALUE_EDEFAULT = 0.0; /** * The cached value of the '{@link #getValue() <em>Value</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getValue() * @generated * @ordered */ protected double value = VALUE_EDEFAULT; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected MaxCreditLimitImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return COSEMObjectsPackage.eINSTANCE.getMaxCreditLimit(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public double getValue() { return value; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setValue(double newValue) { double oldValue = value; value = newValue; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, COSEMObjectsPackage.MAX_CREDIT_LIMIT__VALUE, oldValue, value)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case COSEMObjectsPackage.MAX_CREDIT_LIMIT__VALUE: return getValue(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case COSEMObjectsPackage.MAX_CREDIT_LIMIT__VALUE: setValue((Double)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case COSEMObjectsPackage.MAX_CREDIT_LIMIT__VALUE: setValue(VALUE_EDEFAULT); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case COSEMObjectsPackage.MAX_CREDIT_LIMIT__VALUE: return value != VALUE_EDEFAULT; } return super.eIsSet(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (value: "); result.append(value); result.append(')'); return result.toString(); } } //MaxCreditLimitImpl
mit
SoftwareEngineeringToolDemos/FSE-2012-FaultTracer
src/tracer/faultlocalization/ui/AffectedTestLabelProvider.java
1070
package tracer.faultlocalization.ui; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jface.viewers.IBaseLabelProvider; import org.eclipse.jface.viewers.ILabelProvider; import org.eclipse.jface.viewers.ILabelProviderListener; import org.eclipse.jface.viewers.ITableLabelProvider; import org.eclipse.swt.graphics.Image; public class AffectedTestLabelProvider implements ITableLabelProvider { @Override public void addListener(ILabelProviderListener listener) { } @Override public void dispose() { } @Override public boolean isLabelProperty(Object element, String property) { return false; } @Override public void removeListener(ILabelProviderListener listener) { } @Override public Image getColumnImage(Object element, int columnIndex) { // TODO Auto-generated method stub return null; } @Override public String getColumnText(Object element, int columnIndex) { if (element instanceof String) { if (columnIndex == 0) return (String)element; } return null; } }
mit
recursosCSWuniandes/research
book-store-api/src/main/java/co/edu/uniandes/csw/bookstore/dtos/minimum/BookMinimumDTO.java
4017
/* The MIT License (MIT) Copyright (c) 2015 Los Andes University Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package co.edu.uniandes.csw.bookstore.dtos.minimum; import co.edu.uniandes.csw.bookstore.entities.BookEntity; import javax.xml.bind.annotation.XmlRootElement; import java.util.Date; import uk.co.jemos.podam.common.PodamStrategyValue; import co.edu.uniandes.csw.crud.api.podam.strategy.DateStrategy; import java.io.Serializable; /** * @generated */ @XmlRootElement public class BookMinimumDTO implements Serializable{ private Long id; private String name; private String description; private String isbn; private String image; @PodamStrategyValue(DateStrategy.class) private Date publishDate; /** * @generated */ public BookMinimumDTO() { } /** * @param entity * @generated */ public BookMinimumDTO(BookEntity entity) { if (entity!=null){ this.id=entity.getId(); this.name=entity.getName(); this.description=entity.getDescription(); this.isbn=entity.getIsbn(); this.image=entity.getImage(); this.publishDate=entity.getPublishDate(); } } /** * @generated */ public BookEntity toEntity() { BookEntity entity = new BookEntity(); entity.setId(this.getId()); entity.setName(this.getName()); entity.setDescription(this.getDescription()); entity.setIsbn(this.getIsbn()); entity.setImage(this.getImage()); entity.setPublishDate(this.getPublishDate()); return entity; } /** * @return the id */ public Long getId() { return id; } /** * @param id the id to set */ public void setId(Long id) { this.id = id; } /** * @return the name */ public String getName() { return name; } /** * @param name the name to set */ public void setName(String name) { this.name = name; } /** * @return the description */ public String getDescription() { return description; } /** * @param description the description to set */ public void setDescription(String description) { this.description = description; } /** * @return the isbn */ public String getIsbn() { return isbn; } /** * @param isbn the isbn to set */ public void setIsbn(String isbn) { this.isbn = isbn; } /** * @return the image */ public String getImage() { return image; } /** * @param image the image to set */ public void setImage(String image) { this.image = image; } /** * @return the publishDate */ public Date getPublishDate() { return publishDate; } /** * @param publishDate the publishDate to set */ public void setPublishDate(Date publishdate) { this.publishDate = publishdate; } }
mit
JoshuaKissoon/Kademlia
src/kademlia/message/ContentLookupMessage.java
1736
package kademlia.message; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import kademlia.dht.GetParameter; import kademlia.node.Node; import kademlia.util.serializer.JsonSerializer; /** * Messages used to send to another node requesting content. * * @author Joshua Kissoon * @since 20140226 */ public class ContentLookupMessage implements Message { public static final byte CODE = 0x03; private Node origin; private GetParameter params; /** * @param origin The node where this lookup came from * @param params The parameters used to find the content */ public ContentLookupMessage(Node origin, GetParameter params) { this.origin = origin; this.params = params; } public ContentLookupMessage(DataInputStream in) throws IOException { this.fromStream(in); } public GetParameter getParameters() { return this.params; } public Node getOrigin() { return this.origin; } @Override public void toStream(DataOutputStream out) throws IOException { this.origin.toStream(out); /* Write the params to the stream */ new JsonSerializer<GetParameter>().write(this.params, out); } @Override public final void fromStream(DataInputStream in) throws IOException { this.origin = new Node(in); /* Read the params from the stream */ try { this.params = new JsonSerializer<GetParameter>().read(in); } catch (ClassNotFoundException e) { e.printStackTrace(); } } @Override public byte code() { return CODE; } }
mit
Neofonie/cinderella
cinderella-core/src/main/java/de/neofonie/cinderella/core/config/util/IpAddressRangeTypeAdapter.java
1573
/* * * The MIT License (MIT) * Copyright (c) 2016 Neofonie GmbH * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ package de.neofonie.cinderella.core.config.util; import javax.xml.bind.annotation.adapters.XmlAdapter; public class IpAddressRangeTypeAdapter extends XmlAdapter<String, IpAddressRange> { @Override public IpAddressRange unmarshal(String v) throws Exception { return IpAddressRange.valueOf(v); } @Override public String marshal(IpAddressRange v) throws Exception { return v.toString(); } }
mit
bing-ads-sdk/BingAds-Java-SDK
src/test/java/com/microsoft/bingads/v12/api/test/entities/ad_group_product_partition/write/WriteFinalMobileUrlsTest.java
2152
package com.microsoft.bingads.v12.api.test.entities.ad_group_product_partition.write; import java.util.Arrays; import java.util.Collection; import org.junit.Test; import org.junit.runners.Parameterized.Parameter; import org.junit.runners.Parameterized.Parameters; import com.microsoft.bingads.internal.functionalinterfaces.BiConsumer; import com.microsoft.bingads.v12.api.test.entities.ad_group_product_partition.BulkAdGroupProductPartitionTest; import com.microsoft.bingads.v12.bulk.entities.BulkAdGroupProductPartition; import com.microsoft.bingads.v12.campaignmanagement.ArrayOfstring; import com.microsoft.bingads.v12.campaignmanagement.BiddableAdGroupCriterion; import com.microsoft.bingads.v12.campaignmanagement.ProductPartition; public class WriteFinalMobileUrlsTest extends BulkAdGroupProductPartitionTest { @Parameter(value = 1) public ArrayOfstring propertyValue; @Parameters public static Collection<Object[]> data() { ArrayOfstring array = new ArrayOfstring(); array.getStrings().addAll(Arrays.asList(new String[] { "http://www.test 1.com", "https://www.test2.com" })); return Arrays.asList(new Object[][]{ {null, null}, {"delete_value", new ArrayOfstring()}, {"http://www.test 1.com; https://www.test2.com", array}, }); } @Test public void testWrite() { testWriteProperty( "Final Url", datum, propertyValue, new BiConsumer<BulkAdGroupProductPartition, ArrayOfstring>() { @Override public void accept(BulkAdGroupProductPartition c, ArrayOfstring v) { ProductPartition criterion = new ProductPartition(); BiddableAdGroupCriterion adGroupCriterion = new BiddableAdGroupCriterion(); adGroupCriterion.setId(100L); adGroupCriterion.setCriterion(criterion); c.setAdGroupCriterion(adGroupCriterion); adGroupCriterion.setFinalUrls(v); } } ); } }
mit
teunvanvegchel/AP-Refactoring
src/test/java/nl/han/ica/app/models/CodeEditorTest.java
1233
package nl.han.ica.app.models; import javafx.scene.web.WebView; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.MockitoAnnotations; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import static org.powermock.api.mockito.PowerMockito.doNothing; /** * @author: Wouter Konecny * @created: 26-10-12 */ @RunWith(PowerMockRunner.class) @PrepareForTest(WebView.class) public class CodeEditorTest { private CodeEditor codeEditor = null; private WebView webView; @Before public void setUp() throws Exception { webView = PowerMockito.mock(WebView.class); codeEditor = PowerMockito.mock(CodeEditor.class); doNothing().when(codeEditor).initializeWebView(); } @Test public void testSetValue() throws Exception { codeEditor.setValue("x"); } @Test public void testHighlightLine() throws Exception { codeEditor.highlightLine(1, "MyClass", "MyClass"); } @Test public void testHighlightText() throws Exception { codeEditor.highlightText(1, 2, 3, 4, "MyClass"); } }
mit
ivanshen/Who-Are-You-Really
org/jfree/chart/renderer/xy/XYDotRenderer.java
6226
package org.jfree.chart.renderer.xy; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.Shape; import java.awt.geom.Rectangle2D; import java.awt.geom.Rectangle2D.Double; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import org.jfree.chart.LegendItem; import org.jfree.chart.axis.DateAxis; import org.jfree.chart.axis.ValueAxis; import org.jfree.chart.plot.CrosshairState; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.PlotRenderingInfo; import org.jfree.chart.plot.XYPlot; import org.jfree.chart.util.ParamChecks; import org.jfree.data.xy.XYDataset; import org.jfree.io.SerialUtilities; import org.jfree.ui.RectangleEdge; import org.jfree.util.PublicCloneable; import org.jfree.util.ShapeUtilities; public class XYDotRenderer extends AbstractXYItemRenderer implements XYItemRenderer, PublicCloneable { private static final long serialVersionUID = -2764344339073566425L; private int dotHeight; private int dotWidth; private transient Shape legendShape; public XYDotRenderer() { this.dotWidth = 1; this.dotHeight = 1; this.legendShape = new Double(-3.0d, -3.0d, 6.0d, 6.0d); } public int getDotWidth() { return this.dotWidth; } public void setDotWidth(int w) { if (w < 1) { throw new IllegalArgumentException("Requires w > 0."); } this.dotWidth = w; fireChangeEvent(); } public int getDotHeight() { return this.dotHeight; } public void setDotHeight(int h) { if (h < 1) { throw new IllegalArgumentException("Requires h > 0."); } this.dotHeight = h; fireChangeEvent(); } public Shape getLegendShape() { return this.legendShape; } public void setLegendShape(Shape shape) { ParamChecks.nullNotPermitted(shape, "shape"); this.legendShape = shape; fireChangeEvent(); } public void drawItem(Graphics2D g2, XYItemRendererState state, Rectangle2D dataArea, PlotRenderingInfo info, XYPlot plot, ValueAxis domainAxis, ValueAxis rangeAxis, XYDataset dataset, int series, int item, CrosshairState crosshairState, int pass) { if (getItemVisible(series, item)) { double x = dataset.getXValue(series, item); double y = dataset.getYValue(series, item); double adjx = ((double) (this.dotWidth - 1)) / DateAxis.DEFAULT_AUTO_RANGE_MINIMUM_SIZE_IN_MILLISECONDS; double adjy = ((double) (this.dotHeight - 1)) / DateAxis.DEFAULT_AUTO_RANGE_MINIMUM_SIZE_IN_MILLISECONDS; if (!Double.isNaN(y)) { RectangleEdge xAxisLocation = plot.getDomainAxisEdge(); double transX = domainAxis.valueToJava2D(x, dataArea, xAxisLocation) - adjx; double transY = rangeAxis.valueToJava2D(y, dataArea, plot.getRangeAxisEdge()) - adjy; g2.setPaint(getItemPaint(series, item)); PlotOrientation orientation = plot.getOrientation(); if (orientation == PlotOrientation.HORIZONTAL) { g2.fillRect((int) transY, (int) transX, this.dotHeight, this.dotWidth); } else if (orientation == PlotOrientation.VERTICAL) { g2.fillRect((int) transX, (int) transY, this.dotWidth, this.dotHeight); } updateCrosshairValues(crosshairState, x, y, plot.getDomainAxisIndex(domainAxis), plot.getRangeAxisIndex(rangeAxis), transX, transY, orientation); } } } public LegendItem getLegendItem(int datasetIndex, int series) { LegendItem legendItem = null; XYPlot plot = getPlot(); if (plot != null) { XYDataset dataset = plot.getDataset(datasetIndex); if (dataset != null) { legendItem = null; if (getItemVisible(series, 0)) { String label = getLegendItemLabelGenerator().generateLabel(dataset, series); String description = label; String toolTipText = null; if (getLegendItemToolTipGenerator() != null) { toolTipText = getLegendItemToolTipGenerator().generateLabel(dataset, series); } String urlText = null; if (getLegendItemURLGenerator() != null) { urlText = getLegendItemURLGenerator().generateLabel(dataset, series); } legendItem = new LegendItem(label, description, toolTipText, urlText, getLegendShape(), lookupSeriesPaint(series)); legendItem.setLabelFont(lookupLegendTextFont(series)); Paint labelPaint = lookupLegendTextPaint(series); if (labelPaint != null) { legendItem.setLabelPaint(labelPaint); } legendItem.setSeriesKey(dataset.getSeriesKey(series)); legendItem.setSeriesIndex(series); legendItem.setDataset(dataset); legendItem.setDatasetIndex(datasetIndex); } } } return legendItem; } public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof XYDotRenderer)) { return false; } XYDotRenderer that = (XYDotRenderer) obj; if (this.dotWidth == that.dotWidth && this.dotHeight == that.dotHeight && ShapeUtilities.equal(this.legendShape, that.legendShape)) { return super.equals(obj); } return false; } public Object clone() throws CloneNotSupportedException { return super.clone(); } private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); this.legendShape = SerialUtilities.readShape(stream); } private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); SerialUtilities.writeShape(this.legendShape, stream); } }
mit
tragabuches/eplerratas
source/vista/propiedadesgui/ClavesGui.java
1474
package epublibre.eplerratas.vista.propiedadesgui; /** * * @author ePubLibre */ public enum ClavesGui { /** * */ APP_POSICION_X(-1), /** * */ APP_POSICION_Y(-1), /** * */ APP_TAMANO_X(640), /** * */ APP_TAMANO_Y(480), /** * */ PRI_DIVISOR_INFORME_PREVIA(320), /** * */ EDI_VER_INFORME(1), /** * */ EDI_VER_SECCION(1), /** * */ EDI_DIVISOR_TABLA_MARCA(250), /** * */ EDI_DIVISOR_INFORME_MARCA(150), /** * */ EDI_PANEL_LISTA_ANCHO(149), /** * */ EDI_DIVISOR_INFORME_SECCION(230), /** * */ EDI_LISTA_INFORME_ALTO(229), /** * */ EDI_LISTA_SECCION_ALTO(229), /** * */ CON_IMP_VER_PLANTILLA(1), /** * */ CON_IMP_DIVISOR_PLANTILLA(200), /** * */ CON_IMP_DIVISOR_PREVIA_INFORME(200), /** * */ CON_IMP_DIVISOR_PLANTILLA_PREVIA(240), /** * */ CON_EXP_DIVISOR_PLANTILLA(200), /** * */ CON_EXP_DIVISOR_PLANTILLA_PREVIA(240); private final int predefinido; private ClavesGui(int valor) { predefinido = valor; } /** * * @return */ public int predefinido() { return predefinido; } }
mit
jhannes/openright-conferencer
src/main/java/net/openright/conferencer/domain/comments/DatabaseCommentRepository.java
1203
package net.openright.conferencer.domain.comments; import java.util.List; import net.openright.conferencer.domain.talks.TalkComment; import net.openright.infrastructure.db.Database; import net.openright.lib.db.DatabaseTable; public class DatabaseCommentRepository implements CommentRepository { private DatabaseTable table; public DatabaseCommentRepository(Database database) { table = new DatabaseTable(database, "talk_comments"); } @Override public long save(Comment comment) { comment.setId(table.insert(row -> { row.put("talk_id", comment.getTalkId()); row.put("title", comment.getTitle()); row.put("content", comment.getContent()); row.put("author", comment.getAuthor()); })); return comment.getId(); } public List<TalkComment> listTalkComments(Long talkId) { return table.where("talk_id", talkId).orderBy("id").list(row -> { TalkComment comment = new TalkComment(); comment.setTitle(row.getString("title")); comment.setAuthor(row.getString("author")); return comment; }); } }
mit
SBeausoleil/Pathfinder-Kingdom-Ruler
Pathfinder Kingdom Ruler/src/com/sb/pathfinder/kingdom/TaxationEdict.java
630
package com.sb.pathfinder.kingdom; public enum TaxationEdict implements KingdomModifier { NONE(0, 1), LIGHT(1, -1), NORMAL(2, -2), HEAVY(3, -4), OVERWHELMING(4, -8); private int economy; private int loyalty; private TaxationEdict(int economy, int loyalty) { this.economy = economy; this.loyalty = loyalty; } @Override public void applyTo(Kingdom kingdom) { kingdom.modEconomy(economy); kingdom.modLoyalty(loyalty); } @Override public void removeFrom(Kingdom kingdom) { kingdom.modEconomy(-economy); kingdom.modLoyalty(-loyalty); } }
mit
EDACC/edacc_gui
src/edacc/manageDB/SolverBinariesTableSelectionListener.java
842
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package edacc.manageDB; import javax.swing.JTable; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; /** * * @author dgall */ public class SolverBinariesTableSelectionListener implements ListSelectionListener { private JTable table; private ManageDBSolvers controller; public SolverBinariesTableSelectionListener(JTable table, ManageDBSolvers controller) { this.table = table; this.controller = controller; } @Override public void valueChanged(ListSelectionEvent e) { if (e.getSource() == table.getSelectionModel() && table.getRowSelectionAllowed()) { controller.selectSolverBinary(table.getSelectedRow() != -1); } } }
mit
MatthijsKamstra/haxejava
04lwjgl/code/lwjgl/org/lwjgl/opengles/EXTTextureFormatBGRA8888.java
2318
/* * Copyright LWJGL. All rights reserved. * License terms: http://lwjgl.org/license.php * MACHINE GENERATED FILE, DO NOT EDIT */ package org.lwjgl.opengles; /** * Native bindings to the <a href="https://www.khronos.org/registry/gles/extensions/EXT/EXT_texture_format_BGRA8888.txt">EXT_texture_format_BGRA8888</a> extension. * * <p>This extension provides an additional format and type combination for use when specifying texture data. The current allowed combinations are:</p> * * <pre><code> Internal Format External Format Type Bytes per Pixel --------------- --------------- ---- --------------- RGBA RGBA UNSIGNED_BYTE 4 RGB RGB UNSIGNED_BYTE 3 RGBA RGBA UNSIGNED_SHORT_4_4_4_4 2 RGBA RGBA UNSIGNED_SHORT_5_5_5_1 2 RGB RGB UNSIGNED_SHORT_5_6_5 2 LUMINANCE_ALPHA LUMINANCE_ALPHA UNSIGNED_BYTE 2 LUMINANCE LUMINANCE UNSIGNED_BYTE 1 ALPHA ALPHA UNSIGNED_BYTE 1</code></pre> * * <p>This table is extended to include format BGRA_EXT and type UNSIGNED_BYTE:</p> * * <pre><code>Internal Format External Format Type Bytes per Pixel --------------- --------------- ---- --------------- BGRA_EXT BGRA_EXT UNSIGNED_BYTE 4 RGBA RGBA UNSIGNED_BYTE 4 RGB RGB UNSIGNED_BYTE 3 RGBA RGBA UNSIGNED_SHORT_4_4_4_4 2 RGBA RGBA UNSIGNED_SHORT_5_5_5_1 2 RGB RGB UNSIGNED_SHORT_5_6_5 2 LUMINANCE_ALPHA LUMINANCE_ALPHA UNSIGNED_BYTE 2 LUMINANCE LUMINANCE UNSIGNED_BYTE 1 ALPHA ALPHA UNSIGNED_BYTE 1</code></pre> */ public final class EXTTextureFormatBGRA8888 { /** Accepted by the {@code format} and {@code internalformat} parameters of TexImage2D and the {@code format} parameter of TexSubImage2D. */ public static final int GL_BGRA_EXT = 0x80E1; private EXTTextureFormatBGRA8888() {} }
mit
CSSE497/pathfinder-webserver
app/models/PermissionKey.java
775
package models; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Embeddable; @Embeddable public class PermissionKey implements Serializable { public String email; @Column(name = "application_id") public String applicationId; @Override public int hashCode() { return (email == null ? 0 : email.hashCode()) + (applicationId == null ? 0 : applicationId.hashCode()); } @Override public boolean equals(Object other) { if (other instanceof PermissionKey) { PermissionKey otherKey = (PermissionKey) other; return email.equals(otherKey.email) && applicationId.equals(otherKey.applicationId); } else { return false; } } }
mit
Ananasr/The-Watcher
src/main/java/agent/User.java
2739
package agent; import jade.core.AID; import jade.core.Agent; import jade.core.behaviours.CyclicBehaviour; import jade.core.behaviours.OneShotBehaviour; import jade.core.behaviours.SimpleBehaviour; import jade.lang.acl.ACLMessage; import jade.tools.sniffer.Message; import java.io.BufferedReader; import java.io.InputStreamReader; /** * RMA : Remote Management Agent which handles the GUI interface. * AMS : Agent Management Service - the core agent which keeps track of all JADE programs and agents in the system. * DF : Directory Facility, a yellow page service, where agents can publish their services. */ public class User extends Agent { @Override protected void setup() { addBehaviour(new OneShotBehaviour(this) { private boolean finished = true; /** * This action call periodically 'logwatch' command * and send the output to the User. */ @Override public void action() { // Send message to admin //message.setLanguage("English"); //message.setContent(executeCommand("logwatch --level high")); ACLMessage message = new ACLMessage(ACLMessage.INFORM); message.addReceiver(new AID("admin", AID.ISLOCALNAME)); message.setContent("Hello"); send(message); // ... this is where the real programming goes !! ACLMessage receive = myAgent.receive(); if (receive != null) { // process the received message System.out.println("Receive message : " + receive.getContent()); } else { // block the behaviour while receiving message System.out.println("block"); block(); } } }); } /** * Execute command * * @param command to execute * @return output of the command */ private String executeCommand(String command) { StringBuilder output = new StringBuilder(); Process p; try { p = Runtime.getRuntime().exec(command); p.waitFor(); BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream())); String line = ""; while ((line = reader.readLine()) != null) { output.append(line + "\n"); } } catch (Exception e) { e.printStackTrace(); } return output.toString(); } public static void main(String[] args) { // write your code here System.out.println("Main !!!"); } }
mit
bcvsolutions/CzechIdMng
Realization/backend/acc/src/main/java/eu/bcvsolutions/idm/acc/service/impl/DefaultAccIdentityAccountService.java
6619
package eu.bcvsolutions.idm.acc.service.impl; import java.util.List; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Join; import javax.persistence.criteria.JoinType; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.Assert; import com.google.common.collect.ImmutableMap; import eu.bcvsolutions.idm.acc.domain.AccGroupPermission; import eu.bcvsolutions.idm.acc.dto.AccIdentityAccountDto; import eu.bcvsolutions.idm.acc.dto.filter.AccIdentityAccountFilter; import eu.bcvsolutions.idm.acc.entity.AccAccount_; import eu.bcvsolutions.idm.acc.entity.AccIdentityAccount; import eu.bcvsolutions.idm.acc.entity.AccIdentityAccount_; import eu.bcvsolutions.idm.acc.entity.SysRoleSystem_; import eu.bcvsolutions.idm.acc.entity.SysSystem_; import eu.bcvsolutions.idm.acc.event.IdentityAccountEvent; import eu.bcvsolutions.idm.acc.event.IdentityAccountEvent.IdentityAccountEventType; import eu.bcvsolutions.idm.acc.repository.AccIdentityAccountRepository; import eu.bcvsolutions.idm.acc.service.api.AccIdentityAccountService; import eu.bcvsolutions.idm.core.api.service.AbstractEventableDtoService; import eu.bcvsolutions.idm.core.api.service.EntityEventManager; import eu.bcvsolutions.idm.core.model.entity.IdmIdentityRole; import eu.bcvsolutions.idm.core.model.entity.IdmIdentityRole_; import eu.bcvsolutions.idm.core.model.entity.IdmIdentity_; import eu.bcvsolutions.idm.core.model.entity.IdmRole_; import eu.bcvsolutions.idm.core.security.api.domain.BasePermission; import eu.bcvsolutions.idm.core.security.api.dto.AuthorizableType; /** * Identity accounts on target system * * @author Radek Tomiška * @author Svanda * */ @Service("accIdentityAccountService") public class DefaultAccIdentityAccountService extends AbstractEventableDtoService<AccIdentityAccountDto, AccIdentityAccount, AccIdentityAccountFilter> implements AccIdentityAccountService { private static final org.slf4j.Logger LOG = org.slf4j.LoggerFactory.getLogger(DefaultAccIdentityAccountService.class); private final EntityEventManager entityEventManager; @Autowired public DefaultAccIdentityAccountService( AccIdentityAccountRepository identityAccountRepository, EntityEventManager entityEventManager) { super(identityAccountRepository, entityEventManager); // Assert.notNull(entityEventManager, "Manager is required."); Assert.notNull(identityAccountRepository, "Repository is required."); // this.entityEventManager = entityEventManager; } @Override public AuthorizableType getAuthorizableType() { return new AuthorizableType(AccGroupPermission.IDENTITYACCOUNT, getEntityClass()); } @Override public AccIdentityAccountDto save(AccIdentityAccountDto dto, BasePermission... permission) { Assert.notNull(dto, "DTO is required."); checkAccess(toEntity(dto, null), permission); // LOG.debug("Saving identity-account [{}]", dto); // if (isNew(dto)) { // create return entityEventManager.process(new IdentityAccountEvent(IdentityAccountEventType.CREATE, dto)).getContent(); } return entityEventManager.process(new IdentityAccountEvent(IdentityAccountEventType.UPDATE, dto)).getContent(); } @Override @Transactional public void delete(AccIdentityAccountDto dto, BasePermission... permission) { this.delete(dto, true, permission); } @Override @Transactional public void delete(AccIdentityAccountDto entity, boolean deleteTargetAccount, BasePermission... permission) { this.delete(entity, deleteTargetAccount, false, permission); } @Override @Transactional public void forceDelete(AccIdentityAccountDto dto, BasePermission... permission) { this.delete(dto, true, true, permission); } private void delete(AccIdentityAccountDto entity, boolean deleteTargetAccount, boolean forceDelete, BasePermission... permission) { Assert.notNull(entity, "Entity is required."); checkAccess(this.getEntity(entity.getId()), permission); // LOG.debug("Deleting identity account [{}]", entity); entityEventManager.process(new IdentityAccountEvent(IdentityAccountEventType.DELETE, entity, ImmutableMap.of(AccIdentityAccountService.DELETE_TARGET_ACCOUNT_KEY, deleteTargetAccount, AccIdentityAccountService.FORCE_DELETE_OF_IDENTITY_ACCOUNT_KEY, forceDelete))); } @Override protected List<Predicate> toPredicates(Root<AccIdentityAccount> root, CriteriaQuery<?> query, CriteriaBuilder builder, AccIdentityAccountFilter filter) { List<Predicate> predicates = super.toPredicates(root, query, builder, filter); // if (filter.getAccountId() != null) { predicates.add(builder.equal(root.get(AccIdentityAccount_.account).get(AccAccount_.id), filter.getAccountId())); } if (filter.getUid() != null) { predicates.add(builder.equal(root.get(AccIdentityAccount_.account).get(AccAccount_.uid), filter.getUid())); } if (filter.getSystemId() != null) { predicates.add(builder.equal(root.get(AccIdentityAccount_.account).get(AccAccount_.system).get(SysSystem_.id), filter.getSystemId())); } if (filter.getIdentityId() != null) { predicates.add(builder.equal(root.get(AccIdentityAccount_.identity).get(IdmIdentity_.id), filter.getIdentityId())); } if (filter.getRoleId() != null || filter.getIdentityRoleId() != null) { Join<AccIdentityAccount, IdmIdentityRole> identityRole = root.join(AccIdentityAccount_.identityRole, JoinType.LEFT); if (filter.getRoleId() != null) { predicates.add(builder.equal(identityRole.get(IdmIdentityRole_.role).get(IdmRole_.id), filter.getRoleId())); } if (filter.getIdentityRoleId() != null) { predicates.add(builder.equal(identityRole.get(IdmIdentityRole_.id), filter.getIdentityRoleId())); } } if (filter.getRoleSystemId() != null) { predicates.add(builder.equal(root.get(AccIdentityAccount_.roleSystem).get(SysRoleSystem_.id), filter.getRoleSystemId())); } if (filter.isOwnership() != null) { predicates.add(builder.equal(root.get(AccIdentityAccount_.ownership), filter.isOwnership())); } if (filter.getNotIdentityAccount() != null) { predicates.add(builder.notEqual(root.get(AccIdentityAccount_.id), filter.getNotIdentityAccount())); } if (filter.getIdentityRoleIds() != null) { predicates.add(root.get(AccIdentityAccount_.identityRole).get(IdmIdentityRole_.id).in(filter.getIdentityRoleIds())); } // return predicates; } }
mit
xmaxing/RxTwitch_MVP_Dagger
pircbotx-2.1/src/main/java/org/pircbotx/hooks/types/GenericUserEvent.java
1252
/** * Copyright (C) 2010-2014 Leon Blakey <lord.quackstar at gmail.com> * * This file is part of PircBotX. * * PircBotX is free software: you can redistribute it and/or modify it under the * terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * PircBotX is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with * PircBotX. If not, see <http://www.gnu.org/licenses/>. */ package org.pircbotx.hooks.types; import org.pircbotx.UserHostmask; import org.pircbotx.User; /** * * @author Leon Blakey */ public interface GenericUserEvent extends GenericEvent { /** * The source user hostmask that generated the event. * * @return The hostmask of the user */ public UserHostmask getUserHostmask(); /** * The source user that generated the event. * * @return The user or null if the hostmask didn't match a user at creation * time */ public User getUser(); }
mit
keenezhu/MaoMao
MaoMao/src/ustc/maomao/patterns/abstractfac/CrystalPie.java
779
package ustc.maomao.patterns.abstractfac; import ustc.maomao.patterns.support.Data; /** * @author Keene. Mail: waterzhj@ustc.edu.cn * * 该代码遵循MIT License, 详细见 https://mit-license.org/ * * Copyright {2017} {Keene} * * designed by Keene, implemented by {Keene} * * 水晶风格的饼状图 * */ public class CrystalPie extends Pie { private Data data; /* (non-Javadoc) * @see ustc.maomao.patterns.abstractfac.Pie#draw() */ @Override public void draw() { // TODO Auto-generated method stub System.out.println("绘制水晶样式的饼状图..."); } /** * @param data the data to set */ public void setData(Data data) { this.data = data; } }
mit
sherter/google-java-format-gradle-plugin
src/main/java/com/github/sherter/googlejavaformatgradleplugin/FileToStateMapper.java
4663
package com.github.sherter.googlejavaformatgradleplugin; import com.google.common.base.Function; import com.google.common.collect.ImmutableListMultimap; import com.google.common.collect.Iterators; import com.google.common.collect.Multimaps; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.attribute.FileTime; import java.util.ConcurrentModificationException; import java.util.Iterator; import java.util.concurrent.ConcurrentHashMap; import org.gradle.api.logging.Logger; import org.gradle.api.logging.Logging; /** Map files to their {@link FileState}. Designed for concurrent use in multiple threads. */ class FileToStateMapper implements Iterable<FileInfo> { private static final Logger log = Logging.getLogger(FileToStateMapper.class); private final ConcurrentHashMap<Path, FileInfo> infoCache = new ConcurrentHashMap<>(); private final Object replaceRemoveLock = new Object(); private final Function<Path, FileState> mapFunction = new Function<Path, FileState>() { @Override public FileState apply(Path path) { return map(path); } }; /** * Associate {@code files} with their {@link FileState}. * * @see #map(Path) */ ImmutableListMultimap<FileState, Path> reverseMap(Iterable<Path> files) { return Multimaps.index(files, mapFunction); } /** * Checks if we have information about the given {@code file} and returns the associated {@link * FileState} if this information is still valid. Otherwise returns {@link FileState#UNKNOWN}. * * <p>The information is valid if {@link FileInfo#lastModified()} and {@link FileInfo#size()} * equals the {@code file}'s current size and last modified time. This method always tries to * access the file system to verify this. Returns {@link FileState#UNKNOWN} if accessing the file * system fails. */ FileState map(Path file) { file = file.toAbsolutePath().normalize(); FileInfo info = infoCache.get(file); if (info == null) { return FileState.UNKNOWN; } FileTime currentLastModified; long currentSize; try { currentLastModified = Files.getLastModifiedTime(file); currentSize = Files.size(file); } catch (IOException e) { return FileState.UNKNOWN; } if (info.lastModified().equals(currentLastModified) && info.size() == currentSize) { return info.state(); } log.debug("change detected; invalidating cached state for file '{}'", file); log.debug("timestamps (old - new): {} {}", info.lastModified(), currentLastModified); log.debug("sizes (old - new): {} {}", info.size(), currentSize); synchronized (replaceRemoveLock) { infoCache.remove(file); } return FileState.UNKNOWN; } /** Return the cached information (probably out-of-date) about a path or null if not in cache. */ FileInfo get(Path path) { return infoCache.get(path.toAbsolutePath().normalize()); } /** * Returns the {@code FileInfo} that is currently associated with the given {@code fileInfo}'s * path. If the given {@code fileInfo} is more recent than the currently associated one (according * to {@link FileInfo#isMoreRecentThan(FileInfo)}) than the old one is replaced by the given * {@code fileInfo} */ FileInfo putIfNewer(FileInfo fileInfo) { // handle the case where no info was previously associated with the file FileInfo existingResult = infoCache.putIfAbsent(fileInfo.path(), fileInfo); if (existingResult == null) { return null; } // we already have information about this file, extra locking required! synchronized (replaceRemoveLock) { // get info for this file again, because it could have been // replaced by other threads while we were waiting for the lock, // i.e the (at this point non-null) value returned by putIfAbsent // is at this point not necessarily the latest info associated with the file existingResult = infoCache.get(fileInfo.path()); if (existingResult == null || fileInfo.isMoreRecentThan(existingResult)) { infoCache.put(fileInfo.path(), fileInfo); } return existingResult; } } /** * Returns a "weakly consistent", unmodifiable iterator that will never throw {@link * ConcurrentModificationException}, and guarantees to traverse elements as they existed upon * construction of the iterator, and may (but is not guaranteed to) reflect any modifications * subsequent to construction. */ @Override public Iterator<FileInfo> iterator() { return Iterators.unmodifiableIterator(infoCache.values().iterator()); } }
mit
FeiZhan/Algo-Collection
answers/leetcode/Verify Preorder Serialization of a Binary Tree/Verify Preorder Serialization of a Binary Tree.java
444
class Solution { public boolean isValidSerialization(String preorder) { String[] splitted = preorder.split(","); int count = 1; for (String s : splitted) { if (count <= 0) { return false; } if (s.length() == 1 && s.charAt(0) == '#') { count--; } else { count++; } } return count == 0; } }
mit
Livestream/livestream-api-samples
java/api-keys-auth-sample/src/main/java/com/livestream/api/samples/apikeys/server/endpoint/AccountApi.java
675
package com.livestream.api.samples.apikeys.server.endpoint; import java.io.IOException; import javax.ws.rs.*; import javax.ws.rs.core.*; import org.apache.http.client.*; import com.livestream.api.samples.apikeys.server.LivestreamApiService; @Path("") public class AccountApi { @Path("/accounts") @GET public Response getAccounts() throws ClientProtocolException, IOException { try { return Response.ok(LivestreamApiService.getAccounts(), MediaType.APPLICATION_JSON_TYPE).build(); } catch (Exception e) { e.printStackTrace(); } return Response.serverError().entity("Backend error").build(); } }
mit
taschetto/artificialIntelligence
informedSearch/HyrulesMazePackage/src/gamestate/GameStateManager.java
880
package gamestate; import java.util.ArrayList; import java.awt.Graphics2D; public class GameStateManager { public GameState gs; private ArrayList<GameState> gameStates; private int currentState; public static final int LEVEL_STATE = 0; public GameStateManager(){ gameStates = new ArrayList<GameState>(); currentState = LEVEL_STATE; gs = new Level1State(this); gameStates.add(gs); } public void setState(int state){ currentState = state; gameStates.get(currentState).init(); } public void update(){ gameStates.get(currentState).update(); } public void draw(Graphics2D g){ gameStates.get(currentState).draw(g); } public void keyPressed(int k) { gameStates.get(currentState).keyPressed(k); } public void keyReleased(int k) { gameStates.get(currentState).keyReleased(k); } }
mit
AndrewRademacher/Algorithms
Java/BubbleSort.java
554
/** * * BubbleSort.java * * Author: Stefan Mendoza * * Based on the description provided in CLRS (3rd Edition). * */ import java.util.Arrays; public class BubbleSort { private static void swap(int[] array, int index1, int index2) { int temp = array[index1]; array[index1] = array[index2]; array[index2] = temp; } public static void sort(int[] array) { for(int i = 0; i < array.length - 1; i++) { for(int j = array.length - 1; j > i; j--) { if(array[j] < array[j - 1]) { swap(array, j - 1, j); } } } } }
mit
shagalalab/Marshrutka
MarshrutkaApp/app/src/main/java/com/shagalalab/marshrutka/util/Utils.java
1929
package com.shagalalab.marshrutka.util; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.preference.PreferenceManager; import com.shagalalab.marshrutka.R; /** * Created by aziz on 7/20/15. */ public class Utils { public static boolean NEED_RESTART = false; public static boolean NEED_REFRESH_AUTOCOMPLETETEXT = false; public static void pendingRestartApp(Context context, Intent intent) { int mPendingIntentId = 123456; PendingIntent mPendingIntent = PendingIntent.getActivity(context, mPendingIntentId, intent, PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_ONE_SHOT); AlarmManager mgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent); System.exit(0); } /** * Get current version of local DB. * Note that even though SQLiteOpenHelper is supposed to track db version, * we use database in non-standard way, i.e. we copy db from assets instead of * creating it in onCreate() callback, and local DB's version will always be 0. * Therefore we need to track it manually. * * @param context * @return */ public static int getDbVersion(Context context) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); return prefs.getInt(context.getString(R.string.pref_dbversion_key), 1); } public static void setDbVersion(Context context, int newDbVersion) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); SharedPreferences.Editor editor = prefs.edit(); editor.putInt(context.getString(R.string.pref_dbversion_key), newDbVersion); editor.apply(); } }
mit
BranchMetrics/Android-Deferred-Deep-Linking-SDK
Branch-SDK/src/main/java/io/branch/referral/BranchActivityLifecycleObserver.java
6502
package io.branch.referral; import android.app.Activity; import android.app.Application; import android.content.Context; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import java.lang.ref.WeakReference; import java.util.HashSet; import java.util.Set; /** * <p>Class that observes activity life cycle events and determines when to start and stop * session.</p> */ class BranchActivityLifecycleObserver implements Application.ActivityLifecycleCallbacks { private int activityCnt_ = 0; //Keep the count of visible activities. //Set of activities observed in this session, note storing it as Activity.toString() ensures // that multiple instances of the same activity are counted individually. private Set<String> activitiesOnStack_ = new HashSet<>(); @Override public void onActivityCreated(@NonNull Activity activity, @Nullable Bundle bundle) { PrefHelper.Debug("onActivityCreated, activity = " + activity); Branch branch = Branch.getInstance(); if (branch == null) return; branch.setIntentState(Branch.INTENT_STATE.PENDING); if (BranchViewHandler.getInstance().isInstallOrOpenBranchViewPending(activity.getApplicationContext())) { BranchViewHandler.getInstance().showPendingBranchView(activity); } } @Override public void onActivityStarted(@NonNull Activity activity) { PrefHelper.Debug("onActivityStarted, activity = " + activity); Branch branch = Branch.getInstance(); if (branch == null) { return; } // technically this should be in onResume but it is effectively the same to have it here, plus // it allows us to use currentActivityReference_ in session initialization code branch.currentActivityReference_ = new WeakReference<>(activity); branch.setIntentState(Branch.INTENT_STATE.PENDING); activityCnt_++; maybeRefreshAdvertisingID(activity); } @Override public void onActivityResumed(@NonNull Activity activity) { PrefHelper.Debug("onActivityResumed, activity = " + activity); Branch branch = Branch.getInstance(); if (branch == null) return; // if the intent state is bypassed from the last activity as it was closed before onResume, we need to skip this with the current // activity also to make sure we do not override the intent data if (!Branch.bypassCurrentActivityIntentState()) { branch.onIntentReady(activity); } if (branch.getInitState() == Branch.SESSION_STATE.UNINITIALISED && !Branch.disableAutoSessionInitialization) { if (Branch.getPluginName() == null) { // this is the only place where we self-initialize in case user opens the app from 'recent apps tray' // and the entry Activity is not the launcher Activity where user placed initSession themselves. PrefHelper.Debug("initializing session on user's behalf (onActivityResumed called but SESSION_STATE = UNINITIALISED)"); Branch.sessionBuilder(activity).isAutoInitialization(true).init(); } else { PrefHelper.Debug("onActivityResumed called and SESSION_STATE = UNINITIALISED, however this is a " + Branch.getPluginName() + " plugin, so we are NOT initializing session on user's behalf"); } } // must be called after session initialization, which relies on checking whether activity // that is initializing the session is being launched from stack or anew activitiesOnStack_.add(activity.toString()); } @Override public void onActivityPaused(@NonNull Activity activity) { PrefHelper.Debug("onActivityPaused, activity = " + activity); Branch branch = Branch.getInstance(); if (branch == null) return; /* Close any opened sharing dialog.*/ if (branch.getShareLinkManager() != null) { branch.getShareLinkManager().cancelShareLinkDialog(true); } } @Override public void onActivityStopped(@NonNull Activity activity) { PrefHelper.Debug("onActivityStopped, activity = " + activity); Branch branch = Branch.getInstance(); if (branch == null) return; activityCnt_--; // Check if this is the last activity. If so, stop the session. if (activityCnt_ < 1) { branch.setInstantDeepLinkPossible(false); branch.closeSessionInternal(); } } @Override public void onActivitySaveInstanceState(@NonNull Activity activity, @NonNull Bundle bundle) { } @Override public void onActivityDestroyed(@NonNull Activity activity) { PrefHelper.Debug("onActivityDestroyed, activity = " + activity); Branch branch = Branch.getInstance(); if (branch == null) return; if (branch.getCurrentActivity() == activity) { branch.currentActivityReference_.clear(); } BranchViewHandler.getInstance().onCurrentActivityDestroyed(activity); activitiesOnStack_.remove(activity.toString()); } private void maybeRefreshAdvertisingID(Context context) { Branch branch = Branch.getInstance(); if (branch == null) return; boolean fullyInitialized = branch.getTrackingController() != null && branch.getDeviceInfo() != null && branch.getDeviceInfo().getSystemObserver() != null && branch.getPrefHelper() != null && branch.getPrefHelper().getSessionID() != null; if (!fullyInitialized) return; final String AIDInitializationSessionID = branch.getDeviceInfo().getSystemObserver().getAIDInitializationSessionID(); boolean AIDInitializedInThisSession = branch.getPrefHelper().getSessionID().equals(AIDInitializationSessionID); if (!AIDInitializedInThisSession && !branch.isGAParamsFetchInProgress() && !branch.getTrackingController().isTrackingDisabled()) { branch.setGAParamsFetchInProgress(branch.getDeviceInfo().getSystemObserver().prefetchAdsParams(context, branch)); } } boolean isCurrentActivityLaunchedFromStack() { Branch branch = Branch.getInstance(); if (branch == null || branch.getCurrentActivity() == null) { // don't think this is possible return false; } return activitiesOnStack_.contains(branch.getCurrentActivity().toString()); } }
mit
rkluszczynski/gradle-templates-project
example-of-mvc-jsp-image-upload/src/main/java/pl/info/rkluszczynski/examples/upload/validator/FileValidator.java
671
package pl.info.rkluszczynski.examples.upload.validator; import org.springframework.validation.Errors; import org.springframework.validation.Validator; import pl.info.rkluszczynski.examples.upload.model.UploadedFile; public class FileValidator implements Validator { @Override public boolean supports(Class<?> arg0) { // TODO Auto-generated method stub return false; } @Override public void validate(Object uploadedFile, Errors errors) { UploadedFile file = (UploadedFile) uploadedFile; if (file.getFile().getSize() == 0) { errors.rejectValue("file", "uploadForm.selectFile", "Please select a file with size > 0!"); } } }
mit
sharawy/timeZoneConverter
src/main/java/com/timezone/validators/annotations/StringTimeDate.java
774
package com.timeZone.validators.annotations; import com.timeZone.validators.StringTimeDateValidator; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import javax.validation.Constraint; import javax.validation.Payload; @Documented @Constraint(validatedBy = StringTimeDateValidator.class) @Target( { ElementType.METHOD, ElementType.FIELD }) @Retention(RetentionPolicy.RUNTIME) public @interface StringTimeDate { String message() default "{date format should be yyyy-MM-dd HH:mm}"; String format () default "yyyy-MM-dd HH:mm"; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; }
mit
KwesiD/SudokuSolver
Grid.java
1310
/** Author: Kwesi Daniel **/ /** v1 **/ class Grid{ private int [][] grid = new int[3][3]; Grid(int[] numbers){ setGrid(numbers); } Grid(){} public boolean contains(int num){ for(int i = 0;i < 3;i++){ for(int j = 0;j < 3;j++){ if(grid[i][j] == num){return true;} } } return false; } public String toString(){ String string = ""; for(int i = 0;i < 3;i++){ string += "|"; for(int j = 0;j < 3;j++){ string += grid[i][j] + "|"; } string += "\n"; } return string; } public String setGrid(int[] numbers){ for(int i = 0,k = 0;i < 3;i++){ for(int j = 0;j < 3;j++,k++){ grid[i][j] = numbers[k]; } } return this.toString(); } public String setGrid(int[][] numbers){ grid = numbers; return this.toString(); } public int setNumber(int row,int col,int num){ if((row < 0) || (row > 2) || (col < 0) || (col > 2)){ System.out.println("Coordinates row= " + row + " col= " + col + "are invalid"); return -1; } if(num < 0 || num > 9){ System.out.println(num + " is invalid."); return -1; } grid[row][col] = num; return grid[row][col]; } public int getNumber(int row,int col){ if((row < 0) || (row > 2) || (col < 0) || (col > 2)){ System.out.println("Coordinates row= " + row + " col= " + col + "are invalid"); return -1; } return grid[row][col]; } }
mit
bitDecayGames/Jump
jump-core/src/test/java/com.bitdecay.jump/level/LevelLayersTest.java
780
package com.bitdecay.jump.level; import org.junit.Test; import static org.junit.Assert.*; /** * Created by Monday on 9/19/2016. */ public class LevelLayersTest { @Test public void testCreateNew() { int cellSize = 10; LevelLayers layers = new LevelLayers(cellSize); assertNotNull(layers.layers.get(0)); assertEquals(cellSize, layers.layers.get(0).cellSize); } @Test public void testAddLayer() { int cellSize = 10; LevelLayers layers = new LevelLayers(cellSize); assertNotNull(layers.layers.get(0)); SingleLayer newLayer = new SingleLayer(cellSize); layers.addLayer(1, newLayer); assertTrue(layers.hasLayer(1)); assertEquals(newLayer, layers.getLayer(1)); } }
mit
mockcrumb/mockcrumb-core
src/main/java/org/mockcrumb/resolver/FullyQualifiedCrumbResolver.java
414
package org.mockcrumb.resolver; import java.nio.file.Path; import java.nio.file.Paths; public class FullyQualifiedCrumbResolver extends FileBasedCrumbResolver { public static final FullyQualifiedCrumbResolver INSTANCE = new FullyQualifiedCrumbResolver(); @Override public <T> Path getContext(final Class<T> clazz, final String name) { return Paths.get(clazz.getName() + "_" + name); } }
mit
myayo/EADJAVA
src/main/java/com/inf380/ead/service/ZipService.java
1578
package com.inf380.ead.service; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; /** * Zip service that create zip file * @author myayo & Hanzhi */ public class ZipService { /** * Create zip file from directory pathName * @param pathName * @throws IOException */ public byte[] createZip(String pathName) throws IOException{ ByteArrayOutputStream baos = new ByteArrayOutputStream(); File dir = new File(pathName); List<String> fileList = getFileList(dir, dir.getAbsolutePath()); ZipOutputStream zos=new ZipOutputStream(baos); for(String filePath:fileList){ ZipEntry ze=new ZipEntry(filePath); zos.putNextEntry(ze); FileInputStream fis = new FileInputStream(pathName+File.separator+filePath); byte[] buffer=new byte[1024]; int len; while((len=fis.read(buffer))>0){ zos.write(buffer, 0, len); } zos.closeEntry(); fis.close(); } zos.close(); baos.close(); return baos.toByteArray(); } private List<String> getFileList(File dir, String sourceFolder) { List<String> filesInDir = new ArrayList<String>(); File[] files=dir.listFiles(); for(File file:files){ if(file.isFile()){ filesInDir.add(file.getAbsoluteFile().toString().substring(sourceFolder.length()+1, file.getAbsoluteFile().toString().length())); } else { filesInDir.addAll(getFileList(file, sourceFolder)); } } return filesInDir; } }
mit
NucleusPowered/Nucleus
nucleus-core/src/main/java/io/github/nucleuspowered/nucleus/core/guice/ConfigDirectory.java
430
/* * This file is part of Nucleus, licensed under the MIT License (MIT). See the LICENSE.txt file * at the root of this project for more details. */ package io.github.nucleuspowered.nucleus.core.guice; import com.google.inject.BindingAnnotation; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @BindingAnnotation @Retention(RetentionPolicy.RUNTIME) public @interface ConfigDirectory { }
mit
imojiengineering/imoji-android-sdk
imoji-android-sdk/src/main/java/io/imoji/sdk/Session.java
10968
/* * Imoji Android SDK * Created by nkhoshini * * Copyright (C) 2016 Imoji * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KID, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. * */ package io.imoji.sdk; import android.graphics.Bitmap; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import java.util.Date; import java.util.List; import io.imoji.sdk.objects.Category; import io.imoji.sdk.objects.CategoryFetchOptions; import io.imoji.sdk.objects.CollectionType; import io.imoji.sdk.objects.Imoji; import io.imoji.sdk.response.CategoriesResponse; import io.imoji.sdk.response.CreateImojiResponse; import io.imoji.sdk.response.GenericApiResponse; import io.imoji.sdk.response.ImojiAttributionsResponse; import io.imoji.sdk.response.ImojisResponse; /** * Base interface for generating any Imoji Api Request * * @author nkhoshini */ public interface Session { /** * Fetches top level imoji categories given a classification type. * * @param classification Type of category classification to retrieve * @return An ApiTask reference to be resolved by the caller * @deprecated Use getImojiCategorys(CategoryFetchOptions fetchOptions) instead */ @NonNull ApiTask<CategoriesResponse> getImojiCategories(@NonNull Category.Classification classification); /** * Fetches top level imoji categories with options. * * @param fetchOptions Options to use for filtering category requests * @return An ApiTask reference to be resolved by the caller */ @NonNull ApiTask<CategoriesResponse> getImojiCategories(@NonNull CategoryFetchOptions fetchOptions); /** * Searches the imojis database with a given search term. * * @param term Search term to find imojis with. If null or empty, the server will typically return the featured set of imojis (this is subject to change). * @return An ApiTask reference to be resolved by the caller */ @NonNull ApiTask<ImojisResponse> searchImojis(@NonNull String term); /** * Searches the imojis database with a given search term. * * @param term Search term to find imojis with. If null or empty, the server will typically returned the featured set of imojis (this is subject to change). * @param offset The result offset from a previous search. * @param numberOfResults Number of results to fetch. * @return An ApiTask reference to be resolved by the caller */ @NonNull ApiTask<ImojisResponse> searchImojis(@NonNull String term, @Nullable Integer offset, @Nullable Integer numberOfResults); /** * Gets a random set of featured imojis. * * @return An ApiTask reference to be resolved by the caller */ @NonNull ApiTask<ImojisResponse> getFeaturedImojis(); /** * Gets a random set of featured imojis * * @param numberOfResults Number of results to fetch. * @return An ApiTask reference to be resolved by the caller */ @NonNull ApiTask<ImojisResponse> getFeaturedImojis(@Nullable Integer numberOfResults); /** * Gets imojis associated to a user's collection which can be accumulated by calling either * createImojiWithRawImage (Created), addImojiToUserCollection (Saved), * or markImojiUsage (Recents). * * @param collectionType CollectionType to filter on. If null, all collected Imoji's are returned * @return An ApiTask reference to be resolved by the caller */ @NonNull ApiTask<ImojisResponse> getCollectedImojis(@Nullable CollectionType collectionType); /** * Gets corresponding Imoji's for one or more imoji identifiers as Strings * * @param identifiers One or more Imoji ID's * @return An ApiTask reference to be resolved by the caller */ @NonNull ApiTask<ImojisResponse> fetchImojisByIdentifiers(@NonNull List<String> identifiers); /** * Searches the imojis database with a complete sentence. The service performs keyword parsing to find best matched imojis. * * @param sentence Full sentence to parse. * @return An ApiTask reference to be resolved by the caller */ @NonNull ApiTask<ImojisResponse> searchImojisWithSentence(@NonNull String sentence); /** * Searches the imojis database with a complete sentence. The service performs keyword parsing to find best matched imojis. * * @param sentence Full sentence to parse. * @param numberOfResults Number of results to fetch. * @return An ApiTask reference to be resolved by the caller */ @NonNull ApiTask<ImojisResponse> searchImojisWithSentence(@NonNull String sentence, @Nullable Integer numberOfResults); /** * Adds an Imoji sticker to the database * * @param rawImage The Imoji sticker image * @param borderedImage The bordered version of the Imoji sticker image * @param tags An array of Strings representing the tags of the Imoji sticker * @return An ApiTask reference to be resolved by the caller */ @NonNull ApiTask<CreateImojiResponse> createImojiWithRawImage(@NonNull Bitmap rawImage, @NonNull Bitmap borderedImage, @Nullable List<String> tags); /** * Removes an Imoji sticker that was created by the user with createImojiWithImage:tags:callback: * * @param imoji The added Imoji object * @return An ApiTask reference to be resolved by the caller */ @NonNull ApiTask<GenericApiResponse> removeImoji(@NonNull Imoji imoji); /** * Reports an Imoji sticker as abusive. You may expose this method in your application in order for users to have the ability to flag * content as not appropriate. Reported Imojis are not removed instantly but are reviewed internally before removal. * * @param imoji The Imoji object to report * @param reason Optional text describing the reason why the content is being reported * @return An ApiTask reference to be resolved by the caller * @deprecated Use reportImojiAsAbusive(String imojiId, String reason) instead */ @NonNull @Deprecated ApiTask<GenericApiResponse> reportImojiAsAbusive(@NonNull Imoji imoji, @Nullable String reason); /** * Reports an Imoji sticker as abusive. You may expose this method in your application in order for users to have the ability to flag * content as not appropriate. Reported Imojis are not removed instantly but are reviewed internally before removal. * * @param imojiId The ID of the Imoji object to report * @param reason Optional text describing the reason why the content is being reported * @return An ApiTask reference to be resolved by the caller */ @NonNull ApiTask<GenericApiResponse> reportImojiAsAbusive(@NonNull String imojiId, @Nullable String reason); /** * Marks an Imoji sticker as being used for sharing. For example, if a user copied a sticker * in a keyboard application, that would qualify as the Imoji being used. * * @param imoji The Imoji object to register for usage * @param originIdentifier Optional arbitrary identifier which developers can supply describing the action that * triggered the usage. String must be less than or equal to 40 characters. * @return An ApiTask reference to be resolved by the caller * @deprecated Use markImojiUsage(String imojiId, String originIdentifier) instead */ @NonNull ApiTask<GenericApiResponse> markImojiUsage(@NonNull Imoji imoji, @Nullable String originIdentifier); /** * Marks an Imoji sticker as being used for sharing. For example, if a user copied a sticker * in a keyboard application, that would qualify as the Imoji being used. * * @param imojiId The ID of the Imoji object to register for usage * @param originIdentifier Optional arbitrary identifier which developers can supply describing the action that * triggered the usage. String must be less than or equal to 40 characters. * @return An ApiTask reference to be resolved by the caller */ @NonNull ApiTask<GenericApiResponse> markImojiUsage(@NonNull String imojiId, @Nullable String originIdentifier); /** * Adds a given Imoji sticker to a users collection. The content can be fetched by calling * getCollectedImojis with CollectionType.Liked for the type. * * @param imojiId The ID of the Imoji object to add * @return An ApiTask reference to be resolved by the caller */ @NonNull ApiTask<GenericApiResponse> addImojiToUserCollection(@NonNull String imojiId); /** * Gets attribution information for a set of Imoji ID's. * * @param identifiers One or more Imoji ID's * @return An ApiTask reference to be resolved by the caller */ @NonNull ApiTask<ImojiAttributionsResponse> fetchAttributionByImojiIdentifiers(@NonNull List<String> identifiers); /** * Gets attribution information for a set of Imoji ID's. * * @param gender An optional gender value for the user (either 'male' or 'female') * @param latitude Optional latitude value for the user's location * @param longitude Optional longitude value for the user's location * @param dateOfBirth Optional date of birth value for the user * @return An ApiTask reference to be resolved by the caller */ @NonNull ApiTask<GenericApiResponse> setUserDemographicsData(@Nullable String gender, @Nullable Double latitude, @Nullable Double longitude, @Nullable Date dateOfBirth); }
mit
TwilioDevEd/api-snippets
rest/voice/generate-twiml-say/generate-twiml-say.8.x.java
596
import com.twilio.twiml.VoiceResponse; import com.twilio.twiml.voice.Say; import static spark.Spark.*; public class VoiceApp { public static void main(String[] args) { get("/hello", (req, res) -> "Hello Web"); post("/", (request, response) -> { Say say = new Say.Builder( "Hello from your pals at Twilio! Have fun.") .build(); VoiceResponse voiceResponse = new VoiceResponse.Builder() .say(say) .build(); return voiceResponse.toXml(); }); } }
mit
Microsoft/vso-httpclient-java
Rest/alm-vss-client/src/main/generated/com/microsoft/alm/visualstudio/services/location/client/LocationHttpClientBase.java
8764
// @formatter:off /* * --------------------------------------------------------- * Copyright(C) Microsoft Corporation. All rights reserved. * Licensed under the MIT license. See License.txt in the project root. * --------------------------------------------------------- * * --------------------------------------------------------- * Generated file, DO NOT EDIT * --------------------------------------------------------- * * See following wiki page for instructions on how to regenerate: * https://vsowiki.com/index.php?title=Rest_Client_Generation */ package com.microsoft.alm.visualstudio.services.location.client; import java.net.URI; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import com.fasterxml.jackson.core.type.TypeReference; import com.microsoft.alm.client.HttpMethod; import com.microsoft.alm.client.model.NameValueCollection; import com.microsoft.alm.client.VssHttpClientBase; import com.microsoft.alm.client.VssMediaTypes; import com.microsoft.alm.client.VssRestClientHandler; import com.microsoft.alm.client.VssRestRequest; import com.microsoft.alm.visualstudio.services.location.ConnectionData; import com.microsoft.alm.visualstudio.services.location.ServiceDefinition; import com.microsoft.alm.visualstudio.services.webapi.ApiResourceVersion; import com.microsoft.alm.visualstudio.services.webapi.ConnectOptions; import com.microsoft.alm.visualstudio.services.webapi.VssJsonCollectionWrapper; public abstract class LocationHttpClientBase extends VssHttpClientBase { private final static Map<String, Class<? extends Exception>> TRANSLATED_EXCEPTIONS; static { TRANSLATED_EXCEPTIONS = new HashMap<String, Class<? extends Exception>>(); } /** * Create a new instance of LocationHttpClientBase * * @param clientHandler * a DefaultRestClientHandler initialized with an instance of a JAX-RS Client implementation or * a TEERestClientHamdler initialized with TEE HTTP client implementation * @param baseUrl * a TFS services URL */ protected LocationHttpClientBase(final VssRestClientHandler clientHandler, final URI baseUrl) { super(clientHandler, baseUrl); } @Override protected Map<String, Class<? extends Exception>> getTranslatedExceptions() { return TRANSLATED_EXCEPTIONS; } /** * [Preview API 3.1-preview.1] This was copied and adapted from TeamFoundationConnectionService.Connect() * * @param connectOptions * * @param lastChangeId * Obsolete 32-bit LastChangeId * @param lastChangeId64 * Non-truncated 64-bit LastChangeId * @return ConnectionData */ public ConnectionData getConnectionData( final ConnectOptions connectOptions, final Integer lastChangeId, final Integer lastChangeId64) { final UUID locationId = UUID.fromString("00d9565f-ed9c-4a06-9a50-00e7896ccab4"); //$NON-NLS-1$ final ApiResourceVersion apiVersion = new ApiResourceVersion("3.1-preview.1"); //$NON-NLS-1$ final NameValueCollection queryParameters = new NameValueCollection(); queryParameters.addIfNotNull("connectOptions", connectOptions); //$NON-NLS-1$ queryParameters.addIfNotNull("lastChangeId", lastChangeId); //$NON-NLS-1$ queryParameters.addIfNotNull("lastChangeId64", lastChangeId64); //$NON-NLS-1$ final VssRestRequest httpRequest = super.createRequest(HttpMethod.GET, locationId, apiVersion, queryParameters, VssMediaTypes.APPLICATION_JSON_TYPE); return super.sendRequest(httpRequest, ConnectionData.class); } /** * [Preview API 3.1-preview.1] * * @param serviceType * * @param identifier * */ public void deleteServiceDefinition( final String serviceType, final UUID identifier) { final UUID locationId = UUID.fromString("d810a47d-f4f4-4a62-a03f-fa1860585c4c"); //$NON-NLS-1$ final ApiResourceVersion apiVersion = new ApiResourceVersion("3.1-preview.1"); //$NON-NLS-1$ final Map<String, Object> routeValues = new HashMap<String, Object>(); routeValues.put("serviceType", serviceType); //$NON-NLS-1$ routeValues.put("identifier", identifier); //$NON-NLS-1$ final VssRestRequest httpRequest = super.createRequest(HttpMethod.DELETE, locationId, routeValues, apiVersion, VssMediaTypes.APPLICATION_JSON_TYPE); super.sendRequest(httpRequest); } /** * [Preview API 3.1-preview.1] * * @param serviceType * * @param identifier * * @param allowFaultIn * * @return ServiceDefinition */ public ServiceDefinition getServiceDefinition( final String serviceType, final UUID identifier, final Boolean allowFaultIn) { final UUID locationId = UUID.fromString("d810a47d-f4f4-4a62-a03f-fa1860585c4c"); //$NON-NLS-1$ final ApiResourceVersion apiVersion = new ApiResourceVersion("3.1-preview.1"); //$NON-NLS-1$ final Map<String, Object> routeValues = new HashMap<String, Object>(); routeValues.put("serviceType", serviceType); //$NON-NLS-1$ routeValues.put("identifier", identifier); //$NON-NLS-1$ final NameValueCollection queryParameters = new NameValueCollection(); queryParameters.addIfNotNull("allowFaultIn", allowFaultIn); //$NON-NLS-1$ final VssRestRequest httpRequest = super.createRequest(HttpMethod.GET, locationId, routeValues, apiVersion, queryParameters, VssMediaTypes.APPLICATION_JSON_TYPE); return super.sendRequest(httpRequest, ServiceDefinition.class); } /** * [Preview API 3.1-preview.1] * * @param serviceType * * @return ArrayList&lt;ServiceDefinition&gt; */ public ArrayList<ServiceDefinition> getServiceDefinitions(final String serviceType) { final UUID locationId = UUID.fromString("d810a47d-f4f4-4a62-a03f-fa1860585c4c"); //$NON-NLS-1$ final ApiResourceVersion apiVersion = new ApiResourceVersion("3.1-preview.1"); //$NON-NLS-1$ final Map<String, Object> routeValues = new HashMap<String, Object>(); routeValues.put("serviceType", serviceType); //$NON-NLS-1$ final VssRestRequest httpRequest = super.createRequest(HttpMethod.GET, locationId, routeValues, apiVersion, VssMediaTypes.APPLICATION_JSON_TYPE); return super.sendRequest(httpRequest, new TypeReference<ArrayList<ServiceDefinition>>() {}); } /** * [Preview API 3.1-preview.1] * * @param serviceDefinitions * */ public void updateServiceDefinitions(final VssJsonCollectionWrapper<List<ServiceDefinition>> serviceDefinitions) { final UUID locationId = UUID.fromString("d810a47d-f4f4-4a62-a03f-fa1860585c4c"); //$NON-NLS-1$ final ApiResourceVersion apiVersion = new ApiResourceVersion("3.1-preview.1"); //$NON-NLS-1$ final VssRestRequest httpRequest = super.createRequest(HttpMethod.PATCH, locationId, apiVersion, serviceDefinitions, VssMediaTypes.APPLICATION_JSON_TYPE, VssMediaTypes.APPLICATION_JSON_TYPE); super.sendRequest(httpRequest); } }
mit
AlexRogalskiy/SubscriptionServiceREST
src/main/java/com/wildbeeslabs/rest/model/Subscription.java
4771
package com.wildbeeslabs.rest.model; import com.wildbeeslabs.api.rest.common.model.BaseEntity; import com.wildbeeslabs.api.rest.common.utils.DateUtils; import java.io.Serializable; import java.util.Date; import java.util.HashSet; import java.util.Objects; import java.util.Set; import javax.persistence.Basic; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Inheritance; import javax.persistence.InheritanceType; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.UniqueConstraint; import org.hibernate.validator.constraints.NotBlank; import org.springframework.format.annotation.DateTimeFormat; /** * * Subscription REST Application Model * * @author Alex * @version 1.0.0 * @since 2017-08-08 */ @Entity(name = "Subscription") @Table(name = "subscriptions", uniqueConstraints = { @UniqueConstraint(columnNames = "name", name = "name_unique_constraint") }) @Inheritance(strategy = InheritanceType.JOINED) public class Subscription extends BaseEntity<Long> implements Serializable { @Id @Basic(optional = false) @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "subscription_id", unique = true, nullable = false) private Long id; @NotBlank(message = "Field <name> cannot be blank") @Column(name = "name", nullable = false, unique = true) private String name; @DateTimeFormat(pattern = DateUtils.DEFAULT_DATE_FORMAT_PATTERN) @Column(name = "expired_at", nullable = true) @Temporal(javax.persistence.TemporalType.TIMESTAMP) private Date expireAt; @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL, optional = false) //@JsonManagedReference(value = "subscriptionToSubscriptionStatus") @JoinColumn(name = "subscription_status_id", referencedColumnName = "subscription_status_id") private SubscriptionStatusInfo statusInfo; @OneToMany(mappedBy = "id.subscription", cascade = CascadeType.ALL, fetch = FetchType.LAZY, orphanRemoval = true) @Column(name = "users", nullable = true) private final Set<UserSubOrder> userOrders = new HashSet<>(); @Override public Long getId() { return id; } @Override public void setId(final Long id) { this.id = id; } public String getName() { return name; } public void setName(final String name) { this.name = name; } public Date getExpireAt() { return this.expireAt; } public void setExpireAt(final Date expireAt) { this.expireAt = expireAt; } // public String getExpireAt() { // return (Objects.nonNull(this.expireAt)) ? DateUtils.dateToStr(this.expireAt) : null; // } // // public void setExpireAt(final String str) { // this.expireAt = (Objects.nonNull(str)) ? DateUtils.strToDate(str) : null; // } public SubscriptionStatusInfo getStatusInfo() { return statusInfo; } public void setStatusInfo(final SubscriptionStatusInfo statusInfo) { this.statusInfo = statusInfo; } public Set<UserSubOrder> getUserOrders() { return userOrders; } public void setUserOrders(final Set<UserSubOrder> userOrders) { this.userOrders.clear(); if (Objects.nonNull(userOrders)) { this.userOrders.addAll(userOrders); } } public void addUserOrder(final UserSubOrder userOrder) { if (Objects.nonNull(userOrder)) { this.userOrders.add(userOrder); } } @Override @SuppressWarnings("EqualsWhichDoesntCheckParameterClass") public boolean equals(Object obj) { if (this == obj) { return true; } if (null == obj || obj.getClass() != this.getClass()) { return false; } final Subscription other = (Subscription) obj; return Objects.equals(this.statusInfo, other.statusInfo) && Objects.equals(this.name, other.name) && Objects.equals(this.id, other.id) && Objects.equals(this.expireAt, other.expireAt); } @Override public int hashCode() { return Objects.hash(this.id, this.name, this.expireAt, this.statusInfo); } @Override public String toString() { return String.format("Subscription {id: %d, name: %s, expireAt: %s, statusInfo: %s, inherited: %s}", this.id, this.name, this.expireAt, this.statusInfo, super.toString()); } }
mit
Rojoss/Boxx
src/main/java/com/jroossien/boxx/aliases/DyeColors.java
3451
/* * The MIT License (MIT) * * Copyright (c) 2016 Rojoss <http://jroossien.com> * Copyright (c) 2016 contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.jroossien.boxx.aliases; import com.jroossien.boxx.aliases.internal.AliasMap; import org.bukkit.DyeColor; import java.io.File; import java.util.List; import java.util.Map; public class DyeColors extends AliasMap<DyeColor> { private DyeColors() { super("DyeColors", new File(ALIASES_FOLDER, "DyeColors.yml"), "colors", "dyecolor"); } @Override public void onLoad() { add(DyeColor.WHITE, "White", "0", "WH"); add(DyeColor.ORANGE, "Orange", "1", "OR", "DY", "Dark Yellow", "DYellow"); add(DyeColor.MAGENTA, "Magenta", "2", "LP", "MA", "Light Purple", "LPurple"); add(DyeColor.LIGHT_BLUE, "Light Blue", "LB", "3", "LBlue"); add(DyeColor.YELLOW, "Yellow", "4", "YE", "Light Yellow", "LYellow"); add(DyeColor.LIME, "Lime", "5", "LI", "LG", "Light Green", "LGreen"); add(DyeColor.PINK, "Pink", "6", "PI"); add(DyeColor.GRAY, "Gray", "7", "GR", "Dark Gray", "DGray"); add(DyeColor.SILVER, "Silver", "8", "SI", "Light Gray", "LGray"); add(DyeColor.CYAN, "Cyan", "9", "DA", "CY", "Dark Aqua", "DAqua"); add(DyeColor.PURPLE, "Purple", "10", "DP", "Dark Purple", "DPurple"); add(DyeColor.BLUE, "Blue", "11", "DB", "Dark Blue", "DBlue"); add(DyeColor.BROWN, "Brown", "BR", "12"); add(DyeColor.GREEN, "Green", "13", "DG", "Dark Green", "DGreen"); add(DyeColor.RED, "Red", "14", "DR", "RE", "Dark Red", "DRed"); add(DyeColor.BLACK, "Black", "15", "BL"); } public static DyeColor get(String string) { return instance()._get(string); } public static String getName(DyeColor key) { return instance()._getName(key); } public static String getDisplayName(DyeColor key) { return instance()._getDisplayName(key); } public static List<String> getAliases(DyeColor key) { return instance()._getAliases(key); } public static Map<String, List<String>> getAliasMap() { return instance()._getAliasMap(); } public static DyeColors instance() { if (getMap(DyeColors.class) == null) { aliasMaps.put(DyeColors.class, new DyeColors()); } return (DyeColors)getMap(DyeColors.class); } }
mit
Serguei-P/http
src/main/java/serguei/http/HttpRequestHeaders.java
6756
package serguei.http; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.MalformedURLException; import java.net.URL; /** * This represents request headers - combination of the the request line and the following headers as specified in * RFC-2616: https://tools.ietf.org/html/rfc2616 * * This class is mutable and it is not thread safe. One would directly create and manipulate instance of this class to * prepare request headers in the client * * @author Serguei Poliakov * */ public final class HttpRequestHeaders extends HttpHeaders { private static final String PROTOCOL_SEPARATOR = "://"; private String method; private String version; private String path; /** * This creates an instance of HttpRequestHeaders * * @param requestLine * - request line, e.g. "GET / HTTP/1." * @param headers * - headers in the form "Host: www.google.co.uk" * @throws HttpException * - can be thrown when request line or headers do not follow HTTP standards */ public HttpRequestHeaders(String requestLine, String... headers) throws HttpException { parseRequestLine(requestLine); for (String header : headers) { addHeader(header); } } /** * This creates an instance of this class by reading request line and headers from a stream * * @param inputStream * @throws IOException * - thrown when the data is not HTTP or IO errors */ public HttpRequestHeaders(InputStream inputStream) throws IOException { HeaderLineReader reader = new HeaderLineReader(inputStream); String line = reader.readLine(); if (line != null) { parseRequestLine(line); } else { throw new HttpException("Unexpected EOF when reading HTTP message"); } readHeaders(reader); } HttpRequestHeaders(HttpRequestHeaders requestHeaders) { super(requestHeaders); this.method = requestHeaders.method; this.version = requestHeaders.version; this.path = requestHeaders.path; } /** * This returns Url based on command line and host header. If request line contains host, it has a priority over * what is specified in host header * * @throws HttpException * - thrown when URL is incorrect */ public URL getUrl() throws HttpException { String host = getHeader("Host"); return parseUrl(path, host); } /** * This returns host from Host header or, if Host header does not exist (e.g. when HTTP/1.0) then from path in * command line * * @throws HttpException * - thrown if there was an error parsing path in request line */ public String getHost() throws HttpException { String host = getHeader("Host"); if (host != null) { return host; } else { return parseUrl(path, null).getHost(); } } /** * This writes the request line and headers into the output stream * * This includes an empty line separating headers and body (i.e. you can start writing the body immediately after * this) */ @Override public void write(OutputStream outputStream) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); out.write(method.getBytes()); out.write(SPACE); out.write(path.getBytes()); out.write(SPACE); out.write(version.getBytes()); out.write(LINE_SEPARATOR_BYTES); super.write(out); outputStream.write(out.toByteArray()); } /** * @return request method (e.g. "GET", "POST") */ public String getMethod() { return method; } /** * @return HTTP version (e.g. "HTTP/1.1") */ public String getVersion() { return version; } /** * @return Path as specified in Request Line */ public String getPath() { return path; } @Override public String toString() { return method + " " + path + " " + version + System.lineSeparator() + super.toString(); } private void parseRequestLine(String commandLine) throws HttpException { String[] parts = commandLine.split(" "); if (parts.length != 3) { throw new HttpException("Wrong number of elements in command line: " + commandLine); } method = parts[0]; path = parts[1]; version = parts[2]; } private URL parseUrl(String line, String host) throws HttpException { String protocol; String fullPath; int pos = line.indexOf(PROTOCOL_SEPARATOR); if (pos > 0) { protocol = line.substring(0, pos); fullPath = line.substring(pos + PROTOCOL_SEPARATOR.length()); } else { protocol = "http"; fullPath = line; } String path; if (fullPath.startsWith("/")) { path = fullPath; } else { pos = fullPath.indexOf('/'); if (pos > 0) { host = fullPath.substring(0, pos); path = fullPath.substring(pos); } else { host = fullPath; path = ""; } } if (host == null || host.length() == 0) { throw new HttpException("No host found in request headers"); } try { return new URL(protocol, host, path); } catch (MalformedURLException e) { throw new HttpException("Cannot create url for protocol: " + protocol + ", host: " + host + ", path: " + path); } } /** * Creates request headers for CONNECT request */ public static HttpRequestHeaders connectRequest(String host) { try { return new HttpRequestHeaders("CONNECT " + host + " HTTP/1.1", "Host: " + host); } catch (HttpException e) { // should never happen return null; } } /** * Creates request headers for GET request */ public static HttpRequestHeaders getRequest(String url) throws IOException { String host = (new URL(url)).getHost(); return new HttpRequestHeaders("GET " + url + " HTTP/1.1", "Host: " + host); } /** * Creates request headers for POST request */ public static HttpRequestHeaders postRequest(String url) throws IOException { String host = (new URL(url)).getHost(); return new HttpRequestHeaders("POST " + url + " HTTP/1.1", "Host: " + host); } }
mit
bobbylight/rak
src/main/java/org/sgc/rak/util/QuerySpecifications.java
10579
package org.sgc.rak.util; import org.apache.commons.lang3.StringUtils; import org.sgc.rak.model.ActivityProfile; import org.sgc.rak.model.Audit; import org.sgc.rak.model.AuditAction; import org.sgc.rak.model.Compound; import org.springframework.data.jpa.domain.Specification; import org.springframework.lang.Nullable; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import java.util.Arrays; import java.util.Date; import java.util.List; import java.util.Locale; /** * Specifications used to simplify JPA repository queries. */ public final class QuerySpecifications { private QuerySpecifications() { // Do nothing (comment for Sonar) } /** * Returns a specification that looks for any {@code ActivityProfile}s matching the given criteria. * * @param compoundName The compound name. Case is ignored. This may be {@code null} if the returned * list should not be restricted to a particular compound. * @param kinaseIds The kinase involved in the activity profile. This may be {@code null} to not limit * the search to one particular kinase. * @param percentControl The value that the percent control of the activity profile must be less than or * equal to. This may be {@code null} to not restrict by percent control. * @return The specification. */ public static Specification<ActivityProfile> activityProfilesMatching(String compoundName, List<Long> kinaseIds, Double percentControl) { return new Specification<ActivityProfile>() { @Nullable @Override public Predicate toPredicate(Root<ActivityProfile> root, CriteriaQuery<?> query, CriteriaBuilder builder) { Predicate predicate = null; if (StringUtils.isNotBlank(compoundName)) { predicate = builder.like(builder.lower(root.get("compoundName")), compoundName.toLowerCase(Locale.US)); } if (kinaseIds != null && !kinaseIds.isEmpty()) { CriteriaBuilder.In<Object> inPredicate = builder.in(root.get("kinase")); for (Long kinaseId : kinaseIds) { inPredicate.value(kinaseId); } predicate = predicate == null ? inPredicate : builder.and(predicate, inPredicate); } if (percentControl != null) { Predicate pcPredicate = builder.le(root.get("percentControl"), percentControl); predicate = predicate == null ? pcPredicate : builder.and(predicate, pcPredicate); } return predicate; } }; } /** * Returns a specification that looks for any {@code Audit} records matching the given criteria. * * @param user The start of a user name to filter on. Case is ignored. This may be {@code null} or empty string * to not filter on user. * @param action An action to filter on. This may be {@code null} to not filter on action. * @param ipAddress The start of an IP address to filter on. Case is ignored. This may be {@code null} or empty * string to not filter on IP address. * @param success Whether the action was successful. May be {@code null} to denote to ignore this property. * @param fromDate The starting date from which to fetch audits. May be {@code null}. * @param toDate The ending date to which to fetch audits. May be {@code null}. * @return The specification. */ public static Specification<Audit> auditRecordsMatching(String user, AuditAction action, String ipAddress, Boolean success, Date fromDate, Date toDate) { return new Specification<Audit>() { @Nullable @Override public Predicate toPredicate(Root<Audit> root, CriteriaQuery<?> query, CriteriaBuilder builder) { Predicate predicate = null; if (StringUtils.isNotBlank(user)) { predicate = builder.like(builder.lower(root.get("userName")), user.toLowerCase(Locale.US) + "%"); } if (action != null) { // Exact matches because no good way to do startsWith for enums Predicate actionPredicate = builder.equal(root.get("action"), action); predicate = predicate == null ? actionPredicate : builder.and(predicate, actionPredicate); } if (StringUtils.isNotBlank(ipAddress)) { Predicate ipPredicate = builder.like(root.get("ipAddress"), ipAddress + "%"); predicate = predicate == null ? ipPredicate : builder.and(predicate, ipPredicate); } if (success != null) { Predicate successPredicate = builder.equal(root.get("success"), success); predicate = predicate == null ? successPredicate : builder.and(predicate, successPredicate); } if (fromDate != null) { Predicate datePredicate = builder.greaterThanOrEqualTo(root.get("createDate"), fromDate); predicate = predicate == null ? datePredicate : builder.and(predicate, datePredicate); } if (toDate != null) { Predicate datePredicate = builder.lessThanOrEqualTo(root.get("createDate"), toDate); predicate = predicate == null ? datePredicate : builder.and(predicate, datePredicate); } return predicate; } }; } /** * Returns a specification that looks for any {@code Compound}s matching the following criteria. * * <ol> * <li>If part of a compound name is specified, any matching compounds must contain that * text in their names, ignoring case</li> * <li>One or more specified fields must be {@code null}</li> * </ol> * @param compoundNamePart The optional part of a compound name that must be matched, ignoring case. * This may be {@code null}. * @param possiblyNullFields The list of fields, of which at least 1 must be {@code null}. * @return The specification. */ public static Specification<Compound> hasNullFields(String compoundNamePart, String... possiblyNullFields) { return new Specification<Compound>() { @Nullable @Override public Predicate toPredicate(Root<Compound> root, CriteriaQuery<?> query, CriteriaBuilder builder) { // Convert the array of possibly-null field names to an array of Predicates Predicate[] possiblyNullFieldRestrictions = Arrays.stream(possiblyNullFields) .map(f -> builder.isNull(root.get(f))) .toArray(Predicate[]::new); // Main condition is any of those fields are null Predicate predicate = builder.or(possiblyNullFieldRestrictions); // If part of a compound name was specified, it must match as well if (StringUtils.isNotBlank(compoundNamePart)) { predicate = builder.and( predicate, builder.like(builder.lower(root.get("compoundName")), '%' + Util.escapeForLike(compoundNamePart.toLowerCase()) + '%') ); } return predicate; } }; } /** * Returns a specification that looks for any {@code Compound}s that are either hidden or not hidden, and * optionally, have their name match a given pattern. * * @param compoundNamePart The optional part of a compound name that must be matched, ignoring case. * This may be {@code null}. * @param hidden Whether to return hidden compounds (vs. not hidden compounds). * @return The specification. */ public static Specification<Compound> isHidden(String compoundNamePart, boolean hidden) { return new Specification<Compound>() { @Nullable @Override public Predicate toPredicate(Root<Compound> root, CriteriaQuery<?> query, CriteriaBuilder builder) { // Main condition is any compound that is hidden Predicate predicate = builder.equal(root.get("hidden"), hidden); // If part of a compound name was specified, it must match as well if (StringUtils.isNotBlank(compoundNamePart)) { predicate = builder.and( predicate, builder.like(builder.lower(root.get("compoundName")), '%' + Util.escapeForLike(compoundNamePart.toLowerCase()) + '%') ); } return predicate; } }; } /** * Returns a specification that looks for any {@code Compound}s matching the given criteria. * * @param compoundNamePart The optional part of a compound name that must be matched, ignoring case. * This may be {@code null}. * @param includeHidden Whether to include hidden compounds in the response. * @return The specification. */ public static Specification<Compound> standardSearch(String compoundNamePart, boolean includeHidden) { return new Specification<Compound>() { @Nullable @Override public Predicate toPredicate(Root<Compound> root, CriteriaQuery<?> query, CriteriaBuilder builder) { Predicate predicate = null; if (StringUtils.isNotBlank(compoundNamePart)) { predicate = builder.like(builder.lower(root.get("compoundName")), '%' + Util.escapeForLike(compoundNamePart.toLowerCase()) + '%'); } if (!includeHidden) { Predicate noHiddenPredicate = builder.isFalse(root.get("hidden")); predicate = predicate == null ? noHiddenPredicate : builder.and(predicate, noHiddenPredicate); } return predicate; } }; } }
mit
LaoZhongGu/RushServer
GameServer/src/com/skill/FightSkillMgr.java
9227
package com.skill; import java.util.ArrayList; import java.util.List; import com.BaseServer; import com.db.DBOption; import com.pbmessage.GamePBMsg.SkillChainMsg; import com.pbmessage.GamePBMsg.SkillInfoMsg; import com.pbmessage.GamePBMsg.SkillMsg; import com.player.DaoMgr; import com.player.GamePlayer; import com.player.ItemChangeType; import com.protocol.Protocol; import com.table.ConfigMgr; import com.table.SkillTemplateMgr; import com.util.Log; public class FightSkillMgr { private GamePlayer player; /** * 玩家所拥有的技能 */ private List<FightSkillUnit> playerSkillList; /** * 玩家技能链信息 */ private SkillChainInfo skillChainInfo; public FightSkillMgr(GamePlayer player) { this.player = player; playerSkillList = new ArrayList<FightSkillUnit>(); } /** * 从数据库中加载技能信息 */ public void loadFromDB() { int jobType = player.getJobId(); long userId = player.getUserId(); DaoMgr.fightSkillInfoDao.getFightSkillInfo(userId, jobType, playerSkillList); checkSkillUnlock(player.getPlayerLv(), jobType); skillChainInfo = DaoMgr.fightSkillInfoDao.getSkillChain(userId, jobType); if (skillChainInfo == null) { skillChainInfo = new SkillChainInfo(); int[] arySkillChain = new int[] { -2, -2, -2, -2, -2, -2 }; int skillLen = arySkillChain.length; for (int i = 0, len = arySkillChain.length; i < len; i++) { if (i < skillLen) { int index = 0; for (FightSkillUnit info : playerSkillList) { if (info.isActiveSkill() && index < skillLen) { arySkillChain[index++] = info.getSkillId(); } } index = 4; for (FightSkillUnit info : playerSkillList) { if (!info.isActiveSkill() && index < skillLen) { arySkillChain[index++] = info.getSkillId(); } } } } skillChainInfo.setArySkillChain(arySkillChain); skillChainInfo.setOp(DBOption.INSERT); } syncSkillInfo(); } /** * 根据等级检测技能是否可以解锁并把技能添加到角色身上 */ public void checkSkillUnlock(int level, int jobType) { FightSkillInfo[] arySkillInfo = SkillTemplateMgr.getInstance().getUnlockFightSkillInfo(jobType); for (int i = 0; i < arySkillInfo.length; i++) { FightSkillInfo info = arySkillInfo[i]; if (info != null) { int skillId = info.skillId; boolean isUnlock = level >= info.unlockLv && getSkillUnitBySkillId(skillId) == null; if (isUnlock) { FightSkillUnit newSkillInfo = new FightSkillUnit(); newSkillInfo.setSkillDBId(BaseServer.IDWORK.nextId()); newSkillInfo.setSkillId(skillId); newSkillInfo.setSkillLv(1); newSkillInfo.setActiveSkill(true); newSkillInfo.setOp(DBOption.INSERT); playerSkillList.add(newSkillInfo); } } } List<PassiveSkillInfo> skillInfoList = SkillTemplateMgr.getInstance().getPlayerPassiveSkill(jobType); for (PassiveSkillInfo info : skillInfoList) { int skillId = info.skillId; if (getSkillUnitBySkillId(skillId) == null) { FightSkillUnit newSkillInfo = new FightSkillUnit(); newSkillInfo.setSkillDBId(BaseServer.IDWORK.nextId()); newSkillInfo.setSkillId(skillId); newSkillInfo.setSkillLv(1); newSkillInfo.setActiveSkill(false); newSkillInfo.setOp(DBOption.INSERT); playerSkillList.add(newSkillInfo); } } } /** * 玩家升级之后解锁技能和同步技能信息给客户端 */ public void playerLvUpUnlockSkill(int level, int jobType) { checkSkillUnlock(level, jobType); syncSkillInfo(); } /** * 同步技能信息 */ public void syncSkillInfo() { SkillMsg.Builder netMsg = SkillMsg.newBuilder(); buildWrite(netMsg); player.sendPacket(Protocol.S_C_SKILL_INFO, netMsg); } public void buildWrite(SkillMsg.Builder netMsg) { for (FightSkillUnit info : playerSkillList) { SkillInfoMsg.Builder infoMsg = SkillInfoMsg.newBuilder(); infoMsg.setSkillId(info.getSkillId()); infoMsg.setSkillLv(info.getSkillLv()); infoMsg.setIsActiveSkill(info.isActiveSkill()); netMsg.addSkillInfoList(infoMsg); } int[] arySkillChain = skillChainInfo.getArySkillChain(); for (int i = 0; i < arySkillChain.length; i++) { netMsg.addSkillChainList(arySkillChain[i]); } } /** * 玩家升级技能,根据operType来确定是单独升级还是一键升级 */ public void skillLevelUp(int skillId, int upgradeType) { FightSkillUnit skillInfo = getSkillUnitBySkillId(skillId); if (skillInfo == null) { Log.error("skillLevelUp 技能Id为: " + skillId + " 并未学习," + "UserId: " + player.getUserId()); return; } int maxSkillLv = ConfigMgr.maxSkillLv; if (!skillInfo.isActiveSkill()) { maxSkillLv = 5; } int curSkillLv = skillInfo.getSkillLv(); if (curSkillLv == maxSkillLv) { Log.error("skillLevelUp 当前技能等级已达最高级,等级为: " + curSkillLv + ",技能Id为: " + skillId + ",UserId: " + player.getUserId()); return; } int costGold = 1000; if (skillInfo.isActiveSkill()) { costGold = SkillTemplateMgr.getInstance().getFightSkillInfo(player.getJobId(), skillId).upgradeGold; } else { costGold = SkillTemplateMgr.getInstance().getPassiveSkillInfo(skillId + curSkillLv - 1).upgradeGold; } while (player.removeGold(costGold, ItemChangeType.UPGRADE_SKILL)) { // 当技能等级升级限制小于等于玩家等级时 curSkillLv += 1; if (upgradeType == 1 || curSkillLv == maxSkillLv) { break; } } skillInfo.setSkillLv(curSkillLv); SkillInfoMsg.Builder netMsg = SkillInfoMsg.newBuilder(); netMsg.setSkillId(skillId); netMsg.setSkillLv(curSkillLv); player.sendPacket(Protocol.S_C_UPGRADE_SKILL, netMsg); } /** * 根据技能Id获得技能信息 */ private FightSkillUnit getSkillUnitBySkillId(int skillId) { for (FightSkillUnit skillInfo : playerSkillList) { if (skillInfo.getSkillId() == skillId) { return skillInfo; } } return null; } public void setFightSkillChain(SkillChainMsg msg) { int skillId = msg.getSkillId(); FightSkillUnit skillUnit = getSkillUnitBySkillId(skillId); if (skillUnit == null) { return; } int[] arySkillChain = skillChainInfo.getArySkillChain(); boolean isExchange = false; int skillPos = msg.getSkillSrcPos(); for (int i = 0, len = arySkillChain.length; i < len; i++) { if (skillId == arySkillChain[i]) { isExchange = true; exchangeSkillChain(skillPos, i + 1); break; } } if (!isExchange) { if (skillUnit.isActiveSkill() && skillPos >= 1 && skillPos <= 4) { arySkillChain[skillPos - 1] = skillId; } else if (!skillUnit.isActiveSkill() && skillPos >= 5 && skillPos <= 6) { arySkillChain[skillPos - 1] = skillId; } } skillChainInfo.setArySkillChain(arySkillChain); SkillMsg.Builder netMsg = SkillMsg.newBuilder(); for (int i = 0; i < arySkillChain.length; i++) { netMsg.addSkillChainList(arySkillChain[i]); } player.sendPacket(Protocol.S_C_FIGHT_SKILL_CHAIN, netMsg); } public void exchangeSkillChain(int srcPos, int destPos) { int[] arySkillChain = skillChainInfo.getArySkillChain(); int skillChainLen = arySkillChain.length; if (srcPos < 1 || srcPos > skillChainLen || destPos < 1 || destPos > skillChainLen) { return; } if ((srcPos == 5 || srcPos == 6) && (destPos == 6 || destPos == 5)) { int srcSkillId = arySkillChain[srcPos - 1]; arySkillChain[srcPos - 1] = arySkillChain[destPos - 1]; arySkillChain[destPos - 1] = srcSkillId; } else if (srcPos >= 1 && destPos >= 1) { int srcSkillId = arySkillChain[srcPos - 1]; arySkillChain[srcPos - 1] = arySkillChain[destPos - 1]; arySkillChain[destPos - 1] = srcSkillId; } skillChainInfo.setArySkillChain(arySkillChain); SkillMsg.Builder netMsg = SkillMsg.newBuilder(); for (int i = 0; i < arySkillChain.length; i++) { netMsg.addSkillChainList(arySkillChain[i]); } player.sendPacket(Protocol.S_C_FIGHT_SKILL_CHAIN, netMsg); } /** * 从内存中卸载玩家的技能数据 */ public void unloadData() { playerSkillList = null; skillChainInfo = null; } /** * 将玩家的技能信息保存到数据库中 */ public void saveToDB(int jobType) { long userId = player.getUserId(); try { List<FightSkillUnit> saveList = new ArrayList<FightSkillUnit>(playerSkillList); for (FightSkillUnit info : saveList) { if (info.getOp() == DBOption.INSERT) { DaoMgr.fightSkillInfoDao.addFightSkillInfo(userId, jobType, info); } if (info.getOp() == DBOption.UPDATE) { DaoMgr.fightSkillInfoDao.updateFightSkillInfo(userId, info); } if (skillChainInfo.getOp() == DBOption.INSERT) { DaoMgr.fightSkillInfoDao.insertSkillChain(userId, jobType, skillChainInfo); } else if (skillChainInfo.getOp() == DBOption.UPDATE) { DaoMgr.fightSkillInfoDao.updateSkillChain(userId, jobType, skillChainInfo); } } } catch (Exception e) { Log.error("保存玩家技能信息出错, UserId: " + userId, e); } } }
mit
F5Networks/f5-icontrol-library-java
src/main/java/iControl/Interfaces.java
157902
//=========================================================================== // // File : Interfaces.java // //--------------------------------------------------------------------------- // // The contents of this file are subject to the "END USER LICENSE AGREEMENT FOR F5 // Software Development Kit for iControl"; you may not use this file except in // compliance with the License. The License is included in the iControl // Software Development Kit. // // Software distributed under the License is distributed on an "AS IS" // basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See // the License for the specific language governing rights and limitations // under the License. // // The Original Code is iControl Code and related documentation // distributed by F5. // // The Initial Developer of the Original Code is F5 Networks, Inc. // Seattle, WA, USA. // Portions created by F5 are Copyright (C) 2006 F5 Networks, Inc. // All Rights Reserved. // iControl (TM) is a registered trademark of F5 Networks, Inc. // // Alternatively, the contents of this file may be used under the terms // of the GNU General Public License (the "GPL"), in which case the // provisions of GPL are applicable instead of those above. If you wish // to allow use of your version of this file only under the terms of the // GPL and not to allow others to use your version of this file under the // License, indicate your decision by deleting the provisions above and // replace them with the notice and other provisions required by the GPL. // If you do not delete the provisions above, a recipient may use your // version of this file under either the License or the GPL. // //=========================================================================== package iControl; import iControl.*; import java.util.*; import java.text.*; import java.lang.*; public class Interfaces extends Object { //------------------------------------------------------------------- // Member Variables //------------------------------------------------------------------- private ASMLoggingProfileBindingStub m_ASMLoggingProfile = null; private ASMPolicyBindingStub m_ASMPolicy = null; private ASMPolicyGroupBindingStub m_ASMPolicyGroup = null; private ASMSystemConfigurationBindingStub m_ASMSystemConfiguration = null; private ASMWebApplicationBindingStub m_ASMWebApplication = null; private ASMWebApplicationGroupBindingStub m_ASMWebApplicationGroup = null; private ClassificationApplicationBindingStub m_ClassificationApplication = null; private ClassificationCategoryBindingStub m_ClassificationCategory = null; private ClassificationSignatureDefinitionBindingStub m_ClassificationSignatureDefinition = null; private ClassificationSignatureUpdateScheduleBindingStub m_ClassificationSignatureUpdateSchedule = null; private ClassificationSignatureVersionBindingStub m_ClassificationSignatureVersion = null; private GlobalLBApplicationBindingStub m_GlobalLBApplication = null; private GlobalLBDataCenterBindingStub m_GlobalLBDataCenter = null; private GlobalLBDNSSECKeyBindingStub m_GlobalLBDNSSECKey = null; private GlobalLBDNSSECZoneBindingStub m_GlobalLBDNSSECZone = null; private GlobalLBGlobalsBindingStub m_GlobalLBGlobals = null; private GlobalLBLinkBindingStub m_GlobalLBLink = null; private GlobalLBMonitorBindingStub m_GlobalLBMonitor = null; private GlobalLBPoolBindingStub m_GlobalLBPool = null; private GlobalLBPoolMemberBindingStub m_GlobalLBPoolMember = null; private GlobalLBPoolV2BindingStub m_GlobalLBPoolV2 = null; private GlobalLBProberPoolBindingStub m_GlobalLBProberPool = null; private GlobalLBRegionBindingStub m_GlobalLBRegion = null; private GlobalLBRuleBindingStub m_GlobalLBRule = null; private GlobalLBServerBindingStub m_GlobalLBServer = null; private GlobalLBTopologyBindingStub m_GlobalLBTopology = null; private GlobalLBVirtualServerBindingStub m_GlobalLBVirtualServer = null; private GlobalLBVirtualServerV2BindingStub m_GlobalLBVirtualServerV2 = null; private GlobalLBWideIPBindingStub m_GlobalLBWideIP = null; private GlobalLBWideIPV2BindingStub m_GlobalLBWideIPV2 = null; private iCallPeriodicHandlerBindingStub m_iCallPeriodicHandler = null; private iCallPerpetualHandlerBindingStub m_iCallPerpetualHandler = null; private iCallScriptBindingStub m_iCallScript = null; private iCallTriggeredHandlerBindingStub m_iCallTriggeredHandler = null; private LocalLBALGLogProfileBindingStub m_LocalLBALGLogProfile = null; private LocalLBCipherGroupBindingStub m_LocalLBCipherGroup = null; private LocalLBCipherRuleBindingStub m_LocalLBCipherRule = null; private LocalLBClassBindingStub m_LocalLBClass = null; private LocalLBContentPolicyBindingStub m_LocalLBContentPolicy = null; private LocalLBContentPolicyStrategyBindingStub m_LocalLBContentPolicyStrategy = null; private LocalLBDataGroupFileBindingStub m_LocalLBDataGroupFile = null; private LocalLBDNSCacheBindingStub m_LocalLBDNSCache = null; private LocalLBDNSExpressBindingStub m_LocalLBDNSExpress = null; private LocalLBDNSGlobalsBindingStub m_LocalLBDNSGlobals = null; private LocalLBDNSServerBindingStub m_LocalLBDNSServer = null; private LocalLBDNSTSIGKeyBindingStub m_LocalLBDNSTSIGKey = null; private LocalLBDNSZoneBindingStub m_LocalLBDNSZone = null; private LocalLBFlowEvictionPolicyBindingStub m_LocalLBFlowEvictionPolicy = null; private LocalLBiFileBindingStub m_LocalLBiFile = null; private LocalLBiFileFileBindingStub m_LocalLBiFileFile = null; private LocalLBLSNLogProfileBindingStub m_LocalLBLSNLogProfile = null; private LocalLBLSNPoolBindingStub m_LocalLBLSNPool = null; private LocalLBMessageRoutingPeerBindingStub m_LocalLBMessageRoutingPeer = null; private LocalLBMessageRoutingSIPRouteBindingStub m_LocalLBMessageRoutingSIPRoute = null; private LocalLBMessageRoutingTransportConfigBindingStub m_LocalLBMessageRoutingTransportConfig = null; private LocalLBMonitorBindingStub m_LocalLBMonitor = null; private LocalLBNATBindingStub m_LocalLBNAT = null; private LocalLBNATV2BindingStub m_LocalLBNATV2 = null; private LocalLBNodeAddressBindingStub m_LocalLBNodeAddress = null; private LocalLBNodeAddressV2BindingStub m_LocalLBNodeAddressV2 = null; private LocalLBOCSPStaplingParametersBindingStub m_LocalLBOCSPStaplingParameters = null; private LocalLBPoolBindingStub m_LocalLBPool = null; private LocalLBPoolMemberBindingStub m_LocalLBPoolMember = null; private LocalLBProfileAnalyticsBindingStub m_LocalLBProfileAnalytics = null; private LocalLBProfileAuthBindingStub m_LocalLBProfileAuth = null; private LocalLBProfileClassificationBindingStub m_LocalLBProfileClassification = null; private LocalLBProfileClientLDAPBindingStub m_LocalLBProfileClientLDAP = null; private LocalLBProfileClientSSLBindingStub m_LocalLBProfileClientSSL = null; private LocalLBProfileDiameterBindingStub m_LocalLBProfileDiameter = null; private LocalLBProfileDiameterEndpointBindingStub m_LocalLBProfileDiameterEndpoint = null; private LocalLBProfileDiameterRouterBindingStub m_LocalLBProfileDiameterRouter = null; private LocalLBProfileDiameterSessionBindingStub m_LocalLBProfileDiameterSession = null; private LocalLBProfileDNSBindingStub m_LocalLBProfileDNS = null; private LocalLBProfileDNSLoggingBindingStub m_LocalLBProfileDNSLogging = null; private LocalLBProfileFastHttpBindingStub m_LocalLBProfileFastHttp = null; private LocalLBProfileFastL4BindingStub m_LocalLBProfileFastL4 = null; private LocalLBProfileFIXBindingStub m_LocalLBProfileFIX = null; private LocalLBProfileFTPBindingStub m_LocalLBProfileFTP = null; private LocalLBProfileHttpBindingStub m_LocalLBProfileHttp = null; private LocalLBProfileHttpClassBindingStub m_LocalLBProfileHttpClass = null; private LocalLBProfileHttpCompressionBindingStub m_LocalLBProfileHttpCompression = null; private LocalLBProfileICAPBindingStub m_LocalLBProfileICAP = null; private LocalLBProfileIIOPBindingStub m_LocalLBProfileIIOP = null; private LocalLBProfileIPsecALGBindingStub m_LocalLBProfileIPsecALG = null; private LocalLBProfileOneConnectBindingStub m_LocalLBProfileOneConnect = null; private LocalLBProfilePCPBindingStub m_LocalLBProfilePCP = null; private LocalLBProfilePersistenceBindingStub m_LocalLBProfilePersistence = null; private LocalLBProfilePPTPBindingStub m_LocalLBProfilePPTP = null; private LocalLBProfileRADIUSBindingStub m_LocalLBProfileRADIUS = null; private LocalLBProfileRequestAdaptBindingStub m_LocalLBProfileRequestAdapt = null; private LocalLBProfileRequestLoggingBindingStub m_LocalLBProfileRequestLogging = null; private LocalLBProfileResponseAdaptBindingStub m_LocalLBProfileResponseAdapt = null; private LocalLBProfileRTSPBindingStub m_LocalLBProfileRTSP = null; private LocalLBProfileSCTPBindingStub m_LocalLBProfileSCTP = null; private LocalLBProfileServerLDAPBindingStub m_LocalLBProfileServerLDAP = null; private LocalLBProfileServerSSLBindingStub m_LocalLBProfileServerSSL = null; private LocalLBProfileSIPBindingStub m_LocalLBProfileSIP = null; private LocalLBProfileSIPRouterBindingStub m_LocalLBProfileSIPRouter = null; private LocalLBProfileSIPSessionBindingStub m_LocalLBProfileSIPSession = null; private LocalLBProfileSMTPSBindingStub m_LocalLBProfileSMTPS = null; private LocalLBProfileSPDYBindingStub m_LocalLBProfileSPDY = null; private LocalLBProfileSPMBindingStub m_LocalLBProfileSPM = null; private LocalLBProfileStreamBindingStub m_LocalLBProfileStream = null; private LocalLBProfileTCPBindingStub m_LocalLBProfileTCP = null; private LocalLBProfileTCPAnalyticsBindingStub m_LocalLBProfileTCPAnalytics = null; private LocalLBProfileTFTPBindingStub m_LocalLBProfileTFTP = null; private LocalLBProfileTrafficAccelerationBindingStub m_LocalLBProfileTrafficAcceleration = null; private LocalLBProfileUDPBindingStub m_LocalLBProfileUDP = null; private LocalLBProfileUserStatisticBindingStub m_LocalLBProfileUserStatistic = null; private LocalLBProfileWebAccelerationBindingStub m_LocalLBProfileWebAcceleration = null; private LocalLBProfileXMLBindingStub m_LocalLBProfileXML = null; private LocalLBRAMCacheInformationBindingStub m_LocalLBRAMCacheInformation = null; private LocalLBRateClassBindingStub m_LocalLBRateClass = null; private LocalLBRuleBindingStub m_LocalLBRule = null; private LocalLBSNATBindingStub m_LocalLBSNAT = null; private LocalLBSNATPoolBindingStub m_LocalLBSNATPool = null; private LocalLBSNATPoolMemberBindingStub m_LocalLBSNATPoolMember = null; private LocalLBSNATTranslationAddressBindingStub m_LocalLBSNATTranslationAddress = null; private LocalLBSNATTranslationAddressV2BindingStub m_LocalLBSNATTranslationAddressV2 = null; private LocalLBVirtualAddressBindingStub m_LocalLBVirtualAddress = null; private LocalLBVirtualAddressV2BindingStub m_LocalLBVirtualAddressV2 = null; private LocalLBVirtualServerBindingStub m_LocalLBVirtualServer = null; private LogDestinationArcSightBindingStub m_LogDestinationArcSight = null; private LogDestinationIPFIXBindingStub m_LogDestinationIPFIX = null; private LogDestinationLocalSyslogBindingStub m_LogDestinationLocalSyslog = null; private LogDestinationManagementPortBindingStub m_LogDestinationManagementPort = null; private LogDestinationRemoteHighSpeedLogBindingStub m_LogDestinationRemoteHighSpeedLog = null; private LogDestinationRemoteSyslogBindingStub m_LogDestinationRemoteSyslog = null; private LogDestinationSplunkBindingStub m_LogDestinationSplunk = null; private LogFilterBindingStub m_LogFilter = null; private LogIPFIXInformationElementBindingStub m_LogIPFIXInformationElement = null; private LogPublisherBindingStub m_LogPublisher = null; private LTConfigClassBindingStub m_LTConfigClass = null; private LTConfigFieldBindingStub m_LTConfigField = null; private ManagementApplicationPresentationScriptBindingStub m_ManagementApplicationPresentationScript = null; private ManagementApplicationServiceBindingStub m_ManagementApplicationService = null; private ManagementApplicationTemplateBindingStub m_ManagementApplicationTemplate = null; private ManagementCCLDAPConfigurationBindingStub m_ManagementCCLDAPConfiguration = null; private ManagementCertificateValidatorOCSPBindingStub m_ManagementCertificateValidatorOCSP = null; private ManagementCertLDAPConfigurationBindingStub m_ManagementCertLDAPConfiguration = null; private ManagementCLIScriptBindingStub m_ManagementCLIScript = null; private ManagementCRLDPConfigurationBindingStub m_ManagementCRLDPConfiguration = null; private ManagementCRLDPServerBindingStub m_ManagementCRLDPServer = null; private ManagementDBVariableBindingStub m_ManagementDBVariable = null; private ManagementDeviceBindingStub m_ManagementDevice = null; private ManagementDeviceGroupBindingStub m_ManagementDeviceGroup = null; private ManagementEMBindingStub m_ManagementEM = null; private ManagementEventNotificationBindingStub m_ManagementEventNotification = null; private ManagementEventSubscriptionBindingStub m_ManagementEventSubscription = null; private ManagementFeatureModuleBindingStub m_ManagementFeatureModule = null; private ManagementFolderBindingStub m_ManagementFolder = null; private ManagementGlobalsBindingStub m_ManagementGlobals = null; private ManagementKeyCertificateBindingStub m_ManagementKeyCertificate = null; private ManagementLDAPConfigurationBindingStub m_ManagementLDAPConfiguration = null; private ManagementLicenseAdministrationBindingStub m_ManagementLicenseAdministration = null; private ManagementNamedBindingStub m_ManagementNamed = null; private ManagementOCSPConfigurationBindingStub m_ManagementOCSPConfiguration = null; private ManagementOCSPResponderBindingStub m_ManagementOCSPResponder = null; private ManagementPartitionBindingStub m_ManagementPartition = null; private ManagementProvisionBindingStub m_ManagementProvision = null; private ManagementRADIUSConfigurationBindingStub m_ManagementRADIUSConfiguration = null; private ManagementRADIUSServerBindingStub m_ManagementRADIUSServer = null; private ManagementResourceRecordBindingStub m_ManagementResourceRecord = null; private ManagementSFlowDataSourceBindingStub m_ManagementSFlowDataSource = null; private ManagementSFlowGlobalsBindingStub m_ManagementSFlowGlobals = null; private ManagementSFlowReceiverBindingStub m_ManagementSFlowReceiver = null; private ManagementSMTPConfigurationBindingStub m_ManagementSMTPConfiguration = null; private ManagementSNMPConfigurationBindingStub m_ManagementSNMPConfiguration = null; private ManagementTACACSConfigurationBindingStub m_ManagementTACACSConfiguration = null; private ManagementTMOSModuleBindingStub m_ManagementTMOSModule = null; private ManagementTrafficGroupBindingStub m_ManagementTrafficGroup = null; private ManagementTrustBindingStub m_ManagementTrust = null; private ManagementUserManagementBindingStub m_ManagementUserManagement = null; private ManagementViewBindingStub m_ManagementView = null; private ManagementZoneBindingStub m_ManagementZone = null; private ManagementZoneRunnerBindingStub m_ManagementZoneRunner = null; private NetworkingAdminIPBindingStub m_NetworkingAdminIP = null; private NetworkingARPBindingStub m_NetworkingARP = null; private NetworkingBWControllerPolicyBindingStub m_NetworkingBWControllerPolicy = null; private NetworkingBWPriorityGroupBindingStub m_NetworkingBWPriorityGroup = null; private NetworkingDNSResolverBindingStub m_NetworkingDNSResolver = null; private NetworkingInterfacesBindingStub m_NetworkingInterfaces = null; private NetworkingIPsecIkeDaemonBindingStub m_NetworkingIPsecIkeDaemon = null; private NetworkingIPsecIkePeerBindingStub m_NetworkingIPsecIkePeer = null; private NetworkingIPsecManualSecurityAssociationBindingStub m_NetworkingIPsecManualSecurityAssociation = null; private NetworkingIPsecPolicyBindingStub m_NetworkingIPsecPolicy = null; private NetworkingIPsecTrafficSelectorBindingStub m_NetworkingIPsecTrafficSelector = null; private NetworkingiSessionAdvertisedRouteBindingStub m_NetworkingiSessionAdvertisedRoute = null; private NetworkingiSessionAdvertisedRouteV2BindingStub m_NetworkingiSessionAdvertisedRouteV2 = null; private NetworkingiSessionDatastorBindingStub m_NetworkingiSessionDatastor = null; private NetworkingiSessionDeduplicationBindingStub m_NetworkingiSessionDeduplication = null; private NetworkingiSessionLocalInterfaceBindingStub m_NetworkingiSessionLocalInterface = null; private NetworkingiSessionPeerDiscoveryBindingStub m_NetworkingiSessionPeerDiscovery = null; private NetworkingiSessionRemoteInterfaceBindingStub m_NetworkingiSessionRemoteInterface = null; private NetworkingiSessionRemoteInterfaceV2BindingStub m_NetworkingiSessionRemoteInterfaceV2 = null; private NetworkingLLDPGlobalsBindingStub m_NetworkingLLDPGlobals = null; private NetworkingMulticastRouteBindingStub m_NetworkingMulticastRoute = null; private NetworkingPacketFilterBindingStub m_NetworkingPacketFilter = null; private NetworkingPacketFilterGlobalsBindingStub m_NetworkingPacketFilterGlobals = null; private NetworkingPortMirrorBindingStub m_NetworkingPortMirror = null; private NetworkingProfileFECBindingStub m_NetworkingProfileFEC = null; private NetworkingProfileGeneveBindingStub m_NetworkingProfileGeneve = null; private NetworkingProfileGREBindingStub m_NetworkingProfileGRE = null; private NetworkingProfileIPIPBindingStub m_NetworkingProfileIPIP = null; private NetworkingProfileIPsecBindingStub m_NetworkingProfileIPsec = null; private NetworkingProfileLightweight4Over6TunnelBindingStub m_NetworkingProfileLightweight4Over6Tunnel = null; private NetworkingProfileMAPBindingStub m_NetworkingProfileMAP = null; private NetworkingProfileV6RDBindingStub m_NetworkingProfileV6RD = null; private NetworkingProfileVXLANBindingStub m_NetworkingProfileVXLAN = null; private NetworkingProfileWCCPGREBindingStub m_NetworkingProfileWCCPGRE = null; private NetworkingRouteDomainBindingStub m_NetworkingRouteDomain = null; private NetworkingRouteDomainV2BindingStub m_NetworkingRouteDomainV2 = null; private NetworkingRouterAdvertisementBindingStub m_NetworkingRouterAdvertisement = null; private NetworkingRouteTableBindingStub m_NetworkingRouteTable = null; private NetworkingRouteTableV2BindingStub m_NetworkingRouteTableV2 = null; private NetworkingSelfIPBindingStub m_NetworkingSelfIP = null; private NetworkingSelfIPPortLockdownBindingStub m_NetworkingSelfIPPortLockdown = null; private NetworkingSelfIPV2BindingStub m_NetworkingSelfIPV2 = null; private NetworkingSTPGlobalsBindingStub m_NetworkingSTPGlobals = null; private NetworkingSTPInstanceBindingStub m_NetworkingSTPInstance = null; private NetworkingSTPInstanceV2BindingStub m_NetworkingSTPInstanceV2 = null; private NetworkingTrunkBindingStub m_NetworkingTrunk = null; private NetworkingTunnelBindingStub m_NetworkingTunnel = null; private NetworkingVLANBindingStub m_NetworkingVLAN = null; private NetworkingVLANGroupBindingStub m_NetworkingVLANGroup = null; private PEMFormatScriptBindingStub m_PEMFormatScript = null; private PEMForwardingEndpointBindingStub m_PEMForwardingEndpoint = null; private PEMInterceptionEndpointBindingStub m_PEMInterceptionEndpoint = null; private PEMListenerBindingStub m_PEMListener = null; private PEMPolicyBindingStub m_PEMPolicy = null; private PEMServiceChainEndpointBindingStub m_PEMServiceChainEndpoint = null; private PEMSubscriberBindingStub m_PEMSubscriber = null; private SecurityDoSDeviceBindingStub m_SecurityDoSDevice = null; private SecurityDoSWhitelistBindingStub m_SecurityDoSWhitelist = null; private SecurityFirewallAddressListBindingStub m_SecurityFirewallAddressList = null; private SecurityFirewallGlobalAdminIPRuleListBindingStub m_SecurityFirewallGlobalAdminIPRuleList = null; private SecurityFirewallGlobalRuleListBindingStub m_SecurityFirewallGlobalRuleList = null; private SecurityFirewallPolicyBindingStub m_SecurityFirewallPolicy = null; private SecurityFirewallPortListBindingStub m_SecurityFirewallPortList = null; private SecurityFirewallRuleListBindingStub m_SecurityFirewallRuleList = null; private SecurityFirewallWeeklyScheduleBindingStub m_SecurityFirewallWeeklySchedule = null; private SecurityIPIntelligenceBlacklistCategoryBindingStub m_SecurityIPIntelligenceBlacklistCategory = null; private SecurityIPIntelligenceFeedListBindingStub m_SecurityIPIntelligenceFeedList = null; private SecurityIPIntelligenceGlobalPolicyBindingStub m_SecurityIPIntelligenceGlobalPolicy = null; private SecurityIPIntelligencePolicyBindingStub m_SecurityIPIntelligencePolicy = null; private SecurityLogProfileBindingStub m_SecurityLogProfile = null; private SecurityProfileDNSSecurityBindingStub m_SecurityProfileDNSSecurity = null; private SecurityProfileDoSBindingStub m_SecurityProfileDoS = null; private SecurityProfileIPIntelligenceBindingStub m_SecurityProfileIPIntelligence = null; private SystemCABundleManagerBindingStub m_SystemCABundleManager = null; private SystemCertificateRevocationListFileBindingStub m_SystemCertificateRevocationListFile = null; private SystemClusterBindingStub m_SystemCluster = null; private SystemConfigSyncBindingStub m_SystemConfigSync = null; private SystemCryptoClientBindingStub m_SystemCryptoClient = null; private SystemCryptoServerBindingStub m_SystemCryptoServer = null; private SystemDiskBindingStub m_SystemDisk = null; private SystemExternalMonitorFileBindingStub m_SystemExternalMonitorFile = null; private SystemFailoverBindingStub m_SystemFailover = null; private SystemGeoIPBindingStub m_SystemGeoIP = null; private SystemHAGroupBindingStub m_SystemHAGroup = null; private SystemHAStatusBindingStub m_SystemHAStatus = null; private SystemInetBindingStub m_SystemInet = null; private SystemLightweightTunnelTableFileBindingStub m_SystemLightweightTunnelTableFile = null; private SystemPerformanceSFlowBindingStub m_SystemPerformanceSFlow = null; private SystemServicesBindingStub m_SystemServices = null; private SystemSessionBindingStub m_SystemSession = null; private SystemSoftwareManagementBindingStub m_SystemSoftwareManagement = null; private SystemStatisticsBindingStub m_SystemStatistics = null; private SystemSystemInfoBindingStub m_SystemSystemInfo = null; private SystemVCMPBindingStub m_SystemVCMP = null; private WebAcceleratorApplicationsBindingStub m_WebAcceleratorApplications = null; private WebAcceleratorPoliciesBindingStub m_WebAcceleratorPolicies = null; private Boolean m_bInitialized = false; private int m_timeout = 60000; private String m_hostname = ""; private long m_port = 443; private String m_username = ""; private String m_password = ""; private void setupInterface(org.apache.axis.client.Stub stub) { stub.setTimeout(m_timeout); stub.setUsername(m_username); stub.setPassword(m_password); } //------------------------------------------------------------------- // public member accessors //------------------------------------------------------------------- public ASMLoggingProfileBindingStub getASMLoggingProfile() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_ASMLoggingProfile ) { m_ASMLoggingProfile = (iControl.ASMLoggingProfileBindingStub) new iControl.ASMLoggingProfileLocator().getASMLoggingProfilePort(new java.net.URL(buildURL())); } setupInterface(m_ASMLoggingProfile); return m_ASMLoggingProfile;} public ASMPolicyBindingStub getASMPolicy() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_ASMPolicy ) { m_ASMPolicy = (iControl.ASMPolicyBindingStub) new iControl.ASMPolicyLocator().getASMPolicyPort(new java.net.URL(buildURL())); } setupInterface(m_ASMPolicy); return m_ASMPolicy;} public ASMPolicyGroupBindingStub getASMPolicyGroup() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_ASMPolicyGroup ) { m_ASMPolicyGroup = (iControl.ASMPolicyGroupBindingStub) new iControl.ASMPolicyGroupLocator().getASMPolicyGroupPort(new java.net.URL(buildURL())); } setupInterface(m_ASMPolicyGroup); return m_ASMPolicyGroup;} public ASMSystemConfigurationBindingStub getASMSystemConfiguration() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_ASMSystemConfiguration ) { m_ASMSystemConfiguration = (iControl.ASMSystemConfigurationBindingStub) new iControl.ASMSystemConfigurationLocator().getASMSystemConfigurationPort(new java.net.URL(buildURL())); } setupInterface(m_ASMSystemConfiguration); return m_ASMSystemConfiguration;} public ASMWebApplicationBindingStub getASMWebApplication() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_ASMWebApplication ) { m_ASMWebApplication = (iControl.ASMWebApplicationBindingStub) new iControl.ASMWebApplicationLocator().getASMWebApplicationPort(new java.net.URL(buildURL())); } setupInterface(m_ASMWebApplication); return m_ASMWebApplication;} public ASMWebApplicationGroupBindingStub getASMWebApplicationGroup() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_ASMWebApplicationGroup ) { m_ASMWebApplicationGroup = (iControl.ASMWebApplicationGroupBindingStub) new iControl.ASMWebApplicationGroupLocator().getASMWebApplicationGroupPort(new java.net.URL(buildURL())); } setupInterface(m_ASMWebApplicationGroup); return m_ASMWebApplicationGroup;} public ClassificationApplicationBindingStub getClassificationApplication() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_ClassificationApplication ) { m_ClassificationApplication = (iControl.ClassificationApplicationBindingStub) new iControl.ClassificationApplicationLocator().getClassificationApplicationPort(new java.net.URL(buildURL())); } setupInterface(m_ClassificationApplication); return m_ClassificationApplication;} public ClassificationCategoryBindingStub getClassificationCategory() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_ClassificationCategory ) { m_ClassificationCategory = (iControl.ClassificationCategoryBindingStub) new iControl.ClassificationCategoryLocator().getClassificationCategoryPort(new java.net.URL(buildURL())); } setupInterface(m_ClassificationCategory); return m_ClassificationCategory;} public ClassificationSignatureDefinitionBindingStub getClassificationSignatureDefinition() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_ClassificationSignatureDefinition ) { m_ClassificationSignatureDefinition = (iControl.ClassificationSignatureDefinitionBindingStub) new iControl.ClassificationSignatureDefinitionLocator().getClassificationSignatureDefinitionPort(new java.net.URL(buildURL())); } setupInterface(m_ClassificationSignatureDefinition); return m_ClassificationSignatureDefinition;} public ClassificationSignatureUpdateScheduleBindingStub getClassificationSignatureUpdateSchedule() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_ClassificationSignatureUpdateSchedule ) { m_ClassificationSignatureUpdateSchedule = (iControl.ClassificationSignatureUpdateScheduleBindingStub) new iControl.ClassificationSignatureUpdateScheduleLocator().getClassificationSignatureUpdateSchedulePort(new java.net.URL(buildURL())); } setupInterface(m_ClassificationSignatureUpdateSchedule); return m_ClassificationSignatureUpdateSchedule;} public ClassificationSignatureVersionBindingStub getClassificationSignatureVersion() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_ClassificationSignatureVersion ) { m_ClassificationSignatureVersion = (iControl.ClassificationSignatureVersionBindingStub) new iControl.ClassificationSignatureVersionLocator().getClassificationSignatureVersionPort(new java.net.URL(buildURL())); } setupInterface(m_ClassificationSignatureVersion); return m_ClassificationSignatureVersion;} public GlobalLBApplicationBindingStub getGlobalLBApplication() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_GlobalLBApplication ) { m_GlobalLBApplication = (iControl.GlobalLBApplicationBindingStub) new iControl.GlobalLBApplicationLocator().getGlobalLBApplicationPort(new java.net.URL(buildURL())); } setupInterface(m_GlobalLBApplication); return m_GlobalLBApplication;} public GlobalLBDataCenterBindingStub getGlobalLBDataCenter() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_GlobalLBDataCenter ) { m_GlobalLBDataCenter = (iControl.GlobalLBDataCenterBindingStub) new iControl.GlobalLBDataCenterLocator().getGlobalLBDataCenterPort(new java.net.URL(buildURL())); } setupInterface(m_GlobalLBDataCenter); return m_GlobalLBDataCenter;} public GlobalLBDNSSECKeyBindingStub getGlobalLBDNSSECKey() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_GlobalLBDNSSECKey ) { m_GlobalLBDNSSECKey = (iControl.GlobalLBDNSSECKeyBindingStub) new iControl.GlobalLBDNSSECKeyLocator().getGlobalLBDNSSECKeyPort(new java.net.URL(buildURL())); } setupInterface(m_GlobalLBDNSSECKey); return m_GlobalLBDNSSECKey;} public GlobalLBDNSSECZoneBindingStub getGlobalLBDNSSECZone() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_GlobalLBDNSSECZone ) { m_GlobalLBDNSSECZone = (iControl.GlobalLBDNSSECZoneBindingStub) new iControl.GlobalLBDNSSECZoneLocator().getGlobalLBDNSSECZonePort(new java.net.URL(buildURL())); } setupInterface(m_GlobalLBDNSSECZone); return m_GlobalLBDNSSECZone;} public GlobalLBGlobalsBindingStub getGlobalLBGlobals() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_GlobalLBGlobals ) { m_GlobalLBGlobals = (iControl.GlobalLBGlobalsBindingStub) new iControl.GlobalLBGlobalsLocator().getGlobalLBGlobalsPort(new java.net.URL(buildURL())); } setupInterface(m_GlobalLBGlobals); return m_GlobalLBGlobals;} public GlobalLBLinkBindingStub getGlobalLBLink() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_GlobalLBLink ) { m_GlobalLBLink = (iControl.GlobalLBLinkBindingStub) new iControl.GlobalLBLinkLocator().getGlobalLBLinkPort(new java.net.URL(buildURL())); } setupInterface(m_GlobalLBLink); return m_GlobalLBLink;} public GlobalLBMonitorBindingStub getGlobalLBMonitor() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_GlobalLBMonitor ) { m_GlobalLBMonitor = (iControl.GlobalLBMonitorBindingStub) new iControl.GlobalLBMonitorLocator().getGlobalLBMonitorPort(new java.net.URL(buildURL())); } setupInterface(m_GlobalLBMonitor); return m_GlobalLBMonitor;} public GlobalLBPoolBindingStub getGlobalLBPool() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_GlobalLBPool ) { m_GlobalLBPool = (iControl.GlobalLBPoolBindingStub) new iControl.GlobalLBPoolLocator().getGlobalLBPoolPort(new java.net.URL(buildURL())); } setupInterface(m_GlobalLBPool); return m_GlobalLBPool;} public GlobalLBPoolMemberBindingStub getGlobalLBPoolMember() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_GlobalLBPoolMember ) { m_GlobalLBPoolMember = (iControl.GlobalLBPoolMemberBindingStub) new iControl.GlobalLBPoolMemberLocator().getGlobalLBPoolMemberPort(new java.net.URL(buildURL())); } setupInterface(m_GlobalLBPoolMember); return m_GlobalLBPoolMember;} public GlobalLBPoolV2BindingStub getGlobalLBPoolV2() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_GlobalLBPoolV2 ) { m_GlobalLBPoolV2 = (iControl.GlobalLBPoolV2BindingStub) new iControl.GlobalLBPoolV2Locator().getGlobalLBPoolV2Port(new java.net.URL(buildURL())); } setupInterface(m_GlobalLBPoolV2); return m_GlobalLBPoolV2;} public GlobalLBProberPoolBindingStub getGlobalLBProberPool() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_GlobalLBProberPool ) { m_GlobalLBProberPool = (iControl.GlobalLBProberPoolBindingStub) new iControl.GlobalLBProberPoolLocator().getGlobalLBProberPoolPort(new java.net.URL(buildURL())); } setupInterface(m_GlobalLBProberPool); return m_GlobalLBProberPool;} public GlobalLBRegionBindingStub getGlobalLBRegion() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_GlobalLBRegion ) { m_GlobalLBRegion = (iControl.GlobalLBRegionBindingStub) new iControl.GlobalLBRegionLocator().getGlobalLBRegionPort(new java.net.URL(buildURL())); } setupInterface(m_GlobalLBRegion); return m_GlobalLBRegion;} public GlobalLBRuleBindingStub getGlobalLBRule() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_GlobalLBRule ) { m_GlobalLBRule = (iControl.GlobalLBRuleBindingStub) new iControl.GlobalLBRuleLocator().getGlobalLBRulePort(new java.net.URL(buildURL())); } setupInterface(m_GlobalLBRule); return m_GlobalLBRule;} public GlobalLBServerBindingStub getGlobalLBServer() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_GlobalLBServer ) { m_GlobalLBServer = (iControl.GlobalLBServerBindingStub) new iControl.GlobalLBServerLocator().getGlobalLBServerPort(new java.net.URL(buildURL())); } setupInterface(m_GlobalLBServer); return m_GlobalLBServer;} public GlobalLBTopologyBindingStub getGlobalLBTopology() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_GlobalLBTopology ) { m_GlobalLBTopology = (iControl.GlobalLBTopologyBindingStub) new iControl.GlobalLBTopologyLocator().getGlobalLBTopologyPort(new java.net.URL(buildURL())); } setupInterface(m_GlobalLBTopology); return m_GlobalLBTopology;} public GlobalLBVirtualServerBindingStub getGlobalLBVirtualServer() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_GlobalLBVirtualServer ) { m_GlobalLBVirtualServer = (iControl.GlobalLBVirtualServerBindingStub) new iControl.GlobalLBVirtualServerLocator().getGlobalLBVirtualServerPort(new java.net.URL(buildURL())); } setupInterface(m_GlobalLBVirtualServer); return m_GlobalLBVirtualServer;} public GlobalLBVirtualServerV2BindingStub getGlobalLBVirtualServerV2() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_GlobalLBVirtualServerV2 ) { m_GlobalLBVirtualServerV2 = (iControl.GlobalLBVirtualServerV2BindingStub) new iControl.GlobalLBVirtualServerV2Locator().getGlobalLBVirtualServerV2Port(new java.net.URL(buildURL())); } setupInterface(m_GlobalLBVirtualServerV2); return m_GlobalLBVirtualServerV2;} public GlobalLBWideIPBindingStub getGlobalLBWideIP() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_GlobalLBWideIP ) { m_GlobalLBWideIP = (iControl.GlobalLBWideIPBindingStub) new iControl.GlobalLBWideIPLocator().getGlobalLBWideIPPort(new java.net.URL(buildURL())); } setupInterface(m_GlobalLBWideIP); return m_GlobalLBWideIP;} public GlobalLBWideIPV2BindingStub getGlobalLBWideIPV2() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_GlobalLBWideIPV2 ) { m_GlobalLBWideIPV2 = (iControl.GlobalLBWideIPV2BindingStub) new iControl.GlobalLBWideIPV2Locator().getGlobalLBWideIPV2Port(new java.net.URL(buildURL())); } setupInterface(m_GlobalLBWideIPV2); return m_GlobalLBWideIPV2;} public iCallPeriodicHandlerBindingStub getiCallPeriodicHandler() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_iCallPeriodicHandler ) { m_iCallPeriodicHandler = (iControl.iCallPeriodicHandlerBindingStub) new iControl.iCallPeriodicHandlerLocator().getiCallPeriodicHandlerPort(new java.net.URL(buildURL())); } setupInterface(m_iCallPeriodicHandler); return m_iCallPeriodicHandler;} public iCallPerpetualHandlerBindingStub getiCallPerpetualHandler() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_iCallPerpetualHandler ) { m_iCallPerpetualHandler = (iControl.iCallPerpetualHandlerBindingStub) new iControl.iCallPerpetualHandlerLocator().getiCallPerpetualHandlerPort(new java.net.URL(buildURL())); } setupInterface(m_iCallPerpetualHandler); return m_iCallPerpetualHandler;} public iCallScriptBindingStub getiCallScript() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_iCallScript ) { m_iCallScript = (iControl.iCallScriptBindingStub) new iControl.iCallScriptLocator().getiCallScriptPort(new java.net.URL(buildURL())); } setupInterface(m_iCallScript); return m_iCallScript;} public iCallTriggeredHandlerBindingStub getiCallTriggeredHandler() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_iCallTriggeredHandler ) { m_iCallTriggeredHandler = (iControl.iCallTriggeredHandlerBindingStub) new iControl.iCallTriggeredHandlerLocator().getiCallTriggeredHandlerPort(new java.net.URL(buildURL())); } setupInterface(m_iCallTriggeredHandler); return m_iCallTriggeredHandler;} public LocalLBALGLogProfileBindingStub getLocalLBALGLogProfile() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_LocalLBALGLogProfile ) { m_LocalLBALGLogProfile = (iControl.LocalLBALGLogProfileBindingStub) new iControl.LocalLBALGLogProfileLocator().getLocalLBALGLogProfilePort(new java.net.URL(buildURL())); } setupInterface(m_LocalLBALGLogProfile); return m_LocalLBALGLogProfile;} public LocalLBCipherGroupBindingStub getLocalLBCipherGroup() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_LocalLBCipherGroup ) { m_LocalLBCipherGroup = (iControl.LocalLBCipherGroupBindingStub) new iControl.LocalLBCipherGroupLocator().getLocalLBCipherGroupPort(new java.net.URL(buildURL())); } setupInterface(m_LocalLBCipherGroup); return m_LocalLBCipherGroup;} public LocalLBCipherRuleBindingStub getLocalLBCipherRule() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_LocalLBCipherRule ) { m_LocalLBCipherRule = (iControl.LocalLBCipherRuleBindingStub) new iControl.LocalLBCipherRuleLocator().getLocalLBCipherRulePort(new java.net.URL(buildURL())); } setupInterface(m_LocalLBCipherRule); return m_LocalLBCipherRule;} public LocalLBClassBindingStub getLocalLBClass() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_LocalLBClass ) { m_LocalLBClass = (iControl.LocalLBClassBindingStub) new iControl.LocalLBClassLocator().getLocalLBClassPort(new java.net.URL(buildURL())); } setupInterface(m_LocalLBClass); return m_LocalLBClass;} public LocalLBContentPolicyBindingStub getLocalLBContentPolicy() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_LocalLBContentPolicy ) { m_LocalLBContentPolicy = (iControl.LocalLBContentPolicyBindingStub) new iControl.LocalLBContentPolicyLocator().getLocalLBContentPolicyPort(new java.net.URL(buildURL())); } setupInterface(m_LocalLBContentPolicy); return m_LocalLBContentPolicy;} public LocalLBContentPolicyStrategyBindingStub getLocalLBContentPolicyStrategy() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_LocalLBContentPolicyStrategy ) { m_LocalLBContentPolicyStrategy = (iControl.LocalLBContentPolicyStrategyBindingStub) new iControl.LocalLBContentPolicyStrategyLocator().getLocalLBContentPolicyStrategyPort(new java.net.URL(buildURL())); } setupInterface(m_LocalLBContentPolicyStrategy); return m_LocalLBContentPolicyStrategy;} public LocalLBDataGroupFileBindingStub getLocalLBDataGroupFile() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_LocalLBDataGroupFile ) { m_LocalLBDataGroupFile = (iControl.LocalLBDataGroupFileBindingStub) new iControl.LocalLBDataGroupFileLocator().getLocalLBDataGroupFilePort(new java.net.URL(buildURL())); } setupInterface(m_LocalLBDataGroupFile); return m_LocalLBDataGroupFile;} public LocalLBDNSCacheBindingStub getLocalLBDNSCache() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_LocalLBDNSCache ) { m_LocalLBDNSCache = (iControl.LocalLBDNSCacheBindingStub) new iControl.LocalLBDNSCacheLocator().getLocalLBDNSCachePort(new java.net.URL(buildURL())); } setupInterface(m_LocalLBDNSCache); return m_LocalLBDNSCache;} public LocalLBDNSExpressBindingStub getLocalLBDNSExpress() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_LocalLBDNSExpress ) { m_LocalLBDNSExpress = (iControl.LocalLBDNSExpressBindingStub) new iControl.LocalLBDNSExpressLocator().getLocalLBDNSExpressPort(new java.net.URL(buildURL())); } setupInterface(m_LocalLBDNSExpress); return m_LocalLBDNSExpress;} public LocalLBDNSGlobalsBindingStub getLocalLBDNSGlobals() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_LocalLBDNSGlobals ) { m_LocalLBDNSGlobals = (iControl.LocalLBDNSGlobalsBindingStub) new iControl.LocalLBDNSGlobalsLocator().getLocalLBDNSGlobalsPort(new java.net.URL(buildURL())); } setupInterface(m_LocalLBDNSGlobals); return m_LocalLBDNSGlobals;} public LocalLBDNSServerBindingStub getLocalLBDNSServer() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_LocalLBDNSServer ) { m_LocalLBDNSServer = (iControl.LocalLBDNSServerBindingStub) new iControl.LocalLBDNSServerLocator().getLocalLBDNSServerPort(new java.net.URL(buildURL())); } setupInterface(m_LocalLBDNSServer); return m_LocalLBDNSServer;} public LocalLBDNSTSIGKeyBindingStub getLocalLBDNSTSIGKey() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_LocalLBDNSTSIGKey ) { m_LocalLBDNSTSIGKey = (iControl.LocalLBDNSTSIGKeyBindingStub) new iControl.LocalLBDNSTSIGKeyLocator().getLocalLBDNSTSIGKeyPort(new java.net.URL(buildURL())); } setupInterface(m_LocalLBDNSTSIGKey); return m_LocalLBDNSTSIGKey;} public LocalLBDNSZoneBindingStub getLocalLBDNSZone() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_LocalLBDNSZone ) { m_LocalLBDNSZone = (iControl.LocalLBDNSZoneBindingStub) new iControl.LocalLBDNSZoneLocator().getLocalLBDNSZonePort(new java.net.URL(buildURL())); } setupInterface(m_LocalLBDNSZone); return m_LocalLBDNSZone;} public LocalLBFlowEvictionPolicyBindingStub getLocalLBFlowEvictionPolicy() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_LocalLBFlowEvictionPolicy ) { m_LocalLBFlowEvictionPolicy = (iControl.LocalLBFlowEvictionPolicyBindingStub) new iControl.LocalLBFlowEvictionPolicyLocator().getLocalLBFlowEvictionPolicyPort(new java.net.URL(buildURL())); } setupInterface(m_LocalLBFlowEvictionPolicy); return m_LocalLBFlowEvictionPolicy;} public LocalLBiFileBindingStub getLocalLBiFile() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_LocalLBiFile ) { m_LocalLBiFile = (iControl.LocalLBiFileBindingStub) new iControl.LocalLBiFileLocator().getLocalLBiFilePort(new java.net.URL(buildURL())); } setupInterface(m_LocalLBiFile); return m_LocalLBiFile;} public LocalLBiFileFileBindingStub getLocalLBiFileFile() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_LocalLBiFileFile ) { m_LocalLBiFileFile = (iControl.LocalLBiFileFileBindingStub) new iControl.LocalLBiFileFileLocator().getLocalLBiFileFilePort(new java.net.URL(buildURL())); } setupInterface(m_LocalLBiFileFile); return m_LocalLBiFileFile;} public LocalLBLSNLogProfileBindingStub getLocalLBLSNLogProfile() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_LocalLBLSNLogProfile ) { m_LocalLBLSNLogProfile = (iControl.LocalLBLSNLogProfileBindingStub) new iControl.LocalLBLSNLogProfileLocator().getLocalLBLSNLogProfilePort(new java.net.URL(buildURL())); } setupInterface(m_LocalLBLSNLogProfile); return m_LocalLBLSNLogProfile;} public LocalLBLSNPoolBindingStub getLocalLBLSNPool() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_LocalLBLSNPool ) { m_LocalLBLSNPool = (iControl.LocalLBLSNPoolBindingStub) new iControl.LocalLBLSNPoolLocator().getLocalLBLSNPoolPort(new java.net.URL(buildURL())); } setupInterface(m_LocalLBLSNPool); return m_LocalLBLSNPool;} public LocalLBMessageRoutingPeerBindingStub getLocalLBMessageRoutingPeer() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_LocalLBMessageRoutingPeer ) { m_LocalLBMessageRoutingPeer = (iControl.LocalLBMessageRoutingPeerBindingStub) new iControl.LocalLBMessageRoutingPeerLocator().getLocalLBMessageRoutingPeerPort(new java.net.URL(buildURL())); } setupInterface(m_LocalLBMessageRoutingPeer); return m_LocalLBMessageRoutingPeer;} public LocalLBMessageRoutingSIPRouteBindingStub getLocalLBMessageRoutingSIPRoute() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_LocalLBMessageRoutingSIPRoute ) { m_LocalLBMessageRoutingSIPRoute = (iControl.LocalLBMessageRoutingSIPRouteBindingStub) new iControl.LocalLBMessageRoutingSIPRouteLocator().getLocalLBMessageRoutingSIPRoutePort(new java.net.URL(buildURL())); } setupInterface(m_LocalLBMessageRoutingSIPRoute); return m_LocalLBMessageRoutingSIPRoute;} public LocalLBMessageRoutingTransportConfigBindingStub getLocalLBMessageRoutingTransportConfig() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_LocalLBMessageRoutingTransportConfig ) { m_LocalLBMessageRoutingTransportConfig = (iControl.LocalLBMessageRoutingTransportConfigBindingStub) new iControl.LocalLBMessageRoutingTransportConfigLocator().getLocalLBMessageRoutingTransportConfigPort(new java.net.URL(buildURL())); } setupInterface(m_LocalLBMessageRoutingTransportConfig); return m_LocalLBMessageRoutingTransportConfig;} public LocalLBMonitorBindingStub getLocalLBMonitor() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_LocalLBMonitor ) { m_LocalLBMonitor = (iControl.LocalLBMonitorBindingStub) new iControl.LocalLBMonitorLocator().getLocalLBMonitorPort(new java.net.URL(buildURL())); } setupInterface(m_LocalLBMonitor); return m_LocalLBMonitor;} public LocalLBNATBindingStub getLocalLBNAT() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_LocalLBNAT ) { m_LocalLBNAT = (iControl.LocalLBNATBindingStub) new iControl.LocalLBNATLocator().getLocalLBNATPort(new java.net.URL(buildURL())); } setupInterface(m_LocalLBNAT); return m_LocalLBNAT;} public LocalLBNATV2BindingStub getLocalLBNATV2() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_LocalLBNATV2 ) { m_LocalLBNATV2 = (iControl.LocalLBNATV2BindingStub) new iControl.LocalLBNATV2Locator().getLocalLBNATV2Port(new java.net.URL(buildURL())); } setupInterface(m_LocalLBNATV2); return m_LocalLBNATV2;} public LocalLBNodeAddressBindingStub getLocalLBNodeAddress() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_LocalLBNodeAddress ) { m_LocalLBNodeAddress = (iControl.LocalLBNodeAddressBindingStub) new iControl.LocalLBNodeAddressLocator().getLocalLBNodeAddressPort(new java.net.URL(buildURL())); } setupInterface(m_LocalLBNodeAddress); return m_LocalLBNodeAddress;} public LocalLBNodeAddressV2BindingStub getLocalLBNodeAddressV2() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_LocalLBNodeAddressV2 ) { m_LocalLBNodeAddressV2 = (iControl.LocalLBNodeAddressV2BindingStub) new iControl.LocalLBNodeAddressV2Locator().getLocalLBNodeAddressV2Port(new java.net.URL(buildURL())); } setupInterface(m_LocalLBNodeAddressV2); return m_LocalLBNodeAddressV2;} public LocalLBOCSPStaplingParametersBindingStub getLocalLBOCSPStaplingParameters() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_LocalLBOCSPStaplingParameters ) { m_LocalLBOCSPStaplingParameters = (iControl.LocalLBOCSPStaplingParametersBindingStub) new iControl.LocalLBOCSPStaplingParametersLocator().getLocalLBOCSPStaplingParametersPort(new java.net.URL(buildURL())); } setupInterface(m_LocalLBOCSPStaplingParameters); return m_LocalLBOCSPStaplingParameters;} public LocalLBPoolBindingStub getLocalLBPool() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_LocalLBPool ) { m_LocalLBPool = (iControl.LocalLBPoolBindingStub) new iControl.LocalLBPoolLocator().getLocalLBPoolPort(new java.net.URL(buildURL())); } setupInterface(m_LocalLBPool); return m_LocalLBPool;} public LocalLBPoolMemberBindingStub getLocalLBPoolMember() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_LocalLBPoolMember ) { m_LocalLBPoolMember = (iControl.LocalLBPoolMemberBindingStub) new iControl.LocalLBPoolMemberLocator().getLocalLBPoolMemberPort(new java.net.URL(buildURL())); } setupInterface(m_LocalLBPoolMember); return m_LocalLBPoolMember;} public LocalLBProfileAnalyticsBindingStub getLocalLBProfileAnalytics() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_LocalLBProfileAnalytics ) { m_LocalLBProfileAnalytics = (iControl.LocalLBProfileAnalyticsBindingStub) new iControl.LocalLBProfileAnalyticsLocator().getLocalLBProfileAnalyticsPort(new java.net.URL(buildURL())); } setupInterface(m_LocalLBProfileAnalytics); return m_LocalLBProfileAnalytics;} public LocalLBProfileAuthBindingStub getLocalLBProfileAuth() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_LocalLBProfileAuth ) { m_LocalLBProfileAuth = (iControl.LocalLBProfileAuthBindingStub) new iControl.LocalLBProfileAuthLocator().getLocalLBProfileAuthPort(new java.net.URL(buildURL())); } setupInterface(m_LocalLBProfileAuth); return m_LocalLBProfileAuth;} public LocalLBProfileClassificationBindingStub getLocalLBProfileClassification() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_LocalLBProfileClassification ) { m_LocalLBProfileClassification = (iControl.LocalLBProfileClassificationBindingStub) new iControl.LocalLBProfileClassificationLocator().getLocalLBProfileClassificationPort(new java.net.URL(buildURL())); } setupInterface(m_LocalLBProfileClassification); return m_LocalLBProfileClassification;} public LocalLBProfileClientLDAPBindingStub getLocalLBProfileClientLDAP() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_LocalLBProfileClientLDAP ) { m_LocalLBProfileClientLDAP = (iControl.LocalLBProfileClientLDAPBindingStub) new iControl.LocalLBProfileClientLDAPLocator().getLocalLBProfileClientLDAPPort(new java.net.URL(buildURL())); } setupInterface(m_LocalLBProfileClientLDAP); return m_LocalLBProfileClientLDAP;} public LocalLBProfileClientSSLBindingStub getLocalLBProfileClientSSL() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_LocalLBProfileClientSSL ) { m_LocalLBProfileClientSSL = (iControl.LocalLBProfileClientSSLBindingStub) new iControl.LocalLBProfileClientSSLLocator().getLocalLBProfileClientSSLPort(new java.net.URL(buildURL())); } setupInterface(m_LocalLBProfileClientSSL); return m_LocalLBProfileClientSSL;} public LocalLBProfileDiameterBindingStub getLocalLBProfileDiameter() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_LocalLBProfileDiameter ) { m_LocalLBProfileDiameter = (iControl.LocalLBProfileDiameterBindingStub) new iControl.LocalLBProfileDiameterLocator().getLocalLBProfileDiameterPort(new java.net.URL(buildURL())); } setupInterface(m_LocalLBProfileDiameter); return m_LocalLBProfileDiameter;} public LocalLBProfileDiameterEndpointBindingStub getLocalLBProfileDiameterEndpoint() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_LocalLBProfileDiameterEndpoint ) { m_LocalLBProfileDiameterEndpoint = (iControl.LocalLBProfileDiameterEndpointBindingStub) new iControl.LocalLBProfileDiameterEndpointLocator().getLocalLBProfileDiameterEndpointPort(new java.net.URL(buildURL())); } setupInterface(m_LocalLBProfileDiameterEndpoint); return m_LocalLBProfileDiameterEndpoint;} public LocalLBProfileDiameterRouterBindingStub getLocalLBProfileDiameterRouter() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_LocalLBProfileDiameterRouter ) { m_LocalLBProfileDiameterRouter = (iControl.LocalLBProfileDiameterRouterBindingStub) new iControl.LocalLBProfileDiameterRouterLocator().getLocalLBProfileDiameterRouterPort(new java.net.URL(buildURL())); } setupInterface(m_LocalLBProfileDiameterRouter); return m_LocalLBProfileDiameterRouter;} public LocalLBProfileDiameterSessionBindingStub getLocalLBProfileDiameterSession() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_LocalLBProfileDiameterSession ) { m_LocalLBProfileDiameterSession = (iControl.LocalLBProfileDiameterSessionBindingStub) new iControl.LocalLBProfileDiameterSessionLocator().getLocalLBProfileDiameterSessionPort(new java.net.URL(buildURL())); } setupInterface(m_LocalLBProfileDiameterSession); return m_LocalLBProfileDiameterSession;} public LocalLBProfileDNSBindingStub getLocalLBProfileDNS() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_LocalLBProfileDNS ) { m_LocalLBProfileDNS = (iControl.LocalLBProfileDNSBindingStub) new iControl.LocalLBProfileDNSLocator().getLocalLBProfileDNSPort(new java.net.URL(buildURL())); } setupInterface(m_LocalLBProfileDNS); return m_LocalLBProfileDNS;} public LocalLBProfileDNSLoggingBindingStub getLocalLBProfileDNSLogging() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_LocalLBProfileDNSLogging ) { m_LocalLBProfileDNSLogging = (iControl.LocalLBProfileDNSLoggingBindingStub) new iControl.LocalLBProfileDNSLoggingLocator().getLocalLBProfileDNSLoggingPort(new java.net.URL(buildURL())); } setupInterface(m_LocalLBProfileDNSLogging); return m_LocalLBProfileDNSLogging;} public LocalLBProfileFastHttpBindingStub getLocalLBProfileFastHttp() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_LocalLBProfileFastHttp ) { m_LocalLBProfileFastHttp = (iControl.LocalLBProfileFastHttpBindingStub) new iControl.LocalLBProfileFastHttpLocator().getLocalLBProfileFastHttpPort(new java.net.URL(buildURL())); } setupInterface(m_LocalLBProfileFastHttp); return m_LocalLBProfileFastHttp;} public LocalLBProfileFastL4BindingStub getLocalLBProfileFastL4() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_LocalLBProfileFastL4 ) { m_LocalLBProfileFastL4 = (iControl.LocalLBProfileFastL4BindingStub) new iControl.LocalLBProfileFastL4Locator().getLocalLBProfileFastL4Port(new java.net.URL(buildURL())); } setupInterface(m_LocalLBProfileFastL4); return m_LocalLBProfileFastL4;} public LocalLBProfileFIXBindingStub getLocalLBProfileFIX() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_LocalLBProfileFIX ) { m_LocalLBProfileFIX = (iControl.LocalLBProfileFIXBindingStub) new iControl.LocalLBProfileFIXLocator().getLocalLBProfileFIXPort(new java.net.URL(buildURL())); } setupInterface(m_LocalLBProfileFIX); return m_LocalLBProfileFIX;} public LocalLBProfileFTPBindingStub getLocalLBProfileFTP() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_LocalLBProfileFTP ) { m_LocalLBProfileFTP = (iControl.LocalLBProfileFTPBindingStub) new iControl.LocalLBProfileFTPLocator().getLocalLBProfileFTPPort(new java.net.URL(buildURL())); } setupInterface(m_LocalLBProfileFTP); return m_LocalLBProfileFTP;} public LocalLBProfileHttpBindingStub getLocalLBProfileHttp() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_LocalLBProfileHttp ) { m_LocalLBProfileHttp = (iControl.LocalLBProfileHttpBindingStub) new iControl.LocalLBProfileHttpLocator().getLocalLBProfileHttpPort(new java.net.URL(buildURL())); } setupInterface(m_LocalLBProfileHttp); return m_LocalLBProfileHttp;} public LocalLBProfileHttpClassBindingStub getLocalLBProfileHttpClass() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_LocalLBProfileHttpClass ) { m_LocalLBProfileHttpClass = (iControl.LocalLBProfileHttpClassBindingStub) new iControl.LocalLBProfileHttpClassLocator().getLocalLBProfileHttpClassPort(new java.net.URL(buildURL())); } setupInterface(m_LocalLBProfileHttpClass); return m_LocalLBProfileHttpClass;} public LocalLBProfileHttpCompressionBindingStub getLocalLBProfileHttpCompression() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_LocalLBProfileHttpCompression ) { m_LocalLBProfileHttpCompression = (iControl.LocalLBProfileHttpCompressionBindingStub) new iControl.LocalLBProfileHttpCompressionLocator().getLocalLBProfileHttpCompressionPort(new java.net.URL(buildURL())); } setupInterface(m_LocalLBProfileHttpCompression); return m_LocalLBProfileHttpCompression;} public LocalLBProfileICAPBindingStub getLocalLBProfileICAP() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_LocalLBProfileICAP ) { m_LocalLBProfileICAP = (iControl.LocalLBProfileICAPBindingStub) new iControl.LocalLBProfileICAPLocator().getLocalLBProfileICAPPort(new java.net.URL(buildURL())); } setupInterface(m_LocalLBProfileICAP); return m_LocalLBProfileICAP;} public LocalLBProfileIIOPBindingStub getLocalLBProfileIIOP() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_LocalLBProfileIIOP ) { m_LocalLBProfileIIOP = (iControl.LocalLBProfileIIOPBindingStub) new iControl.LocalLBProfileIIOPLocator().getLocalLBProfileIIOPPort(new java.net.URL(buildURL())); } setupInterface(m_LocalLBProfileIIOP); return m_LocalLBProfileIIOP;} public LocalLBProfileIPsecALGBindingStub getLocalLBProfileIPsecALG() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_LocalLBProfileIPsecALG ) { m_LocalLBProfileIPsecALG = (iControl.LocalLBProfileIPsecALGBindingStub) new iControl.LocalLBProfileIPsecALGLocator().getLocalLBProfileIPsecALGPort(new java.net.URL(buildURL())); } setupInterface(m_LocalLBProfileIPsecALG); return m_LocalLBProfileIPsecALG;} public LocalLBProfileOneConnectBindingStub getLocalLBProfileOneConnect() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_LocalLBProfileOneConnect ) { m_LocalLBProfileOneConnect = (iControl.LocalLBProfileOneConnectBindingStub) new iControl.LocalLBProfileOneConnectLocator().getLocalLBProfileOneConnectPort(new java.net.URL(buildURL())); } setupInterface(m_LocalLBProfileOneConnect); return m_LocalLBProfileOneConnect;} public LocalLBProfilePCPBindingStub getLocalLBProfilePCP() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_LocalLBProfilePCP ) { m_LocalLBProfilePCP = (iControl.LocalLBProfilePCPBindingStub) new iControl.LocalLBProfilePCPLocator().getLocalLBProfilePCPPort(new java.net.URL(buildURL())); } setupInterface(m_LocalLBProfilePCP); return m_LocalLBProfilePCP;} public LocalLBProfilePersistenceBindingStub getLocalLBProfilePersistence() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_LocalLBProfilePersistence ) { m_LocalLBProfilePersistence = (iControl.LocalLBProfilePersistenceBindingStub) new iControl.LocalLBProfilePersistenceLocator().getLocalLBProfilePersistencePort(new java.net.URL(buildURL())); } setupInterface(m_LocalLBProfilePersistence); return m_LocalLBProfilePersistence;} public LocalLBProfilePPTPBindingStub getLocalLBProfilePPTP() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_LocalLBProfilePPTP ) { m_LocalLBProfilePPTP = (iControl.LocalLBProfilePPTPBindingStub) new iControl.LocalLBProfilePPTPLocator().getLocalLBProfilePPTPPort(new java.net.URL(buildURL())); } setupInterface(m_LocalLBProfilePPTP); return m_LocalLBProfilePPTP;} public LocalLBProfileRADIUSBindingStub getLocalLBProfileRADIUS() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_LocalLBProfileRADIUS ) { m_LocalLBProfileRADIUS = (iControl.LocalLBProfileRADIUSBindingStub) new iControl.LocalLBProfileRADIUSLocator().getLocalLBProfileRADIUSPort(new java.net.URL(buildURL())); } setupInterface(m_LocalLBProfileRADIUS); return m_LocalLBProfileRADIUS;} public LocalLBProfileRequestAdaptBindingStub getLocalLBProfileRequestAdapt() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_LocalLBProfileRequestAdapt ) { m_LocalLBProfileRequestAdapt = (iControl.LocalLBProfileRequestAdaptBindingStub) new iControl.LocalLBProfileRequestAdaptLocator().getLocalLBProfileRequestAdaptPort(new java.net.URL(buildURL())); } setupInterface(m_LocalLBProfileRequestAdapt); return m_LocalLBProfileRequestAdapt;} public LocalLBProfileRequestLoggingBindingStub getLocalLBProfileRequestLogging() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_LocalLBProfileRequestLogging ) { m_LocalLBProfileRequestLogging = (iControl.LocalLBProfileRequestLoggingBindingStub) new iControl.LocalLBProfileRequestLoggingLocator().getLocalLBProfileRequestLoggingPort(new java.net.URL(buildURL())); } setupInterface(m_LocalLBProfileRequestLogging); return m_LocalLBProfileRequestLogging;} public LocalLBProfileResponseAdaptBindingStub getLocalLBProfileResponseAdapt() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_LocalLBProfileResponseAdapt ) { m_LocalLBProfileResponseAdapt = (iControl.LocalLBProfileResponseAdaptBindingStub) new iControl.LocalLBProfileResponseAdaptLocator().getLocalLBProfileResponseAdaptPort(new java.net.URL(buildURL())); } setupInterface(m_LocalLBProfileResponseAdapt); return m_LocalLBProfileResponseAdapt;} public LocalLBProfileRTSPBindingStub getLocalLBProfileRTSP() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_LocalLBProfileRTSP ) { m_LocalLBProfileRTSP = (iControl.LocalLBProfileRTSPBindingStub) new iControl.LocalLBProfileRTSPLocator().getLocalLBProfileRTSPPort(new java.net.URL(buildURL())); } setupInterface(m_LocalLBProfileRTSP); return m_LocalLBProfileRTSP;} public LocalLBProfileSCTPBindingStub getLocalLBProfileSCTP() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_LocalLBProfileSCTP ) { m_LocalLBProfileSCTP = (iControl.LocalLBProfileSCTPBindingStub) new iControl.LocalLBProfileSCTPLocator().getLocalLBProfileSCTPPort(new java.net.URL(buildURL())); } setupInterface(m_LocalLBProfileSCTP); return m_LocalLBProfileSCTP;} public LocalLBProfileServerLDAPBindingStub getLocalLBProfileServerLDAP() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_LocalLBProfileServerLDAP ) { m_LocalLBProfileServerLDAP = (iControl.LocalLBProfileServerLDAPBindingStub) new iControl.LocalLBProfileServerLDAPLocator().getLocalLBProfileServerLDAPPort(new java.net.URL(buildURL())); } setupInterface(m_LocalLBProfileServerLDAP); return m_LocalLBProfileServerLDAP;} public LocalLBProfileServerSSLBindingStub getLocalLBProfileServerSSL() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_LocalLBProfileServerSSL ) { m_LocalLBProfileServerSSL = (iControl.LocalLBProfileServerSSLBindingStub) new iControl.LocalLBProfileServerSSLLocator().getLocalLBProfileServerSSLPort(new java.net.URL(buildURL())); } setupInterface(m_LocalLBProfileServerSSL); return m_LocalLBProfileServerSSL;} public LocalLBProfileSIPBindingStub getLocalLBProfileSIP() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_LocalLBProfileSIP ) { m_LocalLBProfileSIP = (iControl.LocalLBProfileSIPBindingStub) new iControl.LocalLBProfileSIPLocator().getLocalLBProfileSIPPort(new java.net.URL(buildURL())); } setupInterface(m_LocalLBProfileSIP); return m_LocalLBProfileSIP;} public LocalLBProfileSIPRouterBindingStub getLocalLBProfileSIPRouter() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_LocalLBProfileSIPRouter ) { m_LocalLBProfileSIPRouter = (iControl.LocalLBProfileSIPRouterBindingStub) new iControl.LocalLBProfileSIPRouterLocator().getLocalLBProfileSIPRouterPort(new java.net.URL(buildURL())); } setupInterface(m_LocalLBProfileSIPRouter); return m_LocalLBProfileSIPRouter;} public LocalLBProfileSIPSessionBindingStub getLocalLBProfileSIPSession() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_LocalLBProfileSIPSession ) { m_LocalLBProfileSIPSession = (iControl.LocalLBProfileSIPSessionBindingStub) new iControl.LocalLBProfileSIPSessionLocator().getLocalLBProfileSIPSessionPort(new java.net.URL(buildURL())); } setupInterface(m_LocalLBProfileSIPSession); return m_LocalLBProfileSIPSession;} public LocalLBProfileSMTPSBindingStub getLocalLBProfileSMTPS() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_LocalLBProfileSMTPS ) { m_LocalLBProfileSMTPS = (iControl.LocalLBProfileSMTPSBindingStub) new iControl.LocalLBProfileSMTPSLocator().getLocalLBProfileSMTPSPort(new java.net.URL(buildURL())); } setupInterface(m_LocalLBProfileSMTPS); return m_LocalLBProfileSMTPS;} public LocalLBProfileSPDYBindingStub getLocalLBProfileSPDY() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_LocalLBProfileSPDY ) { m_LocalLBProfileSPDY = (iControl.LocalLBProfileSPDYBindingStub) new iControl.LocalLBProfileSPDYLocator().getLocalLBProfileSPDYPort(new java.net.URL(buildURL())); } setupInterface(m_LocalLBProfileSPDY); return m_LocalLBProfileSPDY;} public LocalLBProfileSPMBindingStub getLocalLBProfileSPM() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_LocalLBProfileSPM ) { m_LocalLBProfileSPM = (iControl.LocalLBProfileSPMBindingStub) new iControl.LocalLBProfileSPMLocator().getLocalLBProfileSPMPort(new java.net.URL(buildURL())); } setupInterface(m_LocalLBProfileSPM); return m_LocalLBProfileSPM;} public LocalLBProfileStreamBindingStub getLocalLBProfileStream() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_LocalLBProfileStream ) { m_LocalLBProfileStream = (iControl.LocalLBProfileStreamBindingStub) new iControl.LocalLBProfileStreamLocator().getLocalLBProfileStreamPort(new java.net.URL(buildURL())); } setupInterface(m_LocalLBProfileStream); return m_LocalLBProfileStream;} public LocalLBProfileTCPBindingStub getLocalLBProfileTCP() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_LocalLBProfileTCP ) { m_LocalLBProfileTCP = (iControl.LocalLBProfileTCPBindingStub) new iControl.LocalLBProfileTCPLocator().getLocalLBProfileTCPPort(new java.net.URL(buildURL())); } setupInterface(m_LocalLBProfileTCP); return m_LocalLBProfileTCP;} public LocalLBProfileTCPAnalyticsBindingStub getLocalLBProfileTCPAnalytics() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_LocalLBProfileTCPAnalytics ) { m_LocalLBProfileTCPAnalytics = (iControl.LocalLBProfileTCPAnalyticsBindingStub) new iControl.LocalLBProfileTCPAnalyticsLocator().getLocalLBProfileTCPAnalyticsPort(new java.net.URL(buildURL())); } setupInterface(m_LocalLBProfileTCPAnalytics); return m_LocalLBProfileTCPAnalytics;} public LocalLBProfileTFTPBindingStub getLocalLBProfileTFTP() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_LocalLBProfileTFTP ) { m_LocalLBProfileTFTP = (iControl.LocalLBProfileTFTPBindingStub) new iControl.LocalLBProfileTFTPLocator().getLocalLBProfileTFTPPort(new java.net.URL(buildURL())); } setupInterface(m_LocalLBProfileTFTP); return m_LocalLBProfileTFTP;} public LocalLBProfileTrafficAccelerationBindingStub getLocalLBProfileTrafficAcceleration() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_LocalLBProfileTrafficAcceleration ) { m_LocalLBProfileTrafficAcceleration = (iControl.LocalLBProfileTrafficAccelerationBindingStub) new iControl.LocalLBProfileTrafficAccelerationLocator().getLocalLBProfileTrafficAccelerationPort(new java.net.URL(buildURL())); } setupInterface(m_LocalLBProfileTrafficAcceleration); return m_LocalLBProfileTrafficAcceleration;} public LocalLBProfileUDPBindingStub getLocalLBProfileUDP() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_LocalLBProfileUDP ) { m_LocalLBProfileUDP = (iControl.LocalLBProfileUDPBindingStub) new iControl.LocalLBProfileUDPLocator().getLocalLBProfileUDPPort(new java.net.URL(buildURL())); } setupInterface(m_LocalLBProfileUDP); return m_LocalLBProfileUDP;} public LocalLBProfileUserStatisticBindingStub getLocalLBProfileUserStatistic() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_LocalLBProfileUserStatistic ) { m_LocalLBProfileUserStatistic = (iControl.LocalLBProfileUserStatisticBindingStub) new iControl.LocalLBProfileUserStatisticLocator().getLocalLBProfileUserStatisticPort(new java.net.URL(buildURL())); } setupInterface(m_LocalLBProfileUserStatistic); return m_LocalLBProfileUserStatistic;} public LocalLBProfileWebAccelerationBindingStub getLocalLBProfileWebAcceleration() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_LocalLBProfileWebAcceleration ) { m_LocalLBProfileWebAcceleration = (iControl.LocalLBProfileWebAccelerationBindingStub) new iControl.LocalLBProfileWebAccelerationLocator().getLocalLBProfileWebAccelerationPort(new java.net.URL(buildURL())); } setupInterface(m_LocalLBProfileWebAcceleration); return m_LocalLBProfileWebAcceleration;} public LocalLBProfileXMLBindingStub getLocalLBProfileXML() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_LocalLBProfileXML ) { m_LocalLBProfileXML = (iControl.LocalLBProfileXMLBindingStub) new iControl.LocalLBProfileXMLLocator().getLocalLBProfileXMLPort(new java.net.URL(buildURL())); } setupInterface(m_LocalLBProfileXML); return m_LocalLBProfileXML;} public LocalLBRAMCacheInformationBindingStub getLocalLBRAMCacheInformation() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_LocalLBRAMCacheInformation ) { m_LocalLBRAMCacheInformation = (iControl.LocalLBRAMCacheInformationBindingStub) new iControl.LocalLBRAMCacheInformationLocator().getLocalLBRAMCacheInformationPort(new java.net.URL(buildURL())); } setupInterface(m_LocalLBRAMCacheInformation); return m_LocalLBRAMCacheInformation;} public LocalLBRateClassBindingStub getLocalLBRateClass() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_LocalLBRateClass ) { m_LocalLBRateClass = (iControl.LocalLBRateClassBindingStub) new iControl.LocalLBRateClassLocator().getLocalLBRateClassPort(new java.net.URL(buildURL())); } setupInterface(m_LocalLBRateClass); return m_LocalLBRateClass;} public LocalLBRuleBindingStub getLocalLBRule() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_LocalLBRule ) { m_LocalLBRule = (iControl.LocalLBRuleBindingStub) new iControl.LocalLBRuleLocator().getLocalLBRulePort(new java.net.URL(buildURL())); } setupInterface(m_LocalLBRule); return m_LocalLBRule;} public LocalLBSNATBindingStub getLocalLBSNAT() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_LocalLBSNAT ) { m_LocalLBSNAT = (iControl.LocalLBSNATBindingStub) new iControl.LocalLBSNATLocator().getLocalLBSNATPort(new java.net.URL(buildURL())); } setupInterface(m_LocalLBSNAT); return m_LocalLBSNAT;} public LocalLBSNATPoolBindingStub getLocalLBSNATPool() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_LocalLBSNATPool ) { m_LocalLBSNATPool = (iControl.LocalLBSNATPoolBindingStub) new iControl.LocalLBSNATPoolLocator().getLocalLBSNATPoolPort(new java.net.URL(buildURL())); } setupInterface(m_LocalLBSNATPool); return m_LocalLBSNATPool;} public LocalLBSNATPoolMemberBindingStub getLocalLBSNATPoolMember() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_LocalLBSNATPoolMember ) { m_LocalLBSNATPoolMember = (iControl.LocalLBSNATPoolMemberBindingStub) new iControl.LocalLBSNATPoolMemberLocator().getLocalLBSNATPoolMemberPort(new java.net.URL(buildURL())); } setupInterface(m_LocalLBSNATPoolMember); return m_LocalLBSNATPoolMember;} public LocalLBSNATTranslationAddressBindingStub getLocalLBSNATTranslationAddress() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_LocalLBSNATTranslationAddress ) { m_LocalLBSNATTranslationAddress = (iControl.LocalLBSNATTranslationAddressBindingStub) new iControl.LocalLBSNATTranslationAddressLocator().getLocalLBSNATTranslationAddressPort(new java.net.URL(buildURL())); } setupInterface(m_LocalLBSNATTranslationAddress); return m_LocalLBSNATTranslationAddress;} public LocalLBSNATTranslationAddressV2BindingStub getLocalLBSNATTranslationAddressV2() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_LocalLBSNATTranslationAddressV2 ) { m_LocalLBSNATTranslationAddressV2 = (iControl.LocalLBSNATTranslationAddressV2BindingStub) new iControl.LocalLBSNATTranslationAddressV2Locator().getLocalLBSNATTranslationAddressV2Port(new java.net.URL(buildURL())); } setupInterface(m_LocalLBSNATTranslationAddressV2); return m_LocalLBSNATTranslationAddressV2;} public LocalLBVirtualAddressBindingStub getLocalLBVirtualAddress() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_LocalLBVirtualAddress ) { m_LocalLBVirtualAddress = (iControl.LocalLBVirtualAddressBindingStub) new iControl.LocalLBVirtualAddressLocator().getLocalLBVirtualAddressPort(new java.net.URL(buildURL())); } setupInterface(m_LocalLBVirtualAddress); return m_LocalLBVirtualAddress;} public LocalLBVirtualAddressV2BindingStub getLocalLBVirtualAddressV2() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_LocalLBVirtualAddressV2 ) { m_LocalLBVirtualAddressV2 = (iControl.LocalLBVirtualAddressV2BindingStub) new iControl.LocalLBVirtualAddressV2Locator().getLocalLBVirtualAddressV2Port(new java.net.URL(buildURL())); } setupInterface(m_LocalLBVirtualAddressV2); return m_LocalLBVirtualAddressV2;} public LocalLBVirtualServerBindingStub getLocalLBVirtualServer() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_LocalLBVirtualServer ) { m_LocalLBVirtualServer = (iControl.LocalLBVirtualServerBindingStub) new iControl.LocalLBVirtualServerLocator().getLocalLBVirtualServerPort(new java.net.URL(buildURL())); } setupInterface(m_LocalLBVirtualServer); return m_LocalLBVirtualServer;} public LogDestinationArcSightBindingStub getLogDestinationArcSight() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_LogDestinationArcSight ) { m_LogDestinationArcSight = (iControl.LogDestinationArcSightBindingStub) new iControl.LogDestinationArcSightLocator().getLogDestinationArcSightPort(new java.net.URL(buildURL())); } setupInterface(m_LogDestinationArcSight); return m_LogDestinationArcSight;} public LogDestinationIPFIXBindingStub getLogDestinationIPFIX() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_LogDestinationIPFIX ) { m_LogDestinationIPFIX = (iControl.LogDestinationIPFIXBindingStub) new iControl.LogDestinationIPFIXLocator().getLogDestinationIPFIXPort(new java.net.URL(buildURL())); } setupInterface(m_LogDestinationIPFIX); return m_LogDestinationIPFIX;} public LogDestinationLocalSyslogBindingStub getLogDestinationLocalSyslog() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_LogDestinationLocalSyslog ) { m_LogDestinationLocalSyslog = (iControl.LogDestinationLocalSyslogBindingStub) new iControl.LogDestinationLocalSyslogLocator().getLogDestinationLocalSyslogPort(new java.net.URL(buildURL())); } setupInterface(m_LogDestinationLocalSyslog); return m_LogDestinationLocalSyslog;} public LogDestinationManagementPortBindingStub getLogDestinationManagementPort() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_LogDestinationManagementPort ) { m_LogDestinationManagementPort = (iControl.LogDestinationManagementPortBindingStub) new iControl.LogDestinationManagementPortLocator().getLogDestinationManagementPortPort(new java.net.URL(buildURL())); } setupInterface(m_LogDestinationManagementPort); return m_LogDestinationManagementPort;} public LogDestinationRemoteHighSpeedLogBindingStub getLogDestinationRemoteHighSpeedLog() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_LogDestinationRemoteHighSpeedLog ) { m_LogDestinationRemoteHighSpeedLog = (iControl.LogDestinationRemoteHighSpeedLogBindingStub) new iControl.LogDestinationRemoteHighSpeedLogLocator().getLogDestinationRemoteHighSpeedLogPort(new java.net.URL(buildURL())); } setupInterface(m_LogDestinationRemoteHighSpeedLog); return m_LogDestinationRemoteHighSpeedLog;} public LogDestinationRemoteSyslogBindingStub getLogDestinationRemoteSyslog() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_LogDestinationRemoteSyslog ) { m_LogDestinationRemoteSyslog = (iControl.LogDestinationRemoteSyslogBindingStub) new iControl.LogDestinationRemoteSyslogLocator().getLogDestinationRemoteSyslogPort(new java.net.URL(buildURL())); } setupInterface(m_LogDestinationRemoteSyslog); return m_LogDestinationRemoteSyslog;} public LogDestinationSplunkBindingStub getLogDestinationSplunk() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_LogDestinationSplunk ) { m_LogDestinationSplunk = (iControl.LogDestinationSplunkBindingStub) new iControl.LogDestinationSplunkLocator().getLogDestinationSplunkPort(new java.net.URL(buildURL())); } setupInterface(m_LogDestinationSplunk); return m_LogDestinationSplunk;} public LogFilterBindingStub getLogFilter() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_LogFilter ) { m_LogFilter = (iControl.LogFilterBindingStub) new iControl.LogFilterLocator().getLogFilterPort(new java.net.URL(buildURL())); } setupInterface(m_LogFilter); return m_LogFilter;} public LogIPFIXInformationElementBindingStub getLogIPFIXInformationElement() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_LogIPFIXInformationElement ) { m_LogIPFIXInformationElement = (iControl.LogIPFIXInformationElementBindingStub) new iControl.LogIPFIXInformationElementLocator().getLogIPFIXInformationElementPort(new java.net.URL(buildURL())); } setupInterface(m_LogIPFIXInformationElement); return m_LogIPFIXInformationElement;} public LogPublisherBindingStub getLogPublisher() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_LogPublisher ) { m_LogPublisher = (iControl.LogPublisherBindingStub) new iControl.LogPublisherLocator().getLogPublisherPort(new java.net.URL(buildURL())); } setupInterface(m_LogPublisher); return m_LogPublisher;} public LTConfigClassBindingStub getLTConfigClass() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_LTConfigClass ) { m_LTConfigClass = (iControl.LTConfigClassBindingStub) new iControl.LTConfigClassLocator().getLTConfigClassPort(new java.net.URL(buildURL())); } setupInterface(m_LTConfigClass); return m_LTConfigClass;} public LTConfigFieldBindingStub getLTConfigField() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_LTConfigField ) { m_LTConfigField = (iControl.LTConfigFieldBindingStub) new iControl.LTConfigFieldLocator().getLTConfigFieldPort(new java.net.URL(buildURL())); } setupInterface(m_LTConfigField); return m_LTConfigField;} public ManagementApplicationPresentationScriptBindingStub getManagementApplicationPresentationScript() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_ManagementApplicationPresentationScript ) { m_ManagementApplicationPresentationScript = (iControl.ManagementApplicationPresentationScriptBindingStub) new iControl.ManagementApplicationPresentationScriptLocator().getManagementApplicationPresentationScriptPort(new java.net.URL(buildURL())); } setupInterface(m_ManagementApplicationPresentationScript); return m_ManagementApplicationPresentationScript;} public ManagementApplicationServiceBindingStub getManagementApplicationService() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_ManagementApplicationService ) { m_ManagementApplicationService = (iControl.ManagementApplicationServiceBindingStub) new iControl.ManagementApplicationServiceLocator().getManagementApplicationServicePort(new java.net.URL(buildURL())); } setupInterface(m_ManagementApplicationService); return m_ManagementApplicationService;} public ManagementApplicationTemplateBindingStub getManagementApplicationTemplate() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_ManagementApplicationTemplate ) { m_ManagementApplicationTemplate = (iControl.ManagementApplicationTemplateBindingStub) new iControl.ManagementApplicationTemplateLocator().getManagementApplicationTemplatePort(new java.net.URL(buildURL())); } setupInterface(m_ManagementApplicationTemplate); return m_ManagementApplicationTemplate;} public ManagementCCLDAPConfigurationBindingStub getManagementCCLDAPConfiguration() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_ManagementCCLDAPConfiguration ) { m_ManagementCCLDAPConfiguration = (iControl.ManagementCCLDAPConfigurationBindingStub) new iControl.ManagementCCLDAPConfigurationLocator().getManagementCCLDAPConfigurationPort(new java.net.URL(buildURL())); } setupInterface(m_ManagementCCLDAPConfiguration); return m_ManagementCCLDAPConfiguration;} public ManagementCertificateValidatorOCSPBindingStub getManagementCertificateValidatorOCSP() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_ManagementCertificateValidatorOCSP ) { m_ManagementCertificateValidatorOCSP = (iControl.ManagementCertificateValidatorOCSPBindingStub) new iControl.ManagementCertificateValidatorOCSPLocator().getManagementCertificateValidatorOCSPPort(new java.net.URL(buildURL())); } setupInterface(m_ManagementCertificateValidatorOCSP); return m_ManagementCertificateValidatorOCSP;} public ManagementCertLDAPConfigurationBindingStub getManagementCertLDAPConfiguration() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_ManagementCertLDAPConfiguration ) { m_ManagementCertLDAPConfiguration = (iControl.ManagementCertLDAPConfigurationBindingStub) new iControl.ManagementCertLDAPConfigurationLocator().getManagementCertLDAPConfigurationPort(new java.net.URL(buildURL())); } setupInterface(m_ManagementCertLDAPConfiguration); return m_ManagementCertLDAPConfiguration;} public ManagementCLIScriptBindingStub getManagementCLIScript() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_ManagementCLIScript ) { m_ManagementCLIScript = (iControl.ManagementCLIScriptBindingStub) new iControl.ManagementCLIScriptLocator().getManagementCLIScriptPort(new java.net.URL(buildURL())); } setupInterface(m_ManagementCLIScript); return m_ManagementCLIScript;} public ManagementCRLDPConfigurationBindingStub getManagementCRLDPConfiguration() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_ManagementCRLDPConfiguration ) { m_ManagementCRLDPConfiguration = (iControl.ManagementCRLDPConfigurationBindingStub) new iControl.ManagementCRLDPConfigurationLocator().getManagementCRLDPConfigurationPort(new java.net.URL(buildURL())); } setupInterface(m_ManagementCRLDPConfiguration); return m_ManagementCRLDPConfiguration;} public ManagementCRLDPServerBindingStub getManagementCRLDPServer() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_ManagementCRLDPServer ) { m_ManagementCRLDPServer = (iControl.ManagementCRLDPServerBindingStub) new iControl.ManagementCRLDPServerLocator().getManagementCRLDPServerPort(new java.net.URL(buildURL())); } setupInterface(m_ManagementCRLDPServer); return m_ManagementCRLDPServer;} public ManagementDBVariableBindingStub getManagementDBVariable() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_ManagementDBVariable ) { m_ManagementDBVariable = (iControl.ManagementDBVariableBindingStub) new iControl.ManagementDBVariableLocator().getManagementDBVariablePort(new java.net.URL(buildURL())); } setupInterface(m_ManagementDBVariable); return m_ManagementDBVariable;} public ManagementDeviceBindingStub getManagementDevice() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_ManagementDevice ) { m_ManagementDevice = (iControl.ManagementDeviceBindingStub) new iControl.ManagementDeviceLocator().getManagementDevicePort(new java.net.URL(buildURL())); } setupInterface(m_ManagementDevice); return m_ManagementDevice;} public ManagementDeviceGroupBindingStub getManagementDeviceGroup() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_ManagementDeviceGroup ) { m_ManagementDeviceGroup = (iControl.ManagementDeviceGroupBindingStub) new iControl.ManagementDeviceGroupLocator().getManagementDeviceGroupPort(new java.net.URL(buildURL())); } setupInterface(m_ManagementDeviceGroup); return m_ManagementDeviceGroup;} public ManagementEMBindingStub getManagementEM() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_ManagementEM ) { m_ManagementEM = (iControl.ManagementEMBindingStub) new iControl.ManagementEMLocator().getManagementEMPort(new java.net.URL(buildURL())); } setupInterface(m_ManagementEM); return m_ManagementEM;} public ManagementEventNotificationBindingStub getManagementEventNotification() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_ManagementEventNotification ) { m_ManagementEventNotification = (iControl.ManagementEventNotificationBindingStub) new iControl.ManagementEventNotificationLocator().getManagementEventNotificationPort(new java.net.URL(buildURL())); } setupInterface(m_ManagementEventNotification); return m_ManagementEventNotification;} public ManagementEventSubscriptionBindingStub getManagementEventSubscription() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_ManagementEventSubscription ) { m_ManagementEventSubscription = (iControl.ManagementEventSubscriptionBindingStub) new iControl.ManagementEventSubscriptionLocator().getManagementEventSubscriptionPort(new java.net.URL(buildURL())); } setupInterface(m_ManagementEventSubscription); return m_ManagementEventSubscription;} public ManagementFeatureModuleBindingStub getManagementFeatureModule() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_ManagementFeatureModule ) { m_ManagementFeatureModule = (iControl.ManagementFeatureModuleBindingStub) new iControl.ManagementFeatureModuleLocator().getManagementFeatureModulePort(new java.net.URL(buildURL())); } setupInterface(m_ManagementFeatureModule); return m_ManagementFeatureModule;} public ManagementFolderBindingStub getManagementFolder() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_ManagementFolder ) { m_ManagementFolder = (iControl.ManagementFolderBindingStub) new iControl.ManagementFolderLocator().getManagementFolderPort(new java.net.URL(buildURL())); } setupInterface(m_ManagementFolder); return m_ManagementFolder;} public ManagementGlobalsBindingStub getManagementGlobals() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_ManagementGlobals ) { m_ManagementGlobals = (iControl.ManagementGlobalsBindingStub) new iControl.ManagementGlobalsLocator().getManagementGlobalsPort(new java.net.URL(buildURL())); } setupInterface(m_ManagementGlobals); return m_ManagementGlobals;} public ManagementKeyCertificateBindingStub getManagementKeyCertificate() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_ManagementKeyCertificate ) { m_ManagementKeyCertificate = (iControl.ManagementKeyCertificateBindingStub) new iControl.ManagementKeyCertificateLocator().getManagementKeyCertificatePort(new java.net.URL(buildURL())); } setupInterface(m_ManagementKeyCertificate); return m_ManagementKeyCertificate;} public ManagementLDAPConfigurationBindingStub getManagementLDAPConfiguration() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_ManagementLDAPConfiguration ) { m_ManagementLDAPConfiguration = (iControl.ManagementLDAPConfigurationBindingStub) new iControl.ManagementLDAPConfigurationLocator().getManagementLDAPConfigurationPort(new java.net.URL(buildURL())); } setupInterface(m_ManagementLDAPConfiguration); return m_ManagementLDAPConfiguration;} public ManagementLicenseAdministrationBindingStub getManagementLicenseAdministration() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_ManagementLicenseAdministration ) { m_ManagementLicenseAdministration = (iControl.ManagementLicenseAdministrationBindingStub) new iControl.ManagementLicenseAdministrationLocator().getManagementLicenseAdministrationPort(new java.net.URL(buildURL())); } setupInterface(m_ManagementLicenseAdministration); return m_ManagementLicenseAdministration;} public ManagementNamedBindingStub getManagementNamed() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_ManagementNamed ) { m_ManagementNamed = (iControl.ManagementNamedBindingStub) new iControl.ManagementNamedLocator().getManagementNamedPort(new java.net.URL(buildURL())); } setupInterface(m_ManagementNamed); return m_ManagementNamed;} public ManagementOCSPConfigurationBindingStub getManagementOCSPConfiguration() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_ManagementOCSPConfiguration ) { m_ManagementOCSPConfiguration = (iControl.ManagementOCSPConfigurationBindingStub) new iControl.ManagementOCSPConfigurationLocator().getManagementOCSPConfigurationPort(new java.net.URL(buildURL())); } setupInterface(m_ManagementOCSPConfiguration); return m_ManagementOCSPConfiguration;} public ManagementOCSPResponderBindingStub getManagementOCSPResponder() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_ManagementOCSPResponder ) { m_ManagementOCSPResponder = (iControl.ManagementOCSPResponderBindingStub) new iControl.ManagementOCSPResponderLocator().getManagementOCSPResponderPort(new java.net.URL(buildURL())); } setupInterface(m_ManagementOCSPResponder); return m_ManagementOCSPResponder;} public ManagementPartitionBindingStub getManagementPartition() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_ManagementPartition ) { m_ManagementPartition = (iControl.ManagementPartitionBindingStub) new iControl.ManagementPartitionLocator().getManagementPartitionPort(new java.net.URL(buildURL())); } setupInterface(m_ManagementPartition); return m_ManagementPartition;} public ManagementProvisionBindingStub getManagementProvision() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_ManagementProvision ) { m_ManagementProvision = (iControl.ManagementProvisionBindingStub) new iControl.ManagementProvisionLocator().getManagementProvisionPort(new java.net.URL(buildURL())); } setupInterface(m_ManagementProvision); return m_ManagementProvision;} public ManagementRADIUSConfigurationBindingStub getManagementRADIUSConfiguration() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_ManagementRADIUSConfiguration ) { m_ManagementRADIUSConfiguration = (iControl.ManagementRADIUSConfigurationBindingStub) new iControl.ManagementRADIUSConfigurationLocator().getManagementRADIUSConfigurationPort(new java.net.URL(buildURL())); } setupInterface(m_ManagementRADIUSConfiguration); return m_ManagementRADIUSConfiguration;} public ManagementRADIUSServerBindingStub getManagementRADIUSServer() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_ManagementRADIUSServer ) { m_ManagementRADIUSServer = (iControl.ManagementRADIUSServerBindingStub) new iControl.ManagementRADIUSServerLocator().getManagementRADIUSServerPort(new java.net.URL(buildURL())); } setupInterface(m_ManagementRADIUSServer); return m_ManagementRADIUSServer;} public ManagementResourceRecordBindingStub getManagementResourceRecord() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_ManagementResourceRecord ) { m_ManagementResourceRecord = (iControl.ManagementResourceRecordBindingStub) new iControl.ManagementResourceRecordLocator().getManagementResourceRecordPort(new java.net.URL(buildURL())); } setupInterface(m_ManagementResourceRecord); return m_ManagementResourceRecord;} public ManagementSFlowDataSourceBindingStub getManagementSFlowDataSource() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_ManagementSFlowDataSource ) { m_ManagementSFlowDataSource = (iControl.ManagementSFlowDataSourceBindingStub) new iControl.ManagementSFlowDataSourceLocator().getManagementSFlowDataSourcePort(new java.net.URL(buildURL())); } setupInterface(m_ManagementSFlowDataSource); return m_ManagementSFlowDataSource;} public ManagementSFlowGlobalsBindingStub getManagementSFlowGlobals() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_ManagementSFlowGlobals ) { m_ManagementSFlowGlobals = (iControl.ManagementSFlowGlobalsBindingStub) new iControl.ManagementSFlowGlobalsLocator().getManagementSFlowGlobalsPort(new java.net.URL(buildURL())); } setupInterface(m_ManagementSFlowGlobals); return m_ManagementSFlowGlobals;} public ManagementSFlowReceiverBindingStub getManagementSFlowReceiver() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_ManagementSFlowReceiver ) { m_ManagementSFlowReceiver = (iControl.ManagementSFlowReceiverBindingStub) new iControl.ManagementSFlowReceiverLocator().getManagementSFlowReceiverPort(new java.net.URL(buildURL())); } setupInterface(m_ManagementSFlowReceiver); return m_ManagementSFlowReceiver;} public ManagementSMTPConfigurationBindingStub getManagementSMTPConfiguration() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_ManagementSMTPConfiguration ) { m_ManagementSMTPConfiguration = (iControl.ManagementSMTPConfigurationBindingStub) new iControl.ManagementSMTPConfigurationLocator().getManagementSMTPConfigurationPort(new java.net.URL(buildURL())); } setupInterface(m_ManagementSMTPConfiguration); return m_ManagementSMTPConfiguration;} public ManagementSNMPConfigurationBindingStub getManagementSNMPConfiguration() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_ManagementSNMPConfiguration ) { m_ManagementSNMPConfiguration = (iControl.ManagementSNMPConfigurationBindingStub) new iControl.ManagementSNMPConfigurationLocator().getManagementSNMPConfigurationPort(new java.net.URL(buildURL())); } setupInterface(m_ManagementSNMPConfiguration); return m_ManagementSNMPConfiguration;} public ManagementTACACSConfigurationBindingStub getManagementTACACSConfiguration() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_ManagementTACACSConfiguration ) { m_ManagementTACACSConfiguration = (iControl.ManagementTACACSConfigurationBindingStub) new iControl.ManagementTACACSConfigurationLocator().getManagementTACACSConfigurationPort(new java.net.URL(buildURL())); } setupInterface(m_ManagementTACACSConfiguration); return m_ManagementTACACSConfiguration;} public ManagementTMOSModuleBindingStub getManagementTMOSModule() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_ManagementTMOSModule ) { m_ManagementTMOSModule = (iControl.ManagementTMOSModuleBindingStub) new iControl.ManagementTMOSModuleLocator().getManagementTMOSModulePort(new java.net.URL(buildURL())); } setupInterface(m_ManagementTMOSModule); return m_ManagementTMOSModule;} public ManagementTrafficGroupBindingStub getManagementTrafficGroup() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_ManagementTrafficGroup ) { m_ManagementTrafficGroup = (iControl.ManagementTrafficGroupBindingStub) new iControl.ManagementTrafficGroupLocator().getManagementTrafficGroupPort(new java.net.URL(buildURL())); } setupInterface(m_ManagementTrafficGroup); return m_ManagementTrafficGroup;} public ManagementTrustBindingStub getManagementTrust() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_ManagementTrust ) { m_ManagementTrust = (iControl.ManagementTrustBindingStub) new iControl.ManagementTrustLocator().getManagementTrustPort(new java.net.URL(buildURL())); } setupInterface(m_ManagementTrust); return m_ManagementTrust;} public ManagementUserManagementBindingStub getManagementUserManagement() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_ManagementUserManagement ) { m_ManagementUserManagement = (iControl.ManagementUserManagementBindingStub) new iControl.ManagementUserManagementLocator().getManagementUserManagementPort(new java.net.URL(buildURL())); } setupInterface(m_ManagementUserManagement); return m_ManagementUserManagement;} public ManagementViewBindingStub getManagementView() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_ManagementView ) { m_ManagementView = (iControl.ManagementViewBindingStub) new iControl.ManagementViewLocator().getManagementViewPort(new java.net.URL(buildURL())); } setupInterface(m_ManagementView); return m_ManagementView;} public ManagementZoneBindingStub getManagementZone() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_ManagementZone ) { m_ManagementZone = (iControl.ManagementZoneBindingStub) new iControl.ManagementZoneLocator().getManagementZonePort(new java.net.URL(buildURL())); } setupInterface(m_ManagementZone); return m_ManagementZone;} public ManagementZoneRunnerBindingStub getManagementZoneRunner() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_ManagementZoneRunner ) { m_ManagementZoneRunner = (iControl.ManagementZoneRunnerBindingStub) new iControl.ManagementZoneRunnerLocator().getManagementZoneRunnerPort(new java.net.URL(buildURL())); } setupInterface(m_ManagementZoneRunner); return m_ManagementZoneRunner;} public NetworkingAdminIPBindingStub getNetworkingAdminIP() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_NetworkingAdminIP ) { m_NetworkingAdminIP = (iControl.NetworkingAdminIPBindingStub) new iControl.NetworkingAdminIPLocator().getNetworkingAdminIPPort(new java.net.URL(buildURL())); } setupInterface(m_NetworkingAdminIP); return m_NetworkingAdminIP;} public NetworkingARPBindingStub getNetworkingARP() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_NetworkingARP ) { m_NetworkingARP = (iControl.NetworkingARPBindingStub) new iControl.NetworkingARPLocator().getNetworkingARPPort(new java.net.URL(buildURL())); } setupInterface(m_NetworkingARP); return m_NetworkingARP;} public NetworkingBWControllerPolicyBindingStub getNetworkingBWControllerPolicy() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_NetworkingBWControllerPolicy ) { m_NetworkingBWControllerPolicy = (iControl.NetworkingBWControllerPolicyBindingStub) new iControl.NetworkingBWControllerPolicyLocator().getNetworkingBWControllerPolicyPort(new java.net.URL(buildURL())); } setupInterface(m_NetworkingBWControllerPolicy); return m_NetworkingBWControllerPolicy;} public NetworkingBWPriorityGroupBindingStub getNetworkingBWPriorityGroup() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_NetworkingBWPriorityGroup ) { m_NetworkingBWPriorityGroup = (iControl.NetworkingBWPriorityGroupBindingStub) new iControl.NetworkingBWPriorityGroupLocator().getNetworkingBWPriorityGroupPort(new java.net.URL(buildURL())); } setupInterface(m_NetworkingBWPriorityGroup); return m_NetworkingBWPriorityGroup;} public NetworkingDNSResolverBindingStub getNetworkingDNSResolver() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_NetworkingDNSResolver ) { m_NetworkingDNSResolver = (iControl.NetworkingDNSResolverBindingStub) new iControl.NetworkingDNSResolverLocator().getNetworkingDNSResolverPort(new java.net.URL(buildURL())); } setupInterface(m_NetworkingDNSResolver); return m_NetworkingDNSResolver;} public NetworkingInterfacesBindingStub getNetworkingInterfaces() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_NetworkingInterfaces ) { m_NetworkingInterfaces = (iControl.NetworkingInterfacesBindingStub) new iControl.NetworkingInterfacesLocator().getNetworkingInterfacesPort(new java.net.URL(buildURL())); } setupInterface(m_NetworkingInterfaces); return m_NetworkingInterfaces;} public NetworkingIPsecIkeDaemonBindingStub getNetworkingIPsecIkeDaemon() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_NetworkingIPsecIkeDaemon ) { m_NetworkingIPsecIkeDaemon = (iControl.NetworkingIPsecIkeDaemonBindingStub) new iControl.NetworkingIPsecIkeDaemonLocator().getNetworkingIPsecIkeDaemonPort(new java.net.URL(buildURL())); } setupInterface(m_NetworkingIPsecIkeDaemon); return m_NetworkingIPsecIkeDaemon;} public NetworkingIPsecIkePeerBindingStub getNetworkingIPsecIkePeer() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_NetworkingIPsecIkePeer ) { m_NetworkingIPsecIkePeer = (iControl.NetworkingIPsecIkePeerBindingStub) new iControl.NetworkingIPsecIkePeerLocator().getNetworkingIPsecIkePeerPort(new java.net.URL(buildURL())); } setupInterface(m_NetworkingIPsecIkePeer); return m_NetworkingIPsecIkePeer;} public NetworkingIPsecManualSecurityAssociationBindingStub getNetworkingIPsecManualSecurityAssociation() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_NetworkingIPsecManualSecurityAssociation ) { m_NetworkingIPsecManualSecurityAssociation = (iControl.NetworkingIPsecManualSecurityAssociationBindingStub) new iControl.NetworkingIPsecManualSecurityAssociationLocator().getNetworkingIPsecManualSecurityAssociationPort(new java.net.URL(buildURL())); } setupInterface(m_NetworkingIPsecManualSecurityAssociation); return m_NetworkingIPsecManualSecurityAssociation;} public NetworkingIPsecPolicyBindingStub getNetworkingIPsecPolicy() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_NetworkingIPsecPolicy ) { m_NetworkingIPsecPolicy = (iControl.NetworkingIPsecPolicyBindingStub) new iControl.NetworkingIPsecPolicyLocator().getNetworkingIPsecPolicyPort(new java.net.URL(buildURL())); } setupInterface(m_NetworkingIPsecPolicy); return m_NetworkingIPsecPolicy;} public NetworkingIPsecTrafficSelectorBindingStub getNetworkingIPsecTrafficSelector() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_NetworkingIPsecTrafficSelector ) { m_NetworkingIPsecTrafficSelector = (iControl.NetworkingIPsecTrafficSelectorBindingStub) new iControl.NetworkingIPsecTrafficSelectorLocator().getNetworkingIPsecTrafficSelectorPort(new java.net.URL(buildURL())); } setupInterface(m_NetworkingIPsecTrafficSelector); return m_NetworkingIPsecTrafficSelector;} public NetworkingiSessionAdvertisedRouteBindingStub getNetworkingiSessionAdvertisedRoute() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_NetworkingiSessionAdvertisedRoute ) { m_NetworkingiSessionAdvertisedRoute = (iControl.NetworkingiSessionAdvertisedRouteBindingStub) new iControl.NetworkingiSessionAdvertisedRouteLocator().getNetworkingiSessionAdvertisedRoutePort(new java.net.URL(buildURL())); } setupInterface(m_NetworkingiSessionAdvertisedRoute); return m_NetworkingiSessionAdvertisedRoute;} public NetworkingiSessionAdvertisedRouteV2BindingStub getNetworkingiSessionAdvertisedRouteV2() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_NetworkingiSessionAdvertisedRouteV2 ) { m_NetworkingiSessionAdvertisedRouteV2 = (iControl.NetworkingiSessionAdvertisedRouteV2BindingStub) new iControl.NetworkingiSessionAdvertisedRouteV2Locator().getNetworkingiSessionAdvertisedRouteV2Port(new java.net.URL(buildURL())); } setupInterface(m_NetworkingiSessionAdvertisedRouteV2); return m_NetworkingiSessionAdvertisedRouteV2;} public NetworkingiSessionDatastorBindingStub getNetworkingiSessionDatastor() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_NetworkingiSessionDatastor ) { m_NetworkingiSessionDatastor = (iControl.NetworkingiSessionDatastorBindingStub) new iControl.NetworkingiSessionDatastorLocator().getNetworkingiSessionDatastorPort(new java.net.URL(buildURL())); } setupInterface(m_NetworkingiSessionDatastor); return m_NetworkingiSessionDatastor;} public NetworkingiSessionDeduplicationBindingStub getNetworkingiSessionDeduplication() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_NetworkingiSessionDeduplication ) { m_NetworkingiSessionDeduplication = (iControl.NetworkingiSessionDeduplicationBindingStub) new iControl.NetworkingiSessionDeduplicationLocator().getNetworkingiSessionDeduplicationPort(new java.net.URL(buildURL())); } setupInterface(m_NetworkingiSessionDeduplication); return m_NetworkingiSessionDeduplication;} public NetworkingiSessionLocalInterfaceBindingStub getNetworkingiSessionLocalInterface() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_NetworkingiSessionLocalInterface ) { m_NetworkingiSessionLocalInterface = (iControl.NetworkingiSessionLocalInterfaceBindingStub) new iControl.NetworkingiSessionLocalInterfaceLocator().getNetworkingiSessionLocalInterfacePort(new java.net.URL(buildURL())); } setupInterface(m_NetworkingiSessionLocalInterface); return m_NetworkingiSessionLocalInterface;} public NetworkingiSessionPeerDiscoveryBindingStub getNetworkingiSessionPeerDiscovery() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_NetworkingiSessionPeerDiscovery ) { m_NetworkingiSessionPeerDiscovery = (iControl.NetworkingiSessionPeerDiscoveryBindingStub) new iControl.NetworkingiSessionPeerDiscoveryLocator().getNetworkingiSessionPeerDiscoveryPort(new java.net.URL(buildURL())); } setupInterface(m_NetworkingiSessionPeerDiscovery); return m_NetworkingiSessionPeerDiscovery;} public NetworkingiSessionRemoteInterfaceBindingStub getNetworkingiSessionRemoteInterface() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_NetworkingiSessionRemoteInterface ) { m_NetworkingiSessionRemoteInterface = (iControl.NetworkingiSessionRemoteInterfaceBindingStub) new iControl.NetworkingiSessionRemoteInterfaceLocator().getNetworkingiSessionRemoteInterfacePort(new java.net.URL(buildURL())); } setupInterface(m_NetworkingiSessionRemoteInterface); return m_NetworkingiSessionRemoteInterface;} public NetworkingiSessionRemoteInterfaceV2BindingStub getNetworkingiSessionRemoteInterfaceV2() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_NetworkingiSessionRemoteInterfaceV2 ) { m_NetworkingiSessionRemoteInterfaceV2 = (iControl.NetworkingiSessionRemoteInterfaceV2BindingStub) new iControl.NetworkingiSessionRemoteInterfaceV2Locator().getNetworkingiSessionRemoteInterfaceV2Port(new java.net.URL(buildURL())); } setupInterface(m_NetworkingiSessionRemoteInterfaceV2); return m_NetworkingiSessionRemoteInterfaceV2;} public NetworkingLLDPGlobalsBindingStub getNetworkingLLDPGlobals() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_NetworkingLLDPGlobals ) { m_NetworkingLLDPGlobals = (iControl.NetworkingLLDPGlobalsBindingStub) new iControl.NetworkingLLDPGlobalsLocator().getNetworkingLLDPGlobalsPort(new java.net.URL(buildURL())); } setupInterface(m_NetworkingLLDPGlobals); return m_NetworkingLLDPGlobals;} public NetworkingMulticastRouteBindingStub getNetworkingMulticastRoute() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_NetworkingMulticastRoute ) { m_NetworkingMulticastRoute = (iControl.NetworkingMulticastRouteBindingStub) new iControl.NetworkingMulticastRouteLocator().getNetworkingMulticastRoutePort(new java.net.URL(buildURL())); } setupInterface(m_NetworkingMulticastRoute); return m_NetworkingMulticastRoute;} public NetworkingPacketFilterBindingStub getNetworkingPacketFilter() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_NetworkingPacketFilter ) { m_NetworkingPacketFilter = (iControl.NetworkingPacketFilterBindingStub) new iControl.NetworkingPacketFilterLocator().getNetworkingPacketFilterPort(new java.net.URL(buildURL())); } setupInterface(m_NetworkingPacketFilter); return m_NetworkingPacketFilter;} public NetworkingPacketFilterGlobalsBindingStub getNetworkingPacketFilterGlobals() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_NetworkingPacketFilterGlobals ) { m_NetworkingPacketFilterGlobals = (iControl.NetworkingPacketFilterGlobalsBindingStub) new iControl.NetworkingPacketFilterGlobalsLocator().getNetworkingPacketFilterGlobalsPort(new java.net.URL(buildURL())); } setupInterface(m_NetworkingPacketFilterGlobals); return m_NetworkingPacketFilterGlobals;} public NetworkingPortMirrorBindingStub getNetworkingPortMirror() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_NetworkingPortMirror ) { m_NetworkingPortMirror = (iControl.NetworkingPortMirrorBindingStub) new iControl.NetworkingPortMirrorLocator().getNetworkingPortMirrorPort(new java.net.URL(buildURL())); } setupInterface(m_NetworkingPortMirror); return m_NetworkingPortMirror;} public NetworkingProfileFECBindingStub getNetworkingProfileFEC() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_NetworkingProfileFEC ) { m_NetworkingProfileFEC = (iControl.NetworkingProfileFECBindingStub) new iControl.NetworkingProfileFECLocator().getNetworkingProfileFECPort(new java.net.URL(buildURL())); } setupInterface(m_NetworkingProfileFEC); return m_NetworkingProfileFEC;} public NetworkingProfileGeneveBindingStub getNetworkingProfileGeneve() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_NetworkingProfileGeneve ) { m_NetworkingProfileGeneve = (iControl.NetworkingProfileGeneveBindingStub) new iControl.NetworkingProfileGeneveLocator().getNetworkingProfileGenevePort(new java.net.URL(buildURL())); } setupInterface(m_NetworkingProfileGeneve); return m_NetworkingProfileGeneve;} public NetworkingProfileGREBindingStub getNetworkingProfileGRE() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_NetworkingProfileGRE ) { m_NetworkingProfileGRE = (iControl.NetworkingProfileGREBindingStub) new iControl.NetworkingProfileGRELocator().getNetworkingProfileGREPort(new java.net.URL(buildURL())); } setupInterface(m_NetworkingProfileGRE); return m_NetworkingProfileGRE;} public NetworkingProfileIPIPBindingStub getNetworkingProfileIPIP() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_NetworkingProfileIPIP ) { m_NetworkingProfileIPIP = (iControl.NetworkingProfileIPIPBindingStub) new iControl.NetworkingProfileIPIPLocator().getNetworkingProfileIPIPPort(new java.net.URL(buildURL())); } setupInterface(m_NetworkingProfileIPIP); return m_NetworkingProfileIPIP;} public NetworkingProfileIPsecBindingStub getNetworkingProfileIPsec() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_NetworkingProfileIPsec ) { m_NetworkingProfileIPsec = (iControl.NetworkingProfileIPsecBindingStub) new iControl.NetworkingProfileIPsecLocator().getNetworkingProfileIPsecPort(new java.net.URL(buildURL())); } setupInterface(m_NetworkingProfileIPsec); return m_NetworkingProfileIPsec;} public NetworkingProfileLightweight4Over6TunnelBindingStub getNetworkingProfileLightweight4Over6Tunnel() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_NetworkingProfileLightweight4Over6Tunnel ) { m_NetworkingProfileLightweight4Over6Tunnel = (iControl.NetworkingProfileLightweight4Over6TunnelBindingStub) new iControl.NetworkingProfileLightweight4Over6TunnelLocator().getNetworkingProfileLightweight4Over6TunnelPort(new java.net.URL(buildURL())); } setupInterface(m_NetworkingProfileLightweight4Over6Tunnel); return m_NetworkingProfileLightweight4Over6Tunnel;} public NetworkingProfileMAPBindingStub getNetworkingProfileMAP() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_NetworkingProfileMAP ) { m_NetworkingProfileMAP = (iControl.NetworkingProfileMAPBindingStub) new iControl.NetworkingProfileMAPLocator().getNetworkingProfileMAPPort(new java.net.URL(buildURL())); } setupInterface(m_NetworkingProfileMAP); return m_NetworkingProfileMAP;} public NetworkingProfileV6RDBindingStub getNetworkingProfileV6RD() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_NetworkingProfileV6RD ) { m_NetworkingProfileV6RD = (iControl.NetworkingProfileV6RDBindingStub) new iControl.NetworkingProfileV6RDLocator().getNetworkingProfileV6RDPort(new java.net.URL(buildURL())); } setupInterface(m_NetworkingProfileV6RD); return m_NetworkingProfileV6RD;} public NetworkingProfileVXLANBindingStub getNetworkingProfileVXLAN() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_NetworkingProfileVXLAN ) { m_NetworkingProfileVXLAN = (iControl.NetworkingProfileVXLANBindingStub) new iControl.NetworkingProfileVXLANLocator().getNetworkingProfileVXLANPort(new java.net.URL(buildURL())); } setupInterface(m_NetworkingProfileVXLAN); return m_NetworkingProfileVXLAN;} public NetworkingProfileWCCPGREBindingStub getNetworkingProfileWCCPGRE() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_NetworkingProfileWCCPGRE ) { m_NetworkingProfileWCCPGRE = (iControl.NetworkingProfileWCCPGREBindingStub) new iControl.NetworkingProfileWCCPGRELocator().getNetworkingProfileWCCPGREPort(new java.net.URL(buildURL())); } setupInterface(m_NetworkingProfileWCCPGRE); return m_NetworkingProfileWCCPGRE;} public NetworkingRouteDomainBindingStub getNetworkingRouteDomain() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_NetworkingRouteDomain ) { m_NetworkingRouteDomain = (iControl.NetworkingRouteDomainBindingStub) new iControl.NetworkingRouteDomainLocator().getNetworkingRouteDomainPort(new java.net.URL(buildURL())); } setupInterface(m_NetworkingRouteDomain); return m_NetworkingRouteDomain;} public NetworkingRouteDomainV2BindingStub getNetworkingRouteDomainV2() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_NetworkingRouteDomainV2 ) { m_NetworkingRouteDomainV2 = (iControl.NetworkingRouteDomainV2BindingStub) new iControl.NetworkingRouteDomainV2Locator().getNetworkingRouteDomainV2Port(new java.net.URL(buildURL())); } setupInterface(m_NetworkingRouteDomainV2); return m_NetworkingRouteDomainV2;} public NetworkingRouterAdvertisementBindingStub getNetworkingRouterAdvertisement() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_NetworkingRouterAdvertisement ) { m_NetworkingRouterAdvertisement = (iControl.NetworkingRouterAdvertisementBindingStub) new iControl.NetworkingRouterAdvertisementLocator().getNetworkingRouterAdvertisementPort(new java.net.URL(buildURL())); } setupInterface(m_NetworkingRouterAdvertisement); return m_NetworkingRouterAdvertisement;} public NetworkingRouteTableBindingStub getNetworkingRouteTable() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_NetworkingRouteTable ) { m_NetworkingRouteTable = (iControl.NetworkingRouteTableBindingStub) new iControl.NetworkingRouteTableLocator().getNetworkingRouteTablePort(new java.net.URL(buildURL())); } setupInterface(m_NetworkingRouteTable); return m_NetworkingRouteTable;} public NetworkingRouteTableV2BindingStub getNetworkingRouteTableV2() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_NetworkingRouteTableV2 ) { m_NetworkingRouteTableV2 = (iControl.NetworkingRouteTableV2BindingStub) new iControl.NetworkingRouteTableV2Locator().getNetworkingRouteTableV2Port(new java.net.URL(buildURL())); } setupInterface(m_NetworkingRouteTableV2); return m_NetworkingRouteTableV2;} public NetworkingSelfIPBindingStub getNetworkingSelfIP() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_NetworkingSelfIP ) { m_NetworkingSelfIP = (iControl.NetworkingSelfIPBindingStub) new iControl.NetworkingSelfIPLocator().getNetworkingSelfIPPort(new java.net.URL(buildURL())); } setupInterface(m_NetworkingSelfIP); return m_NetworkingSelfIP;} public NetworkingSelfIPPortLockdownBindingStub getNetworkingSelfIPPortLockdown() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_NetworkingSelfIPPortLockdown ) { m_NetworkingSelfIPPortLockdown = (iControl.NetworkingSelfIPPortLockdownBindingStub) new iControl.NetworkingSelfIPPortLockdownLocator().getNetworkingSelfIPPortLockdownPort(new java.net.URL(buildURL())); } setupInterface(m_NetworkingSelfIPPortLockdown); return m_NetworkingSelfIPPortLockdown;} public NetworkingSelfIPV2BindingStub getNetworkingSelfIPV2() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_NetworkingSelfIPV2 ) { m_NetworkingSelfIPV2 = (iControl.NetworkingSelfIPV2BindingStub) new iControl.NetworkingSelfIPV2Locator().getNetworkingSelfIPV2Port(new java.net.URL(buildURL())); } setupInterface(m_NetworkingSelfIPV2); return m_NetworkingSelfIPV2;} public NetworkingSTPGlobalsBindingStub getNetworkingSTPGlobals() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_NetworkingSTPGlobals ) { m_NetworkingSTPGlobals = (iControl.NetworkingSTPGlobalsBindingStub) new iControl.NetworkingSTPGlobalsLocator().getNetworkingSTPGlobalsPort(new java.net.URL(buildURL())); } setupInterface(m_NetworkingSTPGlobals); return m_NetworkingSTPGlobals;} public NetworkingSTPInstanceBindingStub getNetworkingSTPInstance() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_NetworkingSTPInstance ) { m_NetworkingSTPInstance = (iControl.NetworkingSTPInstanceBindingStub) new iControl.NetworkingSTPInstanceLocator().getNetworkingSTPInstancePort(new java.net.URL(buildURL())); } setupInterface(m_NetworkingSTPInstance); return m_NetworkingSTPInstance;} public NetworkingSTPInstanceV2BindingStub getNetworkingSTPInstanceV2() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_NetworkingSTPInstanceV2 ) { m_NetworkingSTPInstanceV2 = (iControl.NetworkingSTPInstanceV2BindingStub) new iControl.NetworkingSTPInstanceV2Locator().getNetworkingSTPInstanceV2Port(new java.net.URL(buildURL())); } setupInterface(m_NetworkingSTPInstanceV2); return m_NetworkingSTPInstanceV2;} public NetworkingTrunkBindingStub getNetworkingTrunk() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_NetworkingTrunk ) { m_NetworkingTrunk = (iControl.NetworkingTrunkBindingStub) new iControl.NetworkingTrunkLocator().getNetworkingTrunkPort(new java.net.URL(buildURL())); } setupInterface(m_NetworkingTrunk); return m_NetworkingTrunk;} public NetworkingTunnelBindingStub getNetworkingTunnel() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_NetworkingTunnel ) { m_NetworkingTunnel = (iControl.NetworkingTunnelBindingStub) new iControl.NetworkingTunnelLocator().getNetworkingTunnelPort(new java.net.URL(buildURL())); } setupInterface(m_NetworkingTunnel); return m_NetworkingTunnel;} public NetworkingVLANBindingStub getNetworkingVLAN() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_NetworkingVLAN ) { m_NetworkingVLAN = (iControl.NetworkingVLANBindingStub) new iControl.NetworkingVLANLocator().getNetworkingVLANPort(new java.net.URL(buildURL())); } setupInterface(m_NetworkingVLAN); return m_NetworkingVLAN;} public NetworkingVLANGroupBindingStub getNetworkingVLANGroup() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_NetworkingVLANGroup ) { m_NetworkingVLANGroup = (iControl.NetworkingVLANGroupBindingStub) new iControl.NetworkingVLANGroupLocator().getNetworkingVLANGroupPort(new java.net.URL(buildURL())); } setupInterface(m_NetworkingVLANGroup); return m_NetworkingVLANGroup;} public PEMFormatScriptBindingStub getPEMFormatScript() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_PEMFormatScript ) { m_PEMFormatScript = (iControl.PEMFormatScriptBindingStub) new iControl.PEMFormatScriptLocator().getPEMFormatScriptPort(new java.net.URL(buildURL())); } setupInterface(m_PEMFormatScript); return m_PEMFormatScript;} public PEMForwardingEndpointBindingStub getPEMForwardingEndpoint() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_PEMForwardingEndpoint ) { m_PEMForwardingEndpoint = (iControl.PEMForwardingEndpointBindingStub) new iControl.PEMForwardingEndpointLocator().getPEMForwardingEndpointPort(new java.net.URL(buildURL())); } setupInterface(m_PEMForwardingEndpoint); return m_PEMForwardingEndpoint;} public PEMInterceptionEndpointBindingStub getPEMInterceptionEndpoint() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_PEMInterceptionEndpoint ) { m_PEMInterceptionEndpoint = (iControl.PEMInterceptionEndpointBindingStub) new iControl.PEMInterceptionEndpointLocator().getPEMInterceptionEndpointPort(new java.net.URL(buildURL())); } setupInterface(m_PEMInterceptionEndpoint); return m_PEMInterceptionEndpoint;} public PEMListenerBindingStub getPEMListener() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_PEMListener ) { m_PEMListener = (iControl.PEMListenerBindingStub) new iControl.PEMListenerLocator().getPEMListenerPort(new java.net.URL(buildURL())); } setupInterface(m_PEMListener); return m_PEMListener;} public PEMPolicyBindingStub getPEMPolicy() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_PEMPolicy ) { m_PEMPolicy = (iControl.PEMPolicyBindingStub) new iControl.PEMPolicyLocator().getPEMPolicyPort(new java.net.URL(buildURL())); } setupInterface(m_PEMPolicy); return m_PEMPolicy;} public PEMServiceChainEndpointBindingStub getPEMServiceChainEndpoint() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_PEMServiceChainEndpoint ) { m_PEMServiceChainEndpoint = (iControl.PEMServiceChainEndpointBindingStub) new iControl.PEMServiceChainEndpointLocator().getPEMServiceChainEndpointPort(new java.net.URL(buildURL())); } setupInterface(m_PEMServiceChainEndpoint); return m_PEMServiceChainEndpoint;} public PEMSubscriberBindingStub getPEMSubscriber() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_PEMSubscriber ) { m_PEMSubscriber = (iControl.PEMSubscriberBindingStub) new iControl.PEMSubscriberLocator().getPEMSubscriberPort(new java.net.URL(buildURL())); } setupInterface(m_PEMSubscriber); return m_PEMSubscriber;} public SecurityDoSDeviceBindingStub getSecurityDoSDevice() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_SecurityDoSDevice ) { m_SecurityDoSDevice = (iControl.SecurityDoSDeviceBindingStub) new iControl.SecurityDoSDeviceLocator().getSecurityDoSDevicePort(new java.net.URL(buildURL())); } setupInterface(m_SecurityDoSDevice); return m_SecurityDoSDevice;} public SecurityDoSWhitelistBindingStub getSecurityDoSWhitelist() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_SecurityDoSWhitelist ) { m_SecurityDoSWhitelist = (iControl.SecurityDoSWhitelistBindingStub) new iControl.SecurityDoSWhitelistLocator().getSecurityDoSWhitelistPort(new java.net.URL(buildURL())); } setupInterface(m_SecurityDoSWhitelist); return m_SecurityDoSWhitelist;} public SecurityFirewallAddressListBindingStub getSecurityFirewallAddressList() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_SecurityFirewallAddressList ) { m_SecurityFirewallAddressList = (iControl.SecurityFirewallAddressListBindingStub) new iControl.SecurityFirewallAddressListLocator().getSecurityFirewallAddressListPort(new java.net.URL(buildURL())); } setupInterface(m_SecurityFirewallAddressList); return m_SecurityFirewallAddressList;} public SecurityFirewallGlobalAdminIPRuleListBindingStub getSecurityFirewallGlobalAdminIPRuleList() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_SecurityFirewallGlobalAdminIPRuleList ) { m_SecurityFirewallGlobalAdminIPRuleList = (iControl.SecurityFirewallGlobalAdminIPRuleListBindingStub) new iControl.SecurityFirewallGlobalAdminIPRuleListLocator().getSecurityFirewallGlobalAdminIPRuleListPort(new java.net.URL(buildURL())); } setupInterface(m_SecurityFirewallGlobalAdminIPRuleList); return m_SecurityFirewallGlobalAdminIPRuleList;} public SecurityFirewallGlobalRuleListBindingStub getSecurityFirewallGlobalRuleList() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_SecurityFirewallGlobalRuleList ) { m_SecurityFirewallGlobalRuleList = (iControl.SecurityFirewallGlobalRuleListBindingStub) new iControl.SecurityFirewallGlobalRuleListLocator().getSecurityFirewallGlobalRuleListPort(new java.net.URL(buildURL())); } setupInterface(m_SecurityFirewallGlobalRuleList); return m_SecurityFirewallGlobalRuleList;} public SecurityFirewallPolicyBindingStub getSecurityFirewallPolicy() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_SecurityFirewallPolicy ) { m_SecurityFirewallPolicy = (iControl.SecurityFirewallPolicyBindingStub) new iControl.SecurityFirewallPolicyLocator().getSecurityFirewallPolicyPort(new java.net.URL(buildURL())); } setupInterface(m_SecurityFirewallPolicy); return m_SecurityFirewallPolicy;} public SecurityFirewallPortListBindingStub getSecurityFirewallPortList() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_SecurityFirewallPortList ) { m_SecurityFirewallPortList = (iControl.SecurityFirewallPortListBindingStub) new iControl.SecurityFirewallPortListLocator().getSecurityFirewallPortListPort(new java.net.URL(buildURL())); } setupInterface(m_SecurityFirewallPortList); return m_SecurityFirewallPortList;} public SecurityFirewallRuleListBindingStub getSecurityFirewallRuleList() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_SecurityFirewallRuleList ) { m_SecurityFirewallRuleList = (iControl.SecurityFirewallRuleListBindingStub) new iControl.SecurityFirewallRuleListLocator().getSecurityFirewallRuleListPort(new java.net.URL(buildURL())); } setupInterface(m_SecurityFirewallRuleList); return m_SecurityFirewallRuleList;} public SecurityFirewallWeeklyScheduleBindingStub getSecurityFirewallWeeklySchedule() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_SecurityFirewallWeeklySchedule ) { m_SecurityFirewallWeeklySchedule = (iControl.SecurityFirewallWeeklyScheduleBindingStub) new iControl.SecurityFirewallWeeklyScheduleLocator().getSecurityFirewallWeeklySchedulePort(new java.net.URL(buildURL())); } setupInterface(m_SecurityFirewallWeeklySchedule); return m_SecurityFirewallWeeklySchedule;} public SecurityIPIntelligenceBlacklistCategoryBindingStub getSecurityIPIntelligenceBlacklistCategory() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_SecurityIPIntelligenceBlacklistCategory ) { m_SecurityIPIntelligenceBlacklistCategory = (iControl.SecurityIPIntelligenceBlacklistCategoryBindingStub) new iControl.SecurityIPIntelligenceBlacklistCategoryLocator().getSecurityIPIntelligenceBlacklistCategoryPort(new java.net.URL(buildURL())); } setupInterface(m_SecurityIPIntelligenceBlacklistCategory); return m_SecurityIPIntelligenceBlacklistCategory;} public SecurityIPIntelligenceFeedListBindingStub getSecurityIPIntelligenceFeedList() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_SecurityIPIntelligenceFeedList ) { m_SecurityIPIntelligenceFeedList = (iControl.SecurityIPIntelligenceFeedListBindingStub) new iControl.SecurityIPIntelligenceFeedListLocator().getSecurityIPIntelligenceFeedListPort(new java.net.URL(buildURL())); } setupInterface(m_SecurityIPIntelligenceFeedList); return m_SecurityIPIntelligenceFeedList;} public SecurityIPIntelligenceGlobalPolicyBindingStub getSecurityIPIntelligenceGlobalPolicy() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_SecurityIPIntelligenceGlobalPolicy ) { m_SecurityIPIntelligenceGlobalPolicy = (iControl.SecurityIPIntelligenceGlobalPolicyBindingStub) new iControl.SecurityIPIntelligenceGlobalPolicyLocator().getSecurityIPIntelligenceGlobalPolicyPort(new java.net.URL(buildURL())); } setupInterface(m_SecurityIPIntelligenceGlobalPolicy); return m_SecurityIPIntelligenceGlobalPolicy;} public SecurityIPIntelligencePolicyBindingStub getSecurityIPIntelligencePolicy() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_SecurityIPIntelligencePolicy ) { m_SecurityIPIntelligencePolicy = (iControl.SecurityIPIntelligencePolicyBindingStub) new iControl.SecurityIPIntelligencePolicyLocator().getSecurityIPIntelligencePolicyPort(new java.net.URL(buildURL())); } setupInterface(m_SecurityIPIntelligencePolicy); return m_SecurityIPIntelligencePolicy;} public SecurityLogProfileBindingStub getSecurityLogProfile() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_SecurityLogProfile ) { m_SecurityLogProfile = (iControl.SecurityLogProfileBindingStub) new iControl.SecurityLogProfileLocator().getSecurityLogProfilePort(new java.net.URL(buildURL())); } setupInterface(m_SecurityLogProfile); return m_SecurityLogProfile;} public SecurityProfileDNSSecurityBindingStub getSecurityProfileDNSSecurity() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_SecurityProfileDNSSecurity ) { m_SecurityProfileDNSSecurity = (iControl.SecurityProfileDNSSecurityBindingStub) new iControl.SecurityProfileDNSSecurityLocator().getSecurityProfileDNSSecurityPort(new java.net.URL(buildURL())); } setupInterface(m_SecurityProfileDNSSecurity); return m_SecurityProfileDNSSecurity;} public SecurityProfileDoSBindingStub getSecurityProfileDoS() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_SecurityProfileDoS ) { m_SecurityProfileDoS = (iControl.SecurityProfileDoSBindingStub) new iControl.SecurityProfileDoSLocator().getSecurityProfileDoSPort(new java.net.URL(buildURL())); } setupInterface(m_SecurityProfileDoS); return m_SecurityProfileDoS;} public SecurityProfileIPIntelligenceBindingStub getSecurityProfileIPIntelligence() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_SecurityProfileIPIntelligence ) { m_SecurityProfileIPIntelligence = (iControl.SecurityProfileIPIntelligenceBindingStub) new iControl.SecurityProfileIPIntelligenceLocator().getSecurityProfileIPIntelligencePort(new java.net.URL(buildURL())); } setupInterface(m_SecurityProfileIPIntelligence); return m_SecurityProfileIPIntelligence;} public SystemCABundleManagerBindingStub getSystemCABundleManager() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_SystemCABundleManager ) { m_SystemCABundleManager = (iControl.SystemCABundleManagerBindingStub) new iControl.SystemCABundleManagerLocator().getSystemCABundleManagerPort(new java.net.URL(buildURL())); } setupInterface(m_SystemCABundleManager); return m_SystemCABundleManager;} public SystemCertificateRevocationListFileBindingStub getSystemCertificateRevocationListFile() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_SystemCertificateRevocationListFile ) { m_SystemCertificateRevocationListFile = (iControl.SystemCertificateRevocationListFileBindingStub) new iControl.SystemCertificateRevocationListFileLocator().getSystemCertificateRevocationListFilePort(new java.net.URL(buildURL())); } setupInterface(m_SystemCertificateRevocationListFile); return m_SystemCertificateRevocationListFile;} public SystemClusterBindingStub getSystemCluster() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_SystemCluster ) { m_SystemCluster = (iControl.SystemClusterBindingStub) new iControl.SystemClusterLocator().getSystemClusterPort(new java.net.URL(buildURL())); } setupInterface(m_SystemCluster); return m_SystemCluster;} public SystemConfigSyncBindingStub getSystemConfigSync() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_SystemConfigSync ) { m_SystemConfigSync = (iControl.SystemConfigSyncBindingStub) new iControl.SystemConfigSyncLocator().getSystemConfigSyncPort(new java.net.URL(buildURL())); } setupInterface(m_SystemConfigSync); return m_SystemConfigSync;} public SystemCryptoClientBindingStub getSystemCryptoClient() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_SystemCryptoClient ) { m_SystemCryptoClient = (iControl.SystemCryptoClientBindingStub) new iControl.SystemCryptoClientLocator().getSystemCryptoClientPort(new java.net.URL(buildURL())); } setupInterface(m_SystemCryptoClient); return m_SystemCryptoClient;} public SystemCryptoServerBindingStub getSystemCryptoServer() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_SystemCryptoServer ) { m_SystemCryptoServer = (iControl.SystemCryptoServerBindingStub) new iControl.SystemCryptoServerLocator().getSystemCryptoServerPort(new java.net.URL(buildURL())); } setupInterface(m_SystemCryptoServer); return m_SystemCryptoServer;} public SystemDiskBindingStub getSystemDisk() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_SystemDisk ) { m_SystemDisk = (iControl.SystemDiskBindingStub) new iControl.SystemDiskLocator().getSystemDiskPort(new java.net.URL(buildURL())); } setupInterface(m_SystemDisk); return m_SystemDisk;} public SystemExternalMonitorFileBindingStub getSystemExternalMonitorFile() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_SystemExternalMonitorFile ) { m_SystemExternalMonitorFile = (iControl.SystemExternalMonitorFileBindingStub) new iControl.SystemExternalMonitorFileLocator().getSystemExternalMonitorFilePort(new java.net.URL(buildURL())); } setupInterface(m_SystemExternalMonitorFile); return m_SystemExternalMonitorFile;} public SystemFailoverBindingStub getSystemFailover() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_SystemFailover ) { m_SystemFailover = (iControl.SystemFailoverBindingStub) new iControl.SystemFailoverLocator().getSystemFailoverPort(new java.net.URL(buildURL())); } setupInterface(m_SystemFailover); return m_SystemFailover;} public SystemGeoIPBindingStub getSystemGeoIP() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_SystemGeoIP ) { m_SystemGeoIP = (iControl.SystemGeoIPBindingStub) new iControl.SystemGeoIPLocator().getSystemGeoIPPort(new java.net.URL(buildURL())); } setupInterface(m_SystemGeoIP); return m_SystemGeoIP;} public SystemHAGroupBindingStub getSystemHAGroup() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_SystemHAGroup ) { m_SystemHAGroup = (iControl.SystemHAGroupBindingStub) new iControl.SystemHAGroupLocator().getSystemHAGroupPort(new java.net.URL(buildURL())); } setupInterface(m_SystemHAGroup); return m_SystemHAGroup;} public SystemHAStatusBindingStub getSystemHAStatus() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_SystemHAStatus ) { m_SystemHAStatus = (iControl.SystemHAStatusBindingStub) new iControl.SystemHAStatusLocator().getSystemHAStatusPort(new java.net.URL(buildURL())); } setupInterface(m_SystemHAStatus); return m_SystemHAStatus;} public SystemInetBindingStub getSystemInet() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_SystemInet ) { m_SystemInet = (iControl.SystemInetBindingStub) new iControl.SystemInetLocator().getSystemInetPort(new java.net.URL(buildURL())); } setupInterface(m_SystemInet); return m_SystemInet;} public SystemLightweightTunnelTableFileBindingStub getSystemLightweightTunnelTableFile() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_SystemLightweightTunnelTableFile ) { m_SystemLightweightTunnelTableFile = (iControl.SystemLightweightTunnelTableFileBindingStub) new iControl.SystemLightweightTunnelTableFileLocator().getSystemLightweightTunnelTableFilePort(new java.net.URL(buildURL())); } setupInterface(m_SystemLightweightTunnelTableFile); return m_SystemLightweightTunnelTableFile;} public SystemPerformanceSFlowBindingStub getSystemPerformanceSFlow() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_SystemPerformanceSFlow ) { m_SystemPerformanceSFlow = (iControl.SystemPerformanceSFlowBindingStub) new iControl.SystemPerformanceSFlowLocator().getSystemPerformanceSFlowPort(new java.net.URL(buildURL())); } setupInterface(m_SystemPerformanceSFlow); return m_SystemPerformanceSFlow;} public SystemServicesBindingStub getSystemServices() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_SystemServices ) { m_SystemServices = (iControl.SystemServicesBindingStub) new iControl.SystemServicesLocator().getSystemServicesPort(new java.net.URL(buildURL())); } setupInterface(m_SystemServices); return m_SystemServices;} public SystemSessionBindingStub getSystemSession() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_SystemSession ) { m_SystemSession = (iControl.SystemSessionBindingStub) new iControl.SystemSessionLocator().getSystemSessionPort(new java.net.URL(buildURL())); } setupInterface(m_SystemSession); return m_SystemSession;} public SystemSoftwareManagementBindingStub getSystemSoftwareManagement() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_SystemSoftwareManagement ) { m_SystemSoftwareManagement = (iControl.SystemSoftwareManagementBindingStub) new iControl.SystemSoftwareManagementLocator().getSystemSoftwareManagementPort(new java.net.URL(buildURL())); } setupInterface(m_SystemSoftwareManagement); return m_SystemSoftwareManagement;} public SystemStatisticsBindingStub getSystemStatistics() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_SystemStatistics ) { m_SystemStatistics = (iControl.SystemStatisticsBindingStub) new iControl.SystemStatisticsLocator().getSystemStatisticsPort(new java.net.URL(buildURL())); } setupInterface(m_SystemStatistics); return m_SystemStatistics;} public SystemSystemInfoBindingStub getSystemSystemInfo() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_SystemSystemInfo ) { m_SystemSystemInfo = (iControl.SystemSystemInfoBindingStub) new iControl.SystemSystemInfoLocator().getSystemSystemInfoPort(new java.net.URL(buildURL())); } setupInterface(m_SystemSystemInfo); return m_SystemSystemInfo;} public SystemVCMPBindingStub getSystemVCMP() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_SystemVCMP ) { m_SystemVCMP = (iControl.SystemVCMPBindingStub) new iControl.SystemVCMPLocator().getSystemVCMPPort(new java.net.URL(buildURL())); } setupInterface(m_SystemVCMP); return m_SystemVCMP;} public WebAcceleratorApplicationsBindingStub getWebAcceleratorApplications() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_WebAcceleratorApplications ) { m_WebAcceleratorApplications = (iControl.WebAcceleratorApplicationsBindingStub) new iControl.WebAcceleratorApplicationsLocator().getWebAcceleratorApplicationsPort(new java.net.URL(buildURL())); } setupInterface(m_WebAcceleratorApplications); return m_WebAcceleratorApplications;} public WebAcceleratorPoliciesBindingStub getWebAcceleratorPolicies() throws Exception { if (!m_bInitialized ) { throw new IllegalStateException("Not Initialized"); } if (null == m_WebAcceleratorPolicies ) { m_WebAcceleratorPolicies = (iControl.WebAcceleratorPoliciesBindingStub) new iControl.WebAcceleratorPoliciesLocator().getWebAcceleratorPoliciesPort(new java.net.URL(buildURL())); } setupInterface(m_WebAcceleratorPolicies); return m_WebAcceleratorPolicies;} //------------------------------------------------------------------- // Constructor //------------------------------------------------------------------- public Interfaces() { System.setProperty("javax.net.ssl.trustStore", System.getProperty("user.home") + "/.keystore"); XTrustProvider.install(); } public Interfaces(String hostname, String username, String password) { System.setProperty("javax.net.ssl.trustStore", System.getProperty("user.home") + "/.keystore"); XTrustProvider.install(); initialize(hostname, username, password); } public Interfaces(String hostname, long port, String username, String password) { System.setProperty("javax.net.ssl.trustStore", System.getProperty("user.home") + "/.keystore"); XTrustProvider.install(); initialize(hostname, port, username, password); } //------------------------------------------------------------------- // private methods //------------------------------------------------------------------- private String buildURL() { String url = "http"; if ( 443 == m_port ) { url = url + "s"; } //url = url + "://" + m_username + ":" + m_password + "@" + m_hostname + ":" + m_port + "/iControl/iControlPortal.cgi"; url = url + "://" + m_hostname + ":" + m_port + "/iControl/iControlPortal.cgi"; return url; } //------------------------------------------------------------------- // public methods //------------------------------------------------------------------- public Boolean initialize(String hostname, String username, String password) { return initialize(hostname, 443, username, password); } public Boolean initialize(String hostname, long port, String username, String password) { m_bInitialized = false; m_hostname = hostname; m_port = port; m_username = username; m_password = password; m_ASMLoggingProfile = null; m_ASMPolicy = null; m_ASMPolicyGroup = null; m_ASMSystemConfiguration = null; m_ASMWebApplication = null; m_ASMWebApplicationGroup = null; m_ClassificationApplication = null; m_ClassificationCategory = null; m_ClassificationSignatureDefinition = null; m_ClassificationSignatureUpdateSchedule = null; m_ClassificationSignatureVersion = null; m_GlobalLBApplication = null; m_GlobalLBDataCenter = null; m_GlobalLBDNSSECKey = null; m_GlobalLBDNSSECZone = null; m_GlobalLBGlobals = null; m_GlobalLBLink = null; m_GlobalLBMonitor = null; m_GlobalLBPool = null; m_GlobalLBPoolMember = null; m_GlobalLBPoolV2 = null; m_GlobalLBProberPool = null; m_GlobalLBRegion = null; m_GlobalLBRule = null; m_GlobalLBServer = null; m_GlobalLBTopology = null; m_GlobalLBVirtualServer = null; m_GlobalLBVirtualServerV2 = null; m_GlobalLBWideIP = null; m_GlobalLBWideIPV2 = null; m_iCallPeriodicHandler = null; m_iCallPerpetualHandler = null; m_iCallScript = null; m_iCallTriggeredHandler = null; m_LocalLBALGLogProfile = null; m_LocalLBCipherGroup = null; m_LocalLBCipherRule = null; m_LocalLBClass = null; m_LocalLBContentPolicy = null; m_LocalLBContentPolicyStrategy = null; m_LocalLBDataGroupFile = null; m_LocalLBDNSCache = null; m_LocalLBDNSExpress = null; m_LocalLBDNSGlobals = null; m_LocalLBDNSServer = null; m_LocalLBDNSTSIGKey = null; m_LocalLBDNSZone = null; m_LocalLBFlowEvictionPolicy = null; m_LocalLBiFile = null; m_LocalLBiFileFile = null; m_LocalLBLSNLogProfile = null; m_LocalLBLSNPool = null; m_LocalLBMessageRoutingPeer = null; m_LocalLBMessageRoutingSIPRoute = null; m_LocalLBMessageRoutingTransportConfig = null; m_LocalLBMonitor = null; m_LocalLBNAT = null; m_LocalLBNATV2 = null; m_LocalLBNodeAddress = null; m_LocalLBNodeAddressV2 = null; m_LocalLBOCSPStaplingParameters = null; m_LocalLBPool = null; m_LocalLBPoolMember = null; m_LocalLBProfileAnalytics = null; m_LocalLBProfileAuth = null; m_LocalLBProfileClassification = null; m_LocalLBProfileClientLDAP = null; m_LocalLBProfileClientSSL = null; m_LocalLBProfileDiameter = null; m_LocalLBProfileDiameterEndpoint = null; m_LocalLBProfileDiameterRouter = null; m_LocalLBProfileDiameterSession = null; m_LocalLBProfileDNS = null; m_LocalLBProfileDNSLogging = null; m_LocalLBProfileFastHttp = null; m_LocalLBProfileFastL4 = null; m_LocalLBProfileFIX = null; m_LocalLBProfileFTP = null; m_LocalLBProfileHttp = null; m_LocalLBProfileHttpClass = null; m_LocalLBProfileHttpCompression = null; m_LocalLBProfileICAP = null; m_LocalLBProfileIIOP = null; m_LocalLBProfileIPsecALG = null; m_LocalLBProfileOneConnect = null; m_LocalLBProfilePCP = null; m_LocalLBProfilePersistence = null; m_LocalLBProfilePPTP = null; m_LocalLBProfileRADIUS = null; m_LocalLBProfileRequestAdapt = null; m_LocalLBProfileRequestLogging = null; m_LocalLBProfileResponseAdapt = null; m_LocalLBProfileRTSP = null; m_LocalLBProfileSCTP = null; m_LocalLBProfileServerLDAP = null; m_LocalLBProfileServerSSL = null; m_LocalLBProfileSIP = null; m_LocalLBProfileSIPRouter = null; m_LocalLBProfileSIPSession = null; m_LocalLBProfileSMTPS = null; m_LocalLBProfileSPDY = null; m_LocalLBProfileSPM = null; m_LocalLBProfileStream = null; m_LocalLBProfileTCP = null; m_LocalLBProfileTCPAnalytics = null; m_LocalLBProfileTFTP = null; m_LocalLBProfileTrafficAcceleration = null; m_LocalLBProfileUDP = null; m_LocalLBProfileUserStatistic = null; m_LocalLBProfileWebAcceleration = null; m_LocalLBProfileXML = null; m_LocalLBRAMCacheInformation = null; m_LocalLBRateClass = null; m_LocalLBRule = null; m_LocalLBSNAT = null; m_LocalLBSNATPool = null; m_LocalLBSNATPoolMember = null; m_LocalLBSNATTranslationAddress = null; m_LocalLBSNATTranslationAddressV2 = null; m_LocalLBVirtualAddress = null; m_LocalLBVirtualAddressV2 = null; m_LocalLBVirtualServer = null; m_LogDestinationArcSight = null; m_LogDestinationIPFIX = null; m_LogDestinationLocalSyslog = null; m_LogDestinationManagementPort = null; m_LogDestinationRemoteHighSpeedLog = null; m_LogDestinationRemoteSyslog = null; m_LogDestinationSplunk = null; m_LogFilter = null; m_LogIPFIXInformationElement = null; m_LogPublisher = null; m_LTConfigClass = null; m_LTConfigField = null; m_ManagementApplicationPresentationScript = null; m_ManagementApplicationService = null; m_ManagementApplicationTemplate = null; m_ManagementCCLDAPConfiguration = null; m_ManagementCertificateValidatorOCSP = null; m_ManagementCertLDAPConfiguration = null; m_ManagementCLIScript = null; m_ManagementCRLDPConfiguration = null; m_ManagementCRLDPServer = null; m_ManagementDBVariable = null; m_ManagementDevice = null; m_ManagementDeviceGroup = null; m_ManagementEM = null; m_ManagementEventNotification = null; m_ManagementEventSubscription = null; m_ManagementFeatureModule = null; m_ManagementFolder = null; m_ManagementGlobals = null; m_ManagementKeyCertificate = null; m_ManagementLDAPConfiguration = null; m_ManagementLicenseAdministration = null; m_ManagementNamed = null; m_ManagementOCSPConfiguration = null; m_ManagementOCSPResponder = null; m_ManagementPartition = null; m_ManagementProvision = null; m_ManagementRADIUSConfiguration = null; m_ManagementRADIUSServer = null; m_ManagementResourceRecord = null; m_ManagementSFlowDataSource = null; m_ManagementSFlowGlobals = null; m_ManagementSFlowReceiver = null; m_ManagementSMTPConfiguration = null; m_ManagementSNMPConfiguration = null; m_ManagementTACACSConfiguration = null; m_ManagementTMOSModule = null; m_ManagementTrafficGroup = null; m_ManagementTrust = null; m_ManagementUserManagement = null; m_ManagementView = null; m_ManagementZone = null; m_ManagementZoneRunner = null; m_NetworkingAdminIP = null; m_NetworkingARP = null; m_NetworkingBWControllerPolicy = null; m_NetworkingBWPriorityGroup = null; m_NetworkingDNSResolver = null; m_NetworkingInterfaces = null; m_NetworkingIPsecIkeDaemon = null; m_NetworkingIPsecIkePeer = null; m_NetworkingIPsecManualSecurityAssociation = null; m_NetworkingIPsecPolicy = null; m_NetworkingIPsecTrafficSelector = null; m_NetworkingiSessionAdvertisedRoute = null; m_NetworkingiSessionAdvertisedRouteV2 = null; m_NetworkingiSessionDatastor = null; m_NetworkingiSessionDeduplication = null; m_NetworkingiSessionLocalInterface = null; m_NetworkingiSessionPeerDiscovery = null; m_NetworkingiSessionRemoteInterface = null; m_NetworkingiSessionRemoteInterfaceV2 = null; m_NetworkingLLDPGlobals = null; m_NetworkingMulticastRoute = null; m_NetworkingPacketFilter = null; m_NetworkingPacketFilterGlobals = null; m_NetworkingPortMirror = null; m_NetworkingProfileFEC = null; m_NetworkingProfileGeneve = null; m_NetworkingProfileGRE = null; m_NetworkingProfileIPIP = null; m_NetworkingProfileIPsec = null; m_NetworkingProfileLightweight4Over6Tunnel = null; m_NetworkingProfileMAP = null; m_NetworkingProfileV6RD = null; m_NetworkingProfileVXLAN = null; m_NetworkingProfileWCCPGRE = null; m_NetworkingRouteDomain = null; m_NetworkingRouteDomainV2 = null; m_NetworkingRouterAdvertisement = null; m_NetworkingRouteTable = null; m_NetworkingRouteTableV2 = null; m_NetworkingSelfIP = null; m_NetworkingSelfIPPortLockdown = null; m_NetworkingSelfIPV2 = null; m_NetworkingSTPGlobals = null; m_NetworkingSTPInstance = null; m_NetworkingSTPInstanceV2 = null; m_NetworkingTrunk = null; m_NetworkingTunnel = null; m_NetworkingVLAN = null; m_NetworkingVLANGroup = null; m_PEMFormatScript = null; m_PEMForwardingEndpoint = null; m_PEMInterceptionEndpoint = null; m_PEMListener = null; m_PEMPolicy = null; m_PEMServiceChainEndpoint = null; m_PEMSubscriber = null; m_SecurityDoSDevice = null; m_SecurityDoSWhitelist = null; m_SecurityFirewallAddressList = null; m_SecurityFirewallGlobalAdminIPRuleList = null; m_SecurityFirewallGlobalRuleList = null; m_SecurityFirewallPolicy = null; m_SecurityFirewallPortList = null; m_SecurityFirewallRuleList = null; m_SecurityFirewallWeeklySchedule = null; m_SecurityIPIntelligenceBlacklistCategory = null; m_SecurityIPIntelligenceFeedList = null; m_SecurityIPIntelligenceGlobalPolicy = null; m_SecurityIPIntelligencePolicy = null; m_SecurityLogProfile = null; m_SecurityProfileDNSSecurity = null; m_SecurityProfileDoS = null; m_SecurityProfileIPIntelligence = null; m_SystemCABundleManager = null; m_SystemCertificateRevocationListFile = null; m_SystemCluster = null; m_SystemConfigSync = null; m_SystemCryptoClient = null; m_SystemCryptoServer = null; m_SystemDisk = null; m_SystemExternalMonitorFile = null; m_SystemFailover = null; m_SystemGeoIP = null; m_SystemHAGroup = null; m_SystemHAStatus = null; m_SystemInet = null; m_SystemLightweightTunnelTableFile = null; m_SystemPerformanceSFlow = null; m_SystemServices = null; m_SystemSession = null; m_SystemSoftwareManagement = null; m_SystemStatistics = null; m_SystemSystemInfo = null; m_SystemVCMP = null; m_WebAcceleratorApplications = null; m_WebAcceleratorPolicies = null; m_bInitialized = true; return m_bInitialized; } };
mit
AI-comp/Orientation2015Problems
islands/tests/Validator.java
627
import java.util.Scanner; public class Validator { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int d = sc.nextInt(); checkRange(d, 1, 100); while (d-- > 0) { int v = sc.nextInt(); int e = sc.nextInt(); checkRange(v, 2, 1000); checkRange(e, 0, 1000); for (int i = 0; i < e; i++) { int s = sc.nextInt(); int g = sc.nextInt(); checkRange(s, 1, v); checkRange(g, 1, v); if (s == g) System.exit(1); } } sc.close(); } private static void checkRange(int n, int min, int max) { if (n >= min && n <= max) return; System.exit(1); } }
mit
mvaduva87/krol
krol-data/src/main/java/ro/mv/krol/util/Args.java
3328
package ro.mv.krol.util; import java.util.Collection; import java.util.List; import java.util.Map; /** * Created by mihai.vaduva on 07/08/2016. */ public class Args { public static <S> S notNull(S obj) throws IllegalArgumentException { return notNull(obj, null); } public static <S> S notNull(S obj, String name) throws IllegalArgumentException { if (obj == null) { String message = name == null ? "object cannot be null" : name + " cannot be null!"; throw new IllegalArgumentException(message); } return obj; } public static String notEmtpy(String s) throws IllegalArgumentException { return notEmpty(s, null); } public static String notEmpty(String s, String name) throws IllegalArgumentException { if (s == null || s.isEmpty()) { String message = name == null ? "string cannot be empty" : (name + " cannot be empty string!"); throw new IllegalArgumentException(message); } return s; } public static <T> T[] notEmpty(T[] array) throws IllegalArgumentException { return notEmpty(array, null); } public static <T> T[] notEmpty(T[] array, String name) throws IllegalArgumentException { if (array == null || array.length == 0) { String message = name == null ? "array cannot be empty" : name + " cannot be empty array!"; throw new IllegalArgumentException(message); } return array; } public static <E> List<E> notEmpty(List<E> list, String name) throws IllegalArgumentException { if (list == null || list.isEmpty()) { String message = name == null ? "list cannot be empty" : (name + " list be empty collection!"); throw new IllegalArgumentException(message); } return list; } public static <E> List<E> notEmpty(List<E> list) throws IllegalArgumentException { return notEmpty(list, null); } public static <E> Collection<E> notEmpty(Collection<E> collection, String name) throws IllegalArgumentException { if (collection == null || collection.isEmpty()) { String message = name == null ? "collection cannot be empty" : (name + " cannot be empty collection!"); throw new IllegalArgumentException(message); } return collection; } public static <E> Collection<E> notEmpty(Collection<E> collection) throws IllegalArgumentException { return notEmpty(collection, null); } public static <K, V> Map<K, V> notEmpty(Map<K, V> map, String name) throws IllegalArgumentException { if (map == null || map.isEmpty()) { String message = name == null ? "map cannot be empty" : (name + " cannot be empty map!"); throw new IllegalArgumentException(message); } return map; } public static <K, V> Map<K, V> notEmpty(Map<K, V> map) throws IllegalArgumentException { return notEmpty(map, null); } public static <N extends Number> N greaterThanZero(N nr, String name) { if (nr.intValue() <= 0) { String message = "argument " + (name == null ? "number" : name) + " is not greater then 0"; throw new IllegalArgumentException(message); } return nr; } }
mit
wesleyjava2014/ProjetoAmostra
src/br/com/estudo/converter/LancamentoConverter.java
1084
package br.com.estudo.converter; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.convert.Converter; import javax.faces.convert.FacesConverter; import javax.inject.Inject; import br.com.estudo.dao.LancamentoRN; import br.com.estudo.modelo.Lancamento; @FacesConverter(forClass = Lancamento.class) public class LancamentoConverter implements Converter { @Inject private LancamentoRN lancamentoRn; @Override public Object getAsObject(FacesContext arg0, UIComponent arg1, String value) { // TODO Auto-generated method stub Lancamento retorno = null; if (value != null && !"".equals(value)) { retorno = this.lancamentoRn.porId(new Long(value)); } return retorno; } @Override public String getAsString(FacesContext arg0, UIComponent arg1, Object value) { // TODO Auto-generated method stub if (value != null) { Lancamento lancamento = ((Lancamento) value); return lancamento.getId() == null ? null : lancamento.getId() .toString(); } return null; } }
mit
dustin/spyjar
src/java/net/spy/db/DBTTL.java
821
// Copyright (c) 2001 Dustin Sallings <dustin@spy.net> package net.spy.db; import net.spy.util.TTL; /** * Used to track checked out DB connections to report on connections that * have been checked out longer than we expect them to be. */ public class DBTTL extends TTL { /** * Get an instance of DBTTL. */ public DBTTL(long ttl) { super(ttl); } /** * Get an instance of DBTTL with an extra object. */ public DBTTL(long ttl, Object extra) { super(ttl, extra); } /** * String me. */ @Override public String toString() { return("DBTTL: " + getTTL()); } /** * Report DB specific message. */ @Override protected void doReport() { // Get the message. String msg=getMessageFromBundle("net.spy.db.messages", "dbttl.msg", "dbttl.msg.witharg"); reportWithFormat(msg); } }
mit
jamhgit/pesc-transcript-jar
pesccoltrn/src/main/java/org/pesc/sector/academicrecord/v1_9/SchoolSupportServicesType.java
5366
// // 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.02.25 at 04:54:19 PM PST // package org.pesc.sector.academicrecord.v1_9; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; import org.pesc.core.coremain.v1_14.AdvancedPlacementCodeType; import org.pesc.core.coremain.v1_14.AdvancedSubjectCreditCodeType; import org.pesc.core.coremain.v1_14.SchoolServicesType; /** * Particular institutional services offered by an educational institution * * <p>Java class for SchoolSupportServicesType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="SchoolSupportServicesType"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="SchoolServices" type="{urn:org:pesc:core:CoreMain:v1.14.0}SchoolServicesType" maxOccurs="unbounded" minOccurs="0"/> * &lt;element name="AdvancedPlacementCode" type="{urn:org:pesc:core:CoreMain:v1.14.0}AdvancedPlacementCodeType" maxOccurs="unbounded" minOccurs="0"/> * &lt;element name="AdvancedSubjectCreditCode" type="{urn:org:pesc:core:CoreMain:v1.14.0}AdvancedSubjectCreditCodeType" maxOccurs="unbounded" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "SchoolSupportServicesType", propOrder = { "schoolServices", "advancedPlacementCode", "advancedSubjectCreditCode" }) public class SchoolSupportServicesType { @XmlElement(name = "SchoolServices") @XmlSchemaType(name = "string") protected List<SchoolServicesType> schoolServices; @XmlElement(name = "AdvancedPlacementCode") @XmlSchemaType(name = "string") protected List<AdvancedPlacementCodeType> advancedPlacementCode; @XmlElement(name = "AdvancedSubjectCreditCode") @XmlSchemaType(name = "string") protected List<AdvancedSubjectCreditCodeType> advancedSubjectCreditCode; /** * Gets the value of the schoolServices property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the schoolServices property. * * <p> * For example, to add a new item, do as follows: * <pre> * getSchoolServices().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link SchoolServicesType } * * */ public List<SchoolServicesType> getSchoolServices() { if (schoolServices == null) { schoolServices = new ArrayList<SchoolServicesType>(); } return this.schoolServices; } /** * Gets the value of the advancedPlacementCode property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the advancedPlacementCode property. * * <p> * For example, to add a new item, do as follows: * <pre> * getAdvancedPlacementCode().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link AdvancedPlacementCodeType } * * */ public List<AdvancedPlacementCodeType> getAdvancedPlacementCode() { if (advancedPlacementCode == null) { advancedPlacementCode = new ArrayList<AdvancedPlacementCodeType>(); } return this.advancedPlacementCode; } /** * Gets the value of the advancedSubjectCreditCode property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the advancedSubjectCreditCode property. * * <p> * For example, to add a new item, do as follows: * <pre> * getAdvancedSubjectCreditCode().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link AdvancedSubjectCreditCodeType } * * */ public List<AdvancedSubjectCreditCodeType> getAdvancedSubjectCreditCode() { if (advancedSubjectCreditCode == null) { advancedSubjectCreditCode = new ArrayList<AdvancedSubjectCreditCodeType>(); } return this.advancedSubjectCreditCode; } }
cc0-1.0
daniw/prg2-mep
CODE/Thread-singleton/src/stock/Stock.java
1562
package stock; public class Stock { private static final int size = 3; private String stock[] = new String[size]; private int in = 0; private int out = 0; private int n = 0; private static Stock theInstance; public Stock() { } public synchronized static Stock getInstance() { if (theInstance == null) theInstance = new Stock(); return theInstance; } public synchronized void enqueue(String value) { if (value == null) { return; } while (isFull()) { try { wait(); } catch (InterruptedException ie) { }; } n++; if (in == size) { in = 0; } stock[in] = value; System.out.println("enqueue:" + value); in++; notifyAll(); } public synchronized String dequeue() { while (isEmpty()) { try { wait(); } catch (InterruptedException ie) { }; } n--; if (out == size) { out = 0; } String v = stock[out]; out++; System.out.println("dequeue:" + v); notifyAll(); return v; } public synchronized boolean isEmpty() { return (n == 0); } public synchronized boolean isFull() { return (n == size); } }
cc0-1.0
alphadeltablue/Data-Structures
src/algorithm/SelectionSorter.java
2227
package algorithm; import java.util.ArrayList; /** * @author andrew * */ public class SelectionSorter extends Sorter { /** * Sorts an ArrayList. * * @param al ArrayList to be sorted */ public static <T extends Comparable<T>> void selectionSort(ArrayList<T> al) { int smallIndex; int pass; int j; int length = al.size(); T temp; for (pass = 0; pass < (length - 1); pass++) { smallIndex = pass; for (j = pass + 1; j < length; j++) { if (al.get(j).compareTo(al.get(smallIndex)) < 0) { smallIndex = j; } } temp = al.get(pass); al.set(pass, al.get(smallIndex)); al.set(smallIndex, temp); } } /** * Sorts an integer array. * * @param arr * Array to be sorted */ public static <T extends Comparable<? super T>> T[] selectionSort (T[] arr) { // Initializes variables used for sorting int smallIndex; // Index of the smallest number int pass; // Current sorting pass int j; // Index of smaller loop int length = arr.length; // Length of array T temp; // Loop. // The first pass finds the smallest, the second pass finds the second // smallest, etc. // Will not be affected by duplicates for (pass = 0; pass < (length - 1); pass++) { // Sets the index of the smallest to the current pass smallIndex = pass; // Finds the smallest element in the pass for (j = pass + 1; j < length; j++) { if (arr[j].compareTo(arr[smallIndex]) > 0) { smallIndex = j; } } // Switches the nth smallest number with the nth number temp = arr[pass]; arr[pass] = arr[smallIndex]; arr[smallIndex] = temp; } // Returns the array return arr; } public static void selectionSort(int[] arr) { int smallIndex; int pass; int j; int length = arr.length; int temp; for (pass = 0; pass < (length - 1); pass++) { smallIndex = pass; for (j = pass + 1; j < length; j++) { if (arr[j] < arr[smallIndex]) { smallIndex = j; } } temp = arr[pass]; arr[pass] = arr[smallIndex]; arr[smallIndex] = temp; } } @Override public <T extends Comparable<T>> void sort(ArrayList<T> al) { selectionSort(al); } }
cc0-1.0
iCONEXT/SMI_Travel
src/java/com/smi/travel/masterdata/controller/MGalileoController.java
2831
package com.smi.travel.masterdata.controller; import com.smi.travel.controller.LoginController; import com.smi.travel.datalayer.entity.MGalileo; import com.smi.travel.datalayer.service.MGalileoService; import com.smi.travel.master.controller.SMITravelController; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.log4j.Logger; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.view.RedirectView; public class MGalileoController extends SMITravelController { private static final Logger log = Logger.getLogger(LoginController.class.getName()); private static final ModelAndView Galileo = new ModelAndView("MGalileo"); private static final ModelAndView Galileo_REFRESH = new ModelAndView(new RedirectView("MGalileo.smi", true)); private static final String DataList = "Galileo_List"; private static final String DataLap = "staffLap"; private static final String TransactionResult = "result"; private MGalileoService mGalileoService; @Override protected ModelAndView process(HttpServletRequest request, HttpServletResponse response, HttpSession session) { String action = request.getParameter("action"); int result = 0; if ("update".equalsIgnoreCase(action)) { log.info("this here edit function"); String id = request.getParameter("GID"); String name = request.getParameter("Name"); String section = request.getParameter("Section"); String line = request.getParameter("Line"); String length = request.getParameter("Length"); String startLength = request.getParameter("StartLength"); MGalileo mGali = new MGalileo(); mGali.setId(id); mGali.setName(name); mGali.setSection(section); mGali.setLine(line); mGali.setLength(Integer.parseInt(length)); mGali.setStartlength(Integer.parseInt(startLength)); result = mGalileoService.EditGalileo(mGali); if (result == 1) { request.setAttribute(TransactionResult, "save successful"); } else { request.setAttribute(TransactionResult, "save unsuccessful"); } } List<MGalileo> listGalileo = mGalileoService.getGalileoList(); request.setAttribute(DataList, listGalileo); return Galileo; } public void loadcritite() { } public void saveCritite() { } public MGalileoService getmGalileoService() { return mGalileoService; } public void setmGalileoService(MGalileoService mGalileoService) { this.mGalileoService = mGalileoService; } }
cc0-1.0
lxil/easyhomework
easyhomework/src/com/homework/auth/util/MD5Oper.java
1026
package com.homework.auth.util; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class MD5Oper { private String str = null; public String getResult(){ return str; } public static String md5_encode(String plainText) { String result = null; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(plainText.getBytes()); byte b[] = md.digest(); int i; StringBuffer buf = new StringBuffer(""); for (int offset = 0; offset < b.length; offset++) { i = b[offset]; if (i < 0) i += 256; if (i < 16) buf.append("0"); buf.append(Integer.toHexString(i)); } result = buf.toString(); //System.out.println("result: " + buf.toString());// 32位的加密 //System.out.println("result: " + buf.toString().substring(8, 24));// 16位的加密 } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } return result; } }
epl-1.0
lbeurerkellner/n4js
plugins/org.eclipse.n4js.ui/src/org/eclipse/n4js/ui/proposals/imports/ImportRewriter.java
12976
/** * Copyright (c) 2016 NumberFour AG. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * NumberFour AG - Initial API and implementation */ package org.eclipse.n4js.ui.proposals.imports; import static org.eclipse.n4js.parser.InternalSemicolonInjectingParser.SEMICOLON_INSERTED; import static org.eclipse.n4js.utils.UtilN4.isIgnoredSyntaxErrorNode; import java.io.IOException; import java.util.List; import java.util.Set; import org.eclipse.emf.ecore.resource.Resource; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IDocumentExtension4; import org.eclipse.n4js.n4JS.ImportDeclaration; import org.eclipse.n4js.n4JS.N4JSFactory; import org.eclipse.n4js.n4JS.NamedImportSpecifier; import org.eclipse.n4js.n4JS.Script; import org.eclipse.n4js.n4JS.ScriptElement; import org.eclipse.n4js.resource.AccessibleSerializer; import org.eclipse.n4js.services.N4JSGrammarAccess; import org.eclipse.n4js.ts.types.TExportableElement; import org.eclipse.n4js.ui.organize.imports.ImportsRegionHelper; import org.eclipse.n4js.ui.utils.ImportSpacerUserPreferenceHelper; import org.eclipse.n4js.utils.Lazy; import org.eclipse.n4js.utils.N4JSLanguageUtils; import org.eclipse.text.edits.InsertEdit; import org.eclipse.text.edits.MultiTextEdit; import org.eclipse.text.edits.ReplaceEdit; import org.eclipse.xtext.conversion.IValueConverterService; import org.eclipse.xtext.naming.IQualifiedNameConverter; import org.eclipse.xtext.naming.QualifiedName; import org.eclipse.xtext.nodemodel.ICompositeNode; import org.eclipse.xtext.nodemodel.ILeafNode; import org.eclipse.xtext.nodemodel.INode; import org.eclipse.xtext.nodemodel.impl.LeafNodeWithSyntaxError; import org.eclipse.xtext.nodemodel.util.NodeModelUtils; import org.eclipse.xtext.resource.SaveOptions; import org.eclipse.xtext.util.Strings; import org.eclipse.xtext.util.concurrent.IUnitOfWork; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.google.inject.Inject; import com.google.inject.MembersInjector; /** * Obtain an import rewriter for a resource and add used types optionally along with aliases. It uses the serializer to * rewrite the import declarations. * * Instances of the {@link ImportRewriter} are obtained from the {@link ImportRewriter.Factory}. * * TODO: review if that is stable enough, e.g. with broken import declarations. */ public class ImportRewriter { /** * The factory provides a readily configured {@link ImportRewriter}. It is parameterized with a document and a * resource. It is assumed that the resource belongs to the given document and was properly guarded by a * {@link IUnitOfWork}. */ public static class Factory { @Inject private MembersInjector<ImportRewriter> injector; /** * Creates a new import rewriter. */ public ImportRewriter create(IDocument document, Resource resource) { ImportRewriter result = new ImportRewriter(document, resource); injector.injectMembers(result); return result; } } @Inject private IQualifiedNameConverter qualifiedNameConverter; @Inject private IValueConverterService valueConverters; @Inject private N4JSGrammarAccess grammarAccess; @Inject private AccessibleSerializer serializer; @Inject private ImportSpacerUserPreferenceHelper spacerPreference; @Inject private ImportsRegionHelper importsRegionHelper; private final String lineDelimiter; private final Script script; private final Set<NameAndAlias> requestedImports; private final List<ImportDeclaration> existingImports; private final Lazy<String> lazySpacer; private ImportRewriter(IDocument document, Resource resource) { if (document instanceof IDocumentExtension4) { lineDelimiter = ((IDocumentExtension4) document).getDefaultLineDelimiter(); } else { lineDelimiter = Strings.newLine(); } this.script = (Script) resource.getContents().get(0); this.existingImports = Lists.newArrayList(); for (ScriptElement element : script.getScriptElements()) { if (element instanceof ImportDeclaration) existingImports.add((ImportDeclaration) element); } this.requestedImports = Sets.newLinkedHashSet(); this.lazySpacer = new Lazy<>(() -> spacerPreference.getSpacingPreference(resource)); } /** * @param qualifiedName * the name of the thing to import */ public void addImport(QualifiedName qualifiedName) { requestedImports.add(new NameAndAlias(qualifiedName, null)); } /** * @param qualifiedName * the fqn of the thing to import * @param alias * the alias to use, may be null. */ public void addImport(QualifiedName qualifiedName, String alias) { requestedImports.add(new NameAndAlias(qualifiedName, alias)); } /** * @param qualifiedName * the name of the thing to import */ public void addSingleImport(QualifiedName qualifiedName, MultiTextEdit result) { toTextEdit(qualifiedName, null, findInsertionOffset(), result); } /** * @param qualifiedName * the FQN of the thing to import * @param alias * the alias to use, may be null. * @return the location of the alias in the final field */ public AliasLocation addSingleImport(QualifiedName qualifiedName, String alias, MultiTextEdit result) { return toTextEdit(qualifiedName, alias, findInsertionOffset(), result); } /** * @param result * the accumulator for the changes */ public void toTextEdits(MultiTextEdit result) { int insertionOffset = findInsertionOffset(); for (NameAndAlias requested : requestedImports) { toTextEdit(requested.getName(), requested.getAlias(), insertionOffset, result); } } /** * Add the necessary text edits to the accumulating result. Optionally return the offset of the alias. */ private AliasLocation toTextEdit(QualifiedName qualifiedName, String optionalAlias, int insertionOffset, MultiTextEdit result) { QualifiedName moduleName = qualifiedName.skipLast(1); // the following code for enhancing existing ImportDeclarations makes use of the Xtext serializer, which is not // yet compatible with fragments in Xtext grammars (as of Xtext 2.9.1) -> deactivated for now // @formatter:off // String moduleNameAsString = unquoted(syntacticModuleName(moduleName)); // for (ImportDeclaration existing : existingImports) { // String importedModuleName = existing.getModule().getQualifiedName(); // if (moduleNameAsString.equals(importedModuleName)) { // return enhanceExistingImportDeclaration(existing, qualifiedName, optionalAlias, result); // } // } // @formatter:on return addNewImportDeclaration(moduleName, qualifiedName, optionalAlias, insertionOffset, result); } /** */ @SuppressWarnings("unused") private String unquoted(String syntacticModuleName) { if (syntacticModuleName == null || syntacticModuleName.length() < 2) return syntacticModuleName; if (syntacticModuleName.charAt(0) == '"' && syntacticModuleName.charAt(syntacticModuleName.length() - 1) == '"') return syntacticModuleName.substring(1, syntacticModuleName.length() - 1); return syntacticModuleName; } private AliasLocation addNewImportDeclaration(QualifiedName moduleName, QualifiedName qualifiedName, String optionalAlias, int insertionOffset, MultiTextEdit result) { final String spacer = lazySpacer.get(); String syntacticModuleName = syntacticModuleName(moduleName); AliasLocation aliasLocation = null; String importSpec = (insertionOffset != 0 ? lineDelimiter : "") + "import "; if (!N4JSLanguageUtils.isDefaultExport(qualifiedName)) { // not an 'default' export importSpec = importSpec + "{" + spacer + qualifiedName.getLastSegment(); if (optionalAlias != null) { importSpec = importSpec + " as "; aliasLocation = new AliasLocation(insertionOffset, importSpec.length(), optionalAlias); importSpec = importSpec + optionalAlias; } importSpec = importSpec + spacer + "}"; } else { // import default exported element if (optionalAlias == null) { importSpec = importSpec + N4JSLanguageUtils.lastSegmentOrDefaultHost(qualifiedName); } else { aliasLocation = new AliasLocation(insertionOffset, importSpec.length(), optionalAlias); importSpec = importSpec + optionalAlias; } } result.addChild(new InsertEdit(insertionOffset, importSpec + " from " + syntacticModuleName + ";" + (insertionOffset != 0 ? "" : lineDelimiter))); return aliasLocation; } /** compute the syntactic string representation of the moduleName */ private String syntacticModuleName(QualifiedName moduleName) { String syntacticModuleName = valueConverters.toString( qualifiedNameConverter.toString(moduleName), grammarAccess.getModuleSpecifierRule().getName()); return syntacticModuleName; } @SuppressWarnings({ "unused", "deprecation" }) private AliasLocation enhanceExistingImportDeclaration(ImportDeclaration importDeclaration, QualifiedName qualifiedName, String optionalAlias, MultiTextEdit result) { addImportSpecifier(importDeclaration, qualifiedName, optionalAlias); ICompositeNode replaceMe = NodeModelUtils.getNode(importDeclaration); int offset = replaceMe.getOffset(); AliasLocationAwareBuffer observableBuffer = new AliasLocationAwareBuffer( optionalAlias, offset, grammarAccess); try { serializer.serialize( importDeclaration, observableBuffer, SaveOptions.newBuilder().noValidation().getOptions()); } catch (IOException e) { throw new RuntimeException("Should never happen since we write into memory", e); } result.addChild(new ReplaceEdit(offset, replaceMe.getLength(), observableBuffer.toString())); return observableBuffer.getAliasLocation(); } private void addImportSpecifier(ImportDeclaration importDeclaration, QualifiedName qualifiedName, String optionalAlias) { boolean isDefaultExport = N4JSLanguageUtils.isDefaultExport(qualifiedName); NamedImportSpecifier specifier = null; specifier = isDefaultExport ? N4JSFactory.eINSTANCE.createDefaultImportSpecifier() : N4JSFactory.eINSTANCE.createNamedImportSpecifier(); // not only types, but also variables ... Iterable<TExportableElement> topLevelTypes = Iterables.concat( importDeclaration.getModule().getTopLevelTypes(), importDeclaration.getModule().getVariables()); for (TExportableElement t : topLevelTypes) { if (t.getExportedName().equals(qualifiedName.getLastSegment())) { specifier.setImportedElement(t); specifier.setAlias(optionalAlias); if (optionalAlias == null && isDefaultExport) { specifier.setAlias(qualifiedName.getSegment(qualifiedName.getSegmentCount() - 2)); // set to // module-name } break; } } if (isDefaultExport) importDeclaration.getImportSpecifiers().add(0, specifier); // to Front else importDeclaration.getImportSpecifiers().add(specifier); } private int findInsertionOffset() { int result = 0; List<ScriptElement> scriptElements = script.getScriptElements(); for (int i = 0, size = scriptElements.size(); i < size; i++) { ScriptElement element = scriptElements.get(i); if (element instanceof ImportDeclaration) { // Instead of getting the total offset for the first non-import-declaration, we try to get the // total end offset for the most recent import declaration which is followed by any other script element // this is required for the linebreak handling for automatic semicolon insertion. final ICompositeNode importNode = NodeModelUtils.findActualNodeFor(element); if (null != importNode) { result = importNode.getTotalOffset() + getLengthWithoutAutomaticSemicolon(importNode); } } else { // We assume that all import declarations are to be found in one place, thus // at this point we must have seen all of them. break; } } // If previously, an existing import declaration could be found, use it as offset. if (result != 0) { return result; } // Otherwise, we assume there is no import declarations yet. Use {@link ImportsRegionHelper} // to obtain an offset for the insertion of a new import declaration. return importsRegionHelper.getImportOffset(script); } /** * Returns with the length of the node including all hidden leaf nodes but the {@link LeafNodeWithSyntaxError} one, * that was created for the automatic semicolon insertion. */ private int getLengthWithoutAutomaticSemicolon(final INode node) { if (node instanceof ILeafNode) { return node.getLength(); } int length = 0; for (final INode leafNode : ((ICompositeNode) node).getLeafNodes()) { if (!isIgnoredSyntaxErrorNode(leafNode, SEMICOLON_INSERTED)) { length += leafNode.getLength(); } } return length; } }
epl-1.0
Snickermicker/openhab2
bundles/org.openhab.binding.onkyo/src/main/java/org/openhab/binding/onkyo/internal/handler/UpnpAudioSinkHandler.java
7553
/** * Copyright (c) 2010-2019 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.onkyo.internal.handler; import java.util.HashMap; import java.util.HashSet; import java.util.Locale; import java.util.Map; import java.util.Set; import org.eclipse.jdt.annotation.Nullable; import org.eclipse.smarthome.core.audio.AudioFormat; import org.eclipse.smarthome.core.audio.AudioHTTPServer; import org.eclipse.smarthome.core.audio.AudioSink; import org.eclipse.smarthome.core.audio.AudioStream; import org.eclipse.smarthome.core.audio.FixedLengthAudioStream; import org.eclipse.smarthome.core.audio.URLAudioStream; import org.eclipse.smarthome.core.audio.UnsupportedAudioFormatException; import org.eclipse.smarthome.core.audio.UnsupportedAudioStreamException; import org.eclipse.smarthome.core.library.types.StringType; import org.eclipse.smarthome.core.thing.Thing; import org.eclipse.smarthome.core.thing.binding.BaseThingHandler; import org.eclipse.smarthome.core.types.Command; import org.eclipse.smarthome.io.transport.upnp.UpnpIOParticipant; import org.eclipse.smarthome.io.transport.upnp.UpnpIOService; import org.openhab.binding.onkyo.internal.OnkyoBindingConstants; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * The {@link UpnpAudioSinkHandler} is a base class for ThingHandlers for devices which support UPnP playback. It * implements the AudioSink interface. * This will allow to register the derived ThingHandler to be registered as a AudioSink in the framework. * * @author Paul Frank - Initial contribution */ public abstract class UpnpAudioSinkHandler extends BaseThingHandler implements AudioSink, UpnpIOParticipant { private static final Set<AudioFormat> SUPPORTED_FORMATS = new HashSet<>(); private static final Set<Class<? extends AudioStream>> SUPPORTED_STREAMS = new HashSet<>(); static { SUPPORTED_FORMATS.add(AudioFormat.WAV); SUPPORTED_FORMATS.add(AudioFormat.MP3); SUPPORTED_STREAMS.add(AudioStream.class); } private final Logger logger = LoggerFactory.getLogger(getClass()); private AudioHTTPServer audioHTTPServer; private String callbackUrl; private UpnpIOService service; public UpnpAudioSinkHandler(Thing thing, UpnpIOService upnpIOService, AudioHTTPServer audioHTTPServer, String callbackUrl) { super(thing); this.audioHTTPServer = audioHTTPServer; this.callbackUrl = callbackUrl; if (upnpIOService != null) { this.service = upnpIOService; } } protected void handlePlayUri(Command command) { if (command != null && command instanceof StringType) { try { playMedia(command.toString()); } catch (IllegalStateException e) { logger.warn("Cannot play URI ({})", e.getMessage()); } } } private void playMedia(String url) { stop(); removeAllTracksFromQueue(); if (!url.startsWith("x-") && (!url.startsWith("http"))) { url = "x-file-cifs:" + url; } setCurrentURI(url, ""); play(); } @Override public Set<AudioFormat> getSupportedFormats() { return SUPPORTED_FORMATS; } @Override public Set<Class<? extends AudioStream>> getSupportedStreams() { return SUPPORTED_STREAMS; } private void stop() { Map<String, String> inputs = new HashMap<>(); inputs.put("InstanceID", "0"); Map<String, String> result = service.invokeAction(this, "AVTransport", "Stop", inputs); for (String variable : result.keySet()) { this.onValueReceived(variable, result.get(variable), "AVTransport"); } } private void play() { Map<String, String> inputs = new HashMap<>(); inputs.put("InstanceID", "0"); inputs.put("Speed", "1"); Map<String, String> result = service.invokeAction(this, "AVTransport", "Play", inputs); for (String variable : result.keySet()) { this.onValueReceived(variable, result.get(variable), "AVTransport"); } } private void removeAllTracksFromQueue() { Map<String, String> inputs = new HashMap<>(); inputs.put("InstanceID", "0"); Map<String, String> result = service.invokeAction(this, "AVTransport", "RemoveAllTracksFromQueue", inputs); for (String variable : result.keySet()) { this.onValueReceived(variable, result.get(variable), "AVTransport"); } } private void setCurrentURI(String uri, String uriMetaData) { if (uri != null && uriMetaData != null) { Map<String, String> inputs = new HashMap<>(); try { inputs.put("InstanceID", "0"); inputs.put("CurrentURI", uri); inputs.put("CurrentURIMetaData", uriMetaData); } catch (NumberFormatException ex) { logger.error("Action Invalid Value Format Exception {}", ex.getMessage()); } Map<String, String> result = service.invokeAction(this, "AVTransport", "SetAVTransportURI", inputs); for (String variable : result.keySet()) { this.onValueReceived(variable, result.get(variable), "AVTransport"); } } } @Override public String getId() { return getThing().getUID().toString(); } @Override public String getLabel(Locale locale) { return getThing().getLabel(); } @Override public void process(@Nullable AudioStream audioStream) throws UnsupportedAudioFormatException, UnsupportedAudioStreamException { if (audioStream == null) { stop(); return; } String url = null; if (audioStream instanceof URLAudioStream) { // it is an external URL, the speaker can access it itself and play it. URLAudioStream urlAudioStream = (URLAudioStream) audioStream; url = urlAudioStream.getURL(); } else { if (callbackUrl != null) { String relativeUrl; if (audioStream instanceof FixedLengthAudioStream) { // we serve it on our own HTTP server relativeUrl = audioHTTPServer.serve((FixedLengthAudioStream) audioStream, 20); } else { relativeUrl = audioHTTPServer.serve(audioStream); } url = callbackUrl + relativeUrl; } else { logger.warn("We do not have any callback url, so onkyo cannot play the audio stream!"); return; } } playMedia(url); } @Override public String getUDN() { return (String) this.getConfig().get(OnkyoBindingConstants.UDN_PARAMETER); } @Override public void onValueReceived(String variable, String value, String service) { logger.debug("received variable {} with value {} from service {}", variable, value, service); } @Override public void onServiceSubscribed(String service, boolean succeeded) { } @Override public void onStatusChanged(boolean status) { } }
epl-1.0
alovassy/titan.EclipsePlug-ins
org.eclipse.titan.designer/src/org/eclipse/titan/designer/properties/pages/FolderNamingConventionPropertyPage.java
5488
/****************************************************************************** * Copyright (c) 2000-2015 Ericsson Telecom AB * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html ******************************************************************************/ package org.eclipse.titan.designer.properties.pages; import java.io.IOException; import org.eclipse.core.resources.IFolder; import org.eclipse.core.resources.IProject; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.preference.BooleanFieldEditor; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.util.IPropertyChangeListener; import org.eclipse.jface.util.PropertyChangeEvent; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.titan.common.logging.ErrorReporter; import org.eclipse.titan.designer.AST.NamingConventionHelper; import org.eclipse.titan.designer.preferences.PreferenceConstants; import org.eclipse.titan.designer.properties.PropertyNotificationManager; import org.eclipse.titan.designer.properties.data.FolderNamingConventionPropertyData; import org.eclipse.titan.designer.properties.data.ProjectDocumentHandlingUtility; import org.eclipse.titan.designer.wizards.projectFormat.TITANAutomaticProjectExporter; /** * @author Kristof Szabados * */ public class FolderNamingConventionPropertyPage extends BaseNamingConventionPropertyPage { private static final String DESCRIPTION = "Folder specific naming convention related preferences of the on-the-fly checker.\n" + "All options use Java regular expressions."; private static final String ENABLEFOLDERSPECIFIC = "Enable folder specific settings"; private ConfigurationManagerControl configurationManager; private String firstConfiguration; public FolderNamingConventionPropertyPage() { super(GRID); setDescription(DESCRIPTION); } @Override protected String getPageId() { return FolderNamingConventionPropertyData.QUALIFIER; } /** * Handles the change of the active configuration. Sets the new * configuration to be the active one, and loads its settings. * * @param configuration * the name of the new configuration. * */ public void changeConfiguration(final String configuration) { configurationManager.changeActualConfiguration(); resetPreferenceStore(); initialize(); PropertyNotificationManager.firePropertyChange((IFolder) getElement()); } @Override protected void createFieldEditors() { final Composite tempParent = getFieldEditorParent(); IFolder folder = (IFolder) getElement(); configurationManager = new ConfigurationManagerControl(tempParent, folder.getProject()); configurationManager.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(final SelectionEvent e) { if (configurationManager.hasConfigurationChanged()) { changeConfiguration(configurationManager.getActualSelection()); } } }); firstConfiguration = configurationManager.getActualSelection(); BooleanFieldEditor booleanedit = new BooleanFieldEditor(PreferenceConstants.ENABLEFOLDERSPECIFICNAMINGCONVENTIONS, ENABLEFOLDERSPECIFIC, tempParent); booleanedit.setPropertyChangeListener(new IPropertyChangeListener() { @Override public void propertyChange(final PropertyChangeEvent event) { setChanged(true); } }); addField(booleanedit); createNamingConventionBody(tempParent); } @Override public void setVisible(final boolean visible) { if (!visible) { return; } if (configurationManager != null) { configurationManager.refresh(); } super.setVisible(visible); } @Override protected void performDefaults() { super.performDefaults(); configurationManager.saveActualConfiguration(); } @Override public boolean performCancel() { configurationManager.clearActualConfiguration(); resetPreferenceStore(); initialize(); return super.performCancel(); } @Override public boolean performOk() { IFolder folder = (IFolder) getElement(); boolean result = super.performOk(); IPreferenceStore store = getPreferenceStore(); if (store instanceof PropertyStore) { try { ((PropertyStore) store).save(); } catch (IOException e) { ErrorReporter.logExceptionStackTrace(e); } } IProject project = folder.getProject(); configurationManager.saveActualConfiguration(); ProjectDocumentHandlingUtility.saveDocument(project); TITANAutomaticProjectExporter.saveAllAutomatically(project); final boolean configurationChanged = !firstConfiguration.equals(configurationManager.getActualSelection()); if (configurationChanged || (getChanged() && getPreferenceStore().getBoolean(PreferenceConstants.USEONTHEFLYPARSING))) { setChanged(false); Display.getDefault().syncExec(new Runnable() { @Override public void run() { MessageDialog.openWarning(null, "Naming convention settings changed", "Naming convention settings have changed, the known projects have to be re-analyzed completly.\nThis might take some time."); } }); NamingConventionHelper.clearCaches(); PropertyNotificationManager.firePropertyChange(project); } return result; } }
epl-1.0
bfg-repo-cleaner-demos/eclipselink.runtime-bfg-strip-big-blobs
utils/eclipselink.utils.workbench/mappingsplugin/source/org/eclipse/persistence/tools/workbench/mappingsplugin/ui/mapping/relational/VariableOneToOneMappingNode.java
2102
/******************************************************************************* * Copyright (c) 1998, 2012 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * Oracle - initial API and implementation from Oracle TopLink ******************************************************************************/ package org.eclipse.persistence.tools.workbench.mappingsplugin.ui.mapping.relational; import org.eclipse.persistence.tools.workbench.framework.app.SelectionActionsPolicy; import org.eclipse.persistence.tools.workbench.mappingsmodel.mapping.relational.MWVariableOneToOneMapping; import org.eclipse.persistence.tools.workbench.mappingsplugin.ui.descriptor.MappingDescriptorNode; import org.eclipse.persistence.tools.workbench.mappingsplugin.ui.mapping.MappingNode; public final class VariableOneToOneMappingNode extends MappingNode { public VariableOneToOneMappingNode(MWVariableOneToOneMapping value, SelectionActionsPolicy mappingNodeTypePolicy, MappingDescriptorNode parent) { super(value, mappingNodeTypePolicy, parent); } // ************** AbstractApplicationNode overrides ************* protected String accessibleNameKey() { return "ACCESSIBLE_TRANSFORMATION_MAPPING_NODE"; } // ************** ApplicationNode implementation ************* public String helpTopicID() { return "mapping.variableOneToOne"; } protected String buildIconKey() { return this.getDescriptorNode().mappingHelpTopicPrefix() + ".variableOneToOne"; } // ********** MWApplicationNode overrides ********** protected Class propertiesPageClass() { return VariableOneToOneMappingTabbedPropertiesPage.class; } }
epl-1.0
uppaal-emf/uppaal
metamodel/org.muml.uppaal.edit/src/org/muml/uppaal/declarations/provider/ValueIndexItemProvider.java
7229
/** */ package org.muml.uppaal.declarations.provider; import java.util.Collection; import java.util.List; import org.eclipse.emf.common.notify.AdapterFactory; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.ecore.EStructuralFeature; import org.eclipse.emf.edit.provider.IItemPropertyDescriptor; import org.eclipse.emf.edit.provider.ViewerNotification; import org.muml.uppaal.declarations.DeclarationsPackage; import org.muml.uppaal.declarations.ValueIndex; import org.muml.uppaal.expressions.ExpressionsFactory; /** * This is the item provider adapter for a {@link org.muml.uppaal.declarations.ValueIndex} object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public class ValueIndexItemProvider extends IndexItemProvider { /** * This constructs an instance from a factory and a notifier. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public ValueIndexItemProvider(AdapterFactory adapterFactory) { super(adapterFactory); } /** * This returns the property descriptors for the adapted class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public List<IItemPropertyDescriptor> getPropertyDescriptors(Object object) { if (itemPropertyDescriptors == null) { super.getPropertyDescriptors(object); } return itemPropertyDescriptors; } /** * This specifies how to implement {@link #getChildren} and is used to deduce an appropriate feature for an * {@link org.eclipse.emf.edit.command.AddCommand}, {@link org.eclipse.emf.edit.command.RemoveCommand} or * {@link org.eclipse.emf.edit.command.MoveCommand} in {@link #createCommand}. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Collection<? extends EStructuralFeature> getChildrenFeatures(Object object) { if (childrenFeatures == null) { super.getChildrenFeatures(object); childrenFeatures.add(DeclarationsPackage.Literals.VALUE_INDEX__SIZE_EXPRESSION); } return childrenFeatures; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EStructuralFeature getChildFeature(Object object, Object child) { // Check the type of the specified child object and return the proper feature to use for // adding (see {@link AddCommand}) it as a child. return super.getChildFeature(object, child); } /** * This returns ValueIndex.gif. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object getImage(Object object) { return overlayImage(object, getResourceLocator().getImage("full/obj16/ValueIndex")); } /** * This returns the label text for the adapted class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String getText(Object object) { return getString("_UI_ValueIndex_type"); } /** * This handles model notifications by calling {@link #updateChildren} to update any cached * children and by creating a viewer notification, which it passes to {@link #fireNotifyChanged}. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void notifyChanged(Notification notification) { updateChildren(notification); switch (notification.getFeatureID(ValueIndex.class)) { case DeclarationsPackage.VALUE_INDEX__SIZE_EXPRESSION: fireNotifyChanged(new ViewerNotification(notification, notification.getNotifier(), true, false)); return; } super.notifyChanged(notification); } /** * This adds {@link org.eclipse.emf.edit.command.CommandParameter}s describing the children * that can be created under this object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected void collectNewChildDescriptors(Collection<Object> newChildDescriptors, Object object) { super.collectNewChildDescriptors(newChildDescriptors, object); newChildDescriptors.add (createChildParameter (DeclarationsPackage.Literals.VALUE_INDEX__SIZE_EXPRESSION, ExpressionsFactory.eINSTANCE.createNegationExpression())); newChildDescriptors.add (createChildParameter (DeclarationsPackage.Literals.VALUE_INDEX__SIZE_EXPRESSION, ExpressionsFactory.eINSTANCE.createPlusExpression())); newChildDescriptors.add (createChildParameter (DeclarationsPackage.Literals.VALUE_INDEX__SIZE_EXPRESSION, ExpressionsFactory.eINSTANCE.createMinusExpression())); newChildDescriptors.add (createChildParameter (DeclarationsPackage.Literals.VALUE_INDEX__SIZE_EXPRESSION, ExpressionsFactory.eINSTANCE.createAssignmentExpression())); newChildDescriptors.add (createChildParameter (DeclarationsPackage.Literals.VALUE_INDEX__SIZE_EXPRESSION, ExpressionsFactory.eINSTANCE.createIdentifierExpression())); newChildDescriptors.add (createChildParameter (DeclarationsPackage.Literals.VALUE_INDEX__SIZE_EXPRESSION, ExpressionsFactory.eINSTANCE.createLiteralExpression())); newChildDescriptors.add (createChildParameter (DeclarationsPackage.Literals.VALUE_INDEX__SIZE_EXPRESSION, ExpressionsFactory.eINSTANCE.createArithmeticExpression())); newChildDescriptors.add (createChildParameter (DeclarationsPackage.Literals.VALUE_INDEX__SIZE_EXPRESSION, ExpressionsFactory.eINSTANCE.createLogicalExpression())); newChildDescriptors.add (createChildParameter (DeclarationsPackage.Literals.VALUE_INDEX__SIZE_EXPRESSION, ExpressionsFactory.eINSTANCE.createFunctionCallExpression())); newChildDescriptors.add (createChildParameter (DeclarationsPackage.Literals.VALUE_INDEX__SIZE_EXPRESSION, ExpressionsFactory.eINSTANCE.createCompareExpression())); newChildDescriptors.add (createChildParameter (DeclarationsPackage.Literals.VALUE_INDEX__SIZE_EXPRESSION, ExpressionsFactory.eINSTANCE.createConditionExpression())); newChildDescriptors.add (createChildParameter (DeclarationsPackage.Literals.VALUE_INDEX__SIZE_EXPRESSION, ExpressionsFactory.eINSTANCE.createScopedIdentifierExpression())); newChildDescriptors.add (createChildParameter (DeclarationsPackage.Literals.VALUE_INDEX__SIZE_EXPRESSION, ExpressionsFactory.eINSTANCE.createQuantificationExpression())); newChildDescriptors.add (createChildParameter (DeclarationsPackage.Literals.VALUE_INDEX__SIZE_EXPRESSION, ExpressionsFactory.eINSTANCE.createIncrementDecrementExpression())); newChildDescriptors.add (createChildParameter (DeclarationsPackage.Literals.VALUE_INDEX__SIZE_EXPRESSION, ExpressionsFactory.eINSTANCE.createBitShiftExpression())); newChildDescriptors.add (createChildParameter (DeclarationsPackage.Literals.VALUE_INDEX__SIZE_EXPRESSION, ExpressionsFactory.eINSTANCE.createMinMaxExpression())); newChildDescriptors.add (createChildParameter (DeclarationsPackage.Literals.VALUE_INDEX__SIZE_EXPRESSION, ExpressionsFactory.eINSTANCE.createBitwiseExpression())); } }
epl-1.0
occiware/Multi-Cloud-Studio
plugins/org.eclipse.cmf.occi.multicloud.aws.ec2.edit/src-gen/org/eclipse/cmf/occi/multicloud/aws/ec2/provider/D2_8xlargeItemProvider.java
7019
/** * Copyright (c) 2015-2017 Obeo, Inria * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * - William Piers <william.piers@obeo.fr> * - Philippe Merle <philippe.merle@inria.fr> * - Faiez Zalila <faiez.zalila@inria.fr> */ package org.eclipse.cmf.occi.multicloud.aws.ec2.provider; import java.util.Collection; import java.util.List; import org.eclipse.cmf.occi.multicloud.aws.ec2.D2_8xlarge; import org.eclipse.cmf.occi.multicloud.aws.ec2.Ec2Package; import org.eclipse.emf.common.notify.AdapterFactory; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.edit.provider.ComposeableAdapterFactory; import org.eclipse.emf.edit.provider.IItemPropertyDescriptor; import org.eclipse.emf.edit.provider.ItemPropertyDescriptor; import org.eclipse.emf.edit.provider.ViewerNotification; /** * This is the item provider adapter for a {@link org.eclipse.cmf.occi.multicloud.aws.ec2.D2_8xlarge} object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public class D2_8xlargeItemProvider extends StorageoptimizedItemProvider { /** * This constructs an instance from a factory and a notifier. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public D2_8xlargeItemProvider(AdapterFactory adapterFactory) { super(adapterFactory); } /** * This returns the property descriptors for the adapted class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public List<IItemPropertyDescriptor> getPropertyDescriptors(Object object) { if (itemPropertyDescriptors == null) { super.getPropertyDescriptors(object); addOcciComputeMemoryPropertyDescriptor(object); addInstanceTypePropertyDescriptor(object); addOcciComputeCoresPropertyDescriptor(object); addOcciComputeEphemeralStorageSizePropertyDescriptor(object); } return itemPropertyDescriptors; } /** * This adds a property descriptor for the Occi Compute Memory feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected void addOcciComputeMemoryPropertyDescriptor(Object object) { itemPropertyDescriptors.add (createItemPropertyDescriptor (((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(), getResourceLocator(), getString("_UI_D2_8xlarge_occiComputeMemory_feature"), getString("_UI_PropertyDescriptor_description", "_UI_D2_8xlarge_occiComputeMemory_feature", "_UI_D2_8xlarge_type"), Ec2Package.eINSTANCE.getD2_8xlarge_OcciComputeMemory(), true, false, false, ItemPropertyDescriptor.GENERIC_VALUE_IMAGE, null, null)); } /** * This adds a property descriptor for the Instance Type feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected void addInstanceTypePropertyDescriptor(Object object) { itemPropertyDescriptors.add (createItemPropertyDescriptor (((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(), getResourceLocator(), getString("_UI_D2_8xlarge_instanceType_feature"), getString("_UI_PropertyDescriptor_description", "_UI_D2_8xlarge_instanceType_feature", "_UI_D2_8xlarge_type"), Ec2Package.eINSTANCE.getD2_8xlarge_InstanceType(), true, false, false, ItemPropertyDescriptor.GENERIC_VALUE_IMAGE, null, null)); } /** * This adds a property descriptor for the Occi Compute Cores feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected void addOcciComputeCoresPropertyDescriptor(Object object) { itemPropertyDescriptors.add (createItemPropertyDescriptor (((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(), getResourceLocator(), getString("_UI_D2_8xlarge_occiComputeCores_feature"), getString("_UI_PropertyDescriptor_description", "_UI_D2_8xlarge_occiComputeCores_feature", "_UI_D2_8xlarge_type"), Ec2Package.eINSTANCE.getD2_8xlarge_OcciComputeCores(), true, false, false, ItemPropertyDescriptor.GENERIC_VALUE_IMAGE, null, null)); } /** * This adds a property descriptor for the Occi Compute Ephemeral Storage Size feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected void addOcciComputeEphemeralStorageSizePropertyDescriptor(Object object) { itemPropertyDescriptors.add (createItemPropertyDescriptor (((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(), getResourceLocator(), getString("_UI_D2_8xlarge_occiComputeEphemeralStorageSize_feature"), getString("_UI_PropertyDescriptor_description", "_UI_D2_8xlarge_occiComputeEphemeralStorageSize_feature", "_UI_D2_8xlarge_type"), Ec2Package.eINSTANCE.getD2_8xlarge_OcciComputeEphemeralStorageSize(), true, false, false, ItemPropertyDescriptor.GENERIC_VALUE_IMAGE, null, null)); } /** * This returns D2_8xlarge.gif. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object getImage(Object object) { return overlayImage(object, getResourceLocator().getImage("full/obj16/D2_8xlarge")); } /** * This returns the label text for the adapted class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String getText(Object object) { Float labelValue = ((D2_8xlarge)object).getOcciComputeMemory(); String label = labelValue == null ? null : labelValue.toString(); return label == null || label.length() == 0 ? getString("_UI_D2_8xlarge_type") : getString("_UI_D2_8xlarge_type") + " " + label; } /** * This handles model notifications by calling {@link #updateChildren} to update any cached * children and by creating a viewer notification, which it passes to {@link #fireNotifyChanged}. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void notifyChanged(Notification notification) { updateChildren(notification); switch (notification.getFeatureID(D2_8xlarge.class)) { case Ec2Package.D2_8XLARGE__OCCI_COMPUTE_MEMORY: case Ec2Package.D2_8XLARGE__INSTANCE_TYPE: case Ec2Package.D2_8XLARGE__OCCI_COMPUTE_CORES: case Ec2Package.D2_8XLARGE__OCCI_COMPUTE_EPHEMERAL_STORAGE_SIZE: fireNotifyChanged(new ViewerNotification(notification, notification.getNotifier(), false, true)); return; } super.notifyChanged(notification); } /** * This adds {@link org.eclipse.emf.edit.command.CommandParameter}s describing the children * that can be created under this object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected void collectNewChildDescriptors(Collection<Object> newChildDescriptors, Object object) { super.collectNewChildDescriptors(newChildDescriptors, object); } }
epl-1.0
jesusc/bento
plugins/genericity.language.gbind.resource/src-gen/genericity/language/gbind/mopp/GbindPrinter2.java
64095
/** * <copyright> * </copyright> * * */ package genericity.language.gbind.mopp; public class GbindPrinter2 implements genericity.language.gbind.IGbindTextPrinter { protected class PrintToken { private String text; private String tokenName; private org.eclipse.emf.ecore.EObject container; public PrintToken(String text, String tokenName, org.eclipse.emf.ecore.EObject container) { this.text = text; this.tokenName = tokenName; this.container = container; } public String getText() { return text; } public String getTokenName() { return tokenName; } public org.eclipse.emf.ecore.EObject getContainer() { return container; } public String toString() { return "'" + text + "' [" + tokenName + "]"; } } /** * The PrintCountingMap keeps tracks of the values that must be printed for each * feature of an EObject. It is also used to store the indices of all values that * have been printed. This knowledge is used to avoid printing values twice. We * must store the concrete indices of the printed values instead of basically * counting them, because values may be printed in an order that differs from the * order in which they are stored in the EObject's feature. */ protected class PrintCountingMap { private java.util.Map<String, java.util.List<Object>> featureToValuesMap = new java.util.LinkedHashMap<String, java.util.List<Object>>(); private java.util.Map<String, java.util.Set<Integer>> featureToPrintedIndicesMap = new java.util.LinkedHashMap<String, java.util.Set<Integer>>(); public void setFeatureValues(String featureName, java.util.List<Object> values) { featureToValuesMap.put(featureName, values); // If the feature does not have values it won't be printed. An entry in // 'featureToPrintedIndicesMap' is therefore not needed in this case. if (values != null) { featureToPrintedIndicesMap.put(featureName, new java.util.LinkedHashSet<Integer>()); } } public java.util.Set<Integer> getIndicesToPrint(String featureName) { return featureToPrintedIndicesMap.get(featureName); } public void addIndexToPrint(String featureName, int index) { featureToPrintedIndicesMap.get(featureName).add(index); } public int getCountLeft(genericity.language.gbind.grammar.GbindTerminal terminal) { org.eclipse.emf.ecore.EStructuralFeature feature = terminal.getFeature(); String featureName = feature.getName(); java.util.List<Object> totalValuesToPrint = featureToValuesMap.get(featureName); java.util.Set<Integer> printedIndices = featureToPrintedIndicesMap.get(featureName); if (totalValuesToPrint == null) { return 0; } if (feature instanceof org.eclipse.emf.ecore.EAttribute) { // for attributes we do not need to check the type, since the CS languages does // not allow type restrictions for attributes. return totalValuesToPrint.size() - printedIndices.size(); } else if (feature instanceof org.eclipse.emf.ecore.EReference) { org.eclipse.emf.ecore.EReference reference = (org.eclipse.emf.ecore.EReference) feature; if (!reference.isContainment()) { // for non-containment references we also do not need to check the type, since the // CS languages does not allow type restrictions for these either. return totalValuesToPrint.size() - printedIndices.size(); } } // now we're left with containment references for which we check the type of the // objects to print java.util.List<Class<?>> allowedTypes = getAllowedTypes(terminal); java.util.Set<Integer> indicesWithCorrectType = new java.util.LinkedHashSet<Integer>(); int index = 0; for (Object valueToPrint : totalValuesToPrint) { for (Class<?> allowedType : allowedTypes) { if (allowedType.isInstance(valueToPrint)) { indicesWithCorrectType.add(index); } } index++; } indicesWithCorrectType.removeAll(printedIndices); return indicesWithCorrectType.size(); } public int getNextIndexToPrint(String featureName) { int printedValues = featureToPrintedIndicesMap.get(featureName).size(); return printedValues; } } public final static String NEW_LINE = java.lang.System.getProperties().getProperty("line.separator"); private final genericity.language.gbind.util.GbindEClassUtil eClassUtil = new genericity.language.gbind.util.GbindEClassUtil(); /** * Holds the resource that is associated with this printer. May be null if the * printer is used stand alone. */ private genericity.language.gbind.IGbindTextResource resource; private java.util.Map<?, ?> options; private java.io.OutputStream outputStream; private String encoding = System.getProperty("file.encoding"); protected java.util.List<PrintToken> tokenOutputStream; private genericity.language.gbind.IGbindTokenResolverFactory tokenResolverFactory = new genericity.language.gbind.mopp.GbindTokenResolverFactory(); private boolean handleTokenSpaceAutomatically = true; private int tokenSpace = 1; /** * A flag that indicates whether tokens have already been printed for some object. * The flag is set to false whenever printing of an EObject tree is started. The * status of the flag is used to avoid printing default token space in front of * the root object. */ private boolean startedPrintingObject = false; /** * The number of tab characters that were printed before the current line. This * number is used to calculate the relative indentation when printing contained * objects, because all contained objects must start with this indentation * (tabsBeforeCurrentObject + currentTabs). */ private int currentTabs; /** * The number of tab characters that must be printed before the current object. * This number is used to calculate the indentation of new lines, when line breaks * are printed within one object. */ private int tabsBeforeCurrentObject; /** * This flag is used to indicate whether the number of tabs before the current * object has been set for the current object. The flag is needed, because setting * the number of tabs must be performed when the first token of the contained * element is printed. */ private boolean startedPrintingContainedObject; public GbindPrinter2(java.io.OutputStream outputStream, genericity.language.gbind.IGbindTextResource resource) { super(); this.outputStream = outputStream; this.resource = resource; } public void print(org.eclipse.emf.ecore.EObject element) throws java.io.IOException { tokenOutputStream = new java.util.ArrayList<PrintToken>(); currentTabs = 0; tabsBeforeCurrentObject = 0; startedPrintingObject = true; startedPrintingContainedObject = false; java.util.List<genericity.language.gbind.grammar.GbindFormattingElement> formattingElements = new java.util.ArrayList<genericity.language.gbind.grammar.GbindFormattingElement>(); doPrint(element, formattingElements); // print all remaining formatting elements java.util.List<genericity.language.gbind.mopp.GbindLayoutInformation> layoutInformations = getCopyOfLayoutInformation(element); genericity.language.gbind.mopp.GbindLayoutInformation eofLayoutInformation = getLayoutInformation(layoutInformations, null, null, null); printFormattingElements(element, formattingElements, layoutInformations, eofLayoutInformation); java.io.PrintWriter writer = new java.io.PrintWriter(new java.io.OutputStreamWriter(new java.io.BufferedOutputStream(outputStream), encoding)); if (handleTokenSpaceAutomatically) { printSmart(writer); } else { printBasic(writer); } writer.flush(); } protected void doPrint(org.eclipse.emf.ecore.EObject element, java.util.List<genericity.language.gbind.grammar.GbindFormattingElement> foundFormattingElements) { if (element == null) { throw new java.lang.IllegalArgumentException("Nothing to write."); } if (outputStream == null) { throw new java.lang.IllegalArgumentException("Nothing to write on."); } if (element instanceof gbind.simpleocl.Module) { printInternal(element, genericity.language.gbind.grammar.GbindGrammarInformationProvider.GBIND_0, foundFormattingElements); return; } if (element instanceof gbind.simpleocl.Import) { printInternal(element, genericity.language.gbind.grammar.GbindGrammarInformationProvider.GBIND_1, foundFormattingElements); return; } if (element instanceof gbind.simpleocl.OclFeatureDefinition) { printInternal(element, genericity.language.gbind.grammar.GbindGrammarInformationProvider.GBIND_2, foundFormattingElements); return; } if (element instanceof gbind.simpleocl.OclContextDefinition) { printInternal(element, genericity.language.gbind.grammar.GbindGrammarInformationProvider.GBIND_3, foundFormattingElements); return; } if (element instanceof gbind.simpleocl.OclInstanceModel) { printInternal(element, genericity.language.gbind.grammar.GbindGrammarInformationProvider.GBIND_5, foundFormattingElements); return; } if (element instanceof gbind.simpleocl.Attribute) { printInternal(element, genericity.language.gbind.grammar.GbindGrammarInformationProvider.GBIND_7, foundFormattingElements); return; } if (element instanceof gbind.simpleocl.Operation) { printInternal(element, genericity.language.gbind.grammar.GbindGrammarInformationProvider.GBIND_8, foundFormattingElements); return; } if (element instanceof gbind.simpleocl.Parameter) { printInternal(element, genericity.language.gbind.grammar.GbindGrammarInformationProvider.GBIND_9, foundFormattingElements); return; } if (element instanceof gbind.simpleocl.OclModelElementExp) { printInternal(element, genericity.language.gbind.grammar.GbindGrammarInformationProvider.GBIND_10, foundFormattingElements); return; } if (element instanceof gbind.simpleocl.LambdaCallExp) { printInternal(element, genericity.language.gbind.grammar.GbindGrammarInformationProvider.GBIND_11, foundFormattingElements); return; } if (element instanceof gbind.simpleocl.VariableExp) { printInternal(element, genericity.language.gbind.grammar.GbindGrammarInformationProvider.GBIND_12, foundFormattingElements); return; } if (element instanceof gbind.simpleocl.SuperExp) { printInternal(element, genericity.language.gbind.grammar.GbindGrammarInformationProvider.GBIND_13, foundFormattingElements); return; } if (element instanceof gbind.simpleocl.SelfExp) { printInternal(element, genericity.language.gbind.grammar.GbindGrammarInformationProvider.GBIND_14, foundFormattingElements); return; } if (element instanceof gbind.simpleocl.EnvExp) { printInternal(element, genericity.language.gbind.grammar.GbindGrammarInformationProvider.GBIND_15, foundFormattingElements); return; } if (element instanceof gbind.simpleocl.StringExp) { printInternal(element, genericity.language.gbind.grammar.GbindGrammarInformationProvider.GBIND_16, foundFormattingElements); return; } if (element instanceof gbind.simpleocl.BooleanExp) { printInternal(element, genericity.language.gbind.grammar.GbindGrammarInformationProvider.GBIND_17, foundFormattingElements); return; } if (element instanceof gbind.simpleocl.RealExp) { printInternal(element, genericity.language.gbind.grammar.GbindGrammarInformationProvider.GBIND_18, foundFormattingElements); return; } if (element instanceof gbind.simpleocl.IntegerExp) { printInternal(element, genericity.language.gbind.grammar.GbindGrammarInformationProvider.GBIND_19, foundFormattingElements); return; } if (element instanceof gbind.simpleocl.BagExp) { printInternal(element, genericity.language.gbind.grammar.GbindGrammarInformationProvider.GBIND_20, foundFormattingElements); return; } if (element instanceof gbind.simpleocl.OrderedSetExp) { printInternal(element, genericity.language.gbind.grammar.GbindGrammarInformationProvider.GBIND_21, foundFormattingElements); return; } if (element instanceof gbind.simpleocl.SequenceExp) { printInternal(element, genericity.language.gbind.grammar.GbindGrammarInformationProvider.GBIND_22, foundFormattingElements); return; } if (element instanceof gbind.simpleocl.SetExp) { printInternal(element, genericity.language.gbind.grammar.GbindGrammarInformationProvider.GBIND_23, foundFormattingElements); return; } if (element instanceof gbind.simpleocl.TuplePart) { printInternal(element, genericity.language.gbind.grammar.GbindGrammarInformationProvider.GBIND_25, foundFormattingElements); return; } if (element instanceof gbind.simpleocl.MapExp) { printInternal(element, genericity.language.gbind.grammar.GbindGrammarInformationProvider.GBIND_26, foundFormattingElements); return; } if (element instanceof gbind.simpleocl.MapElement) { printInternal(element, genericity.language.gbind.grammar.GbindGrammarInformationProvider.GBIND_27, foundFormattingElements); return; } if (element instanceof gbind.simpleocl.EnumLiteralExp) { printInternal(element, genericity.language.gbind.grammar.GbindGrammarInformationProvider.GBIND_28, foundFormattingElements); return; } if (element instanceof gbind.simpleocl.OclUndefinedExp) { printInternal(element, genericity.language.gbind.grammar.GbindGrammarInformationProvider.GBIND_29, foundFormattingElements); return; } if (element instanceof gbind.simpleocl.LetExp) { printInternal(element, genericity.language.gbind.grammar.GbindGrammarInformationProvider.GBIND_30, foundFormattingElements); return; } if (element instanceof gbind.simpleocl.IfExp) { printInternal(element, genericity.language.gbind.grammar.GbindGrammarInformationProvider.GBIND_31, foundFormattingElements); return; } if (element instanceof gbind.simpleocl.BraceExp) { printInternal(element, genericity.language.gbind.grammar.GbindGrammarInformationProvider.GBIND_32, foundFormattingElements); return; } if (element instanceof gbind.simpleocl.EqOpCallExp) { printInternal(element, genericity.language.gbind.grammar.GbindGrammarInformationProvider.GBIND_34, foundFormattingElements); return; } if (element instanceof gbind.simpleocl.RelOpCallExp) { printInternal(element, genericity.language.gbind.grammar.GbindGrammarInformationProvider.GBIND_35, foundFormattingElements); return; } if (element instanceof gbind.simpleocl.AddOpCallExp) { printInternal(element, genericity.language.gbind.grammar.GbindGrammarInformationProvider.GBIND_36, foundFormattingElements); return; } if (element instanceof gbind.simpleocl.IntOpCallExp) { printInternal(element, genericity.language.gbind.grammar.GbindGrammarInformationProvider.GBIND_37, foundFormattingElements); return; } if (element instanceof gbind.simpleocl.MulOpCallExp) { printInternal(element, genericity.language.gbind.grammar.GbindGrammarInformationProvider.GBIND_38, foundFormattingElements); return; } if (element instanceof gbind.simpleocl.NotOpCallExp) { printInternal(element, genericity.language.gbind.grammar.GbindGrammarInformationProvider.GBIND_39, foundFormattingElements); return; } if (element instanceof gbind.simpleocl.StaticPropertyCallExp) { printInternal(element, genericity.language.gbind.grammar.GbindGrammarInformationProvider.GBIND_40, foundFormattingElements); return; } if (element instanceof gbind.simpleocl.StaticOperationCall) { printInternal(element, genericity.language.gbind.grammar.GbindGrammarInformationProvider.GBIND_41, foundFormattingElements); return; } if (element instanceof gbind.simpleocl.StaticNavigationOrAttributeCall) { printInternal(element, genericity.language.gbind.grammar.GbindGrammarInformationProvider.GBIND_42, foundFormattingElements); return; } if (element instanceof gbind.simpleocl.PropertyCallExp) { printInternal(element, genericity.language.gbind.grammar.GbindGrammarInformationProvider.GBIND_43, foundFormattingElements); return; } if (element instanceof gbind.simpleocl.NavigationOrAttributeCall) { printInternal(element, genericity.language.gbind.grammar.GbindGrammarInformationProvider.GBIND_45, foundFormattingElements); return; } if (element instanceof gbind.simpleocl.IterateExp) { printInternal(element, genericity.language.gbind.grammar.GbindGrammarInformationProvider.GBIND_46, foundFormattingElements); return; } if (element instanceof gbind.simpleocl.IteratorExp) { printInternal(element, genericity.language.gbind.grammar.GbindGrammarInformationProvider.GBIND_47, foundFormattingElements); return; } if (element instanceof gbind.simpleocl.Iterator) { printInternal(element, genericity.language.gbind.grammar.GbindGrammarInformationProvider.GBIND_48, foundFormattingElements); return; } if (element instanceof gbind.simpleocl.CollectionOperationCall) { printInternal(element, genericity.language.gbind.grammar.GbindGrammarInformationProvider.GBIND_49, foundFormattingElements); return; } if (element instanceof gbind.simpleocl.StringType) { printInternal(element, genericity.language.gbind.grammar.GbindGrammarInformationProvider.GBIND_51, foundFormattingElements); return; } if (element instanceof gbind.simpleocl.BooleanType) { printInternal(element, genericity.language.gbind.grammar.GbindGrammarInformationProvider.GBIND_52, foundFormattingElements); return; } if (element instanceof gbind.simpleocl.IntegerType) { printInternal(element, genericity.language.gbind.grammar.GbindGrammarInformationProvider.GBIND_53, foundFormattingElements); return; } if (element instanceof gbind.simpleocl.RealType) { printInternal(element, genericity.language.gbind.grammar.GbindGrammarInformationProvider.GBIND_54, foundFormattingElements); return; } if (element instanceof gbind.simpleocl.BagType) { printInternal(element, genericity.language.gbind.grammar.GbindGrammarInformationProvider.GBIND_55, foundFormattingElements); return; } if (element instanceof gbind.simpleocl.OrderedSetType) { printInternal(element, genericity.language.gbind.grammar.GbindGrammarInformationProvider.GBIND_56, foundFormattingElements); return; } if (element instanceof gbind.simpleocl.SequenceType) { printInternal(element, genericity.language.gbind.grammar.GbindGrammarInformationProvider.GBIND_57, foundFormattingElements); return; } if (element instanceof gbind.simpleocl.SetType) { printInternal(element, genericity.language.gbind.grammar.GbindGrammarInformationProvider.GBIND_58, foundFormattingElements); return; } if (element instanceof gbind.simpleocl.OclAnyType) { printInternal(element, genericity.language.gbind.grammar.GbindGrammarInformationProvider.GBIND_59, foundFormattingElements); return; } if (element instanceof gbind.simpleocl.TupleType) { printInternal(element, genericity.language.gbind.grammar.GbindGrammarInformationProvider.GBIND_61, foundFormattingElements); return; } if (element instanceof gbind.simpleocl.TupleTypeAttribute) { printInternal(element, genericity.language.gbind.grammar.GbindGrammarInformationProvider.GBIND_62, foundFormattingElements); return; } if (element instanceof gbind.simpleocl.OclModelElement) { printInternal(element, genericity.language.gbind.grammar.GbindGrammarInformationProvider.GBIND_63, foundFormattingElements); return; } if (element instanceof gbind.simpleocl.MapType) { printInternal(element, genericity.language.gbind.grammar.GbindGrammarInformationProvider.GBIND_64, foundFormattingElements); return; } if (element instanceof gbind.simpleocl.LambdaType) { printInternal(element, genericity.language.gbind.grammar.GbindGrammarInformationProvider.GBIND_65, foundFormattingElements); return; } if (element instanceof gbind.simpleocl.EnvType) { printInternal(element, genericity.language.gbind.grammar.GbindGrammarInformationProvider.GBIND_66, foundFormattingElements); return; } if (element instanceof gbind.dsl.BindingModel) { printInternal(element, genericity.language.gbind.grammar.GbindGrammarInformationProvider.GBIND_67, foundFormattingElements); return; } if (element instanceof gbind.dsl.BindingOptions) { printInternal(element, genericity.language.gbind.grammar.GbindGrammarInformationProvider.GBIND_68, foundFormattingElements); return; } if (element instanceof gbind.dsl.MetamodelDeclaration) { printInternal(element, genericity.language.gbind.grammar.GbindGrammarInformationProvider.GBIND_69, foundFormattingElements); return; } if (element instanceof gbind.dsl.ClassBinding) { printInternal(element, genericity.language.gbind.grammar.GbindGrammarInformationProvider.GBIND_70, foundFormattingElements); return; } if (element instanceof gbind.dsl.IntermediateClassBinding) { printInternal(element, genericity.language.gbind.grammar.GbindGrammarInformationProvider.GBIND_71, foundFormattingElements); return; } if (element instanceof gbind.dsl.ConcreteReferencDeclaringVar) { printInternal(element, genericity.language.gbind.grammar.GbindGrammarInformationProvider.GBIND_72, foundFormattingElements); return; } if (element instanceof gbind.dsl.VirtualMetaclass) { printInternal(element, genericity.language.gbind.grammar.GbindGrammarInformationProvider.GBIND_73, foundFormattingElements); return; } if (element instanceof gbind.dsl.VirtualTupleExp) { printInternal(element, genericity.language.gbind.grammar.GbindGrammarInformationProvider.GBIND_74, foundFormattingElements); return; } if (element instanceof gbind.dsl.VirtualReference) { printInternal(element, genericity.language.gbind.grammar.GbindGrammarInformationProvider.GBIND_75, foundFormattingElements); return; } if (element instanceof gbind.dsl.VirtualAttribute) { printInternal(element, genericity.language.gbind.grammar.GbindGrammarInformationProvider.GBIND_76, foundFormattingElements); return; } if (element instanceof gbind.dsl.VirtualClassBinding) { printInternal(element, genericity.language.gbind.grammar.GbindGrammarInformationProvider.GBIND_77, foundFormattingElements); return; } if (element instanceof gbind.dsl.ConceptFeatureRef) { printInternal(element, genericity.language.gbind.grammar.GbindGrammarInformationProvider.GBIND_78, foundFormattingElements); return; } if (element instanceof gbind.dsl.OclFeatureBinding) { printInternal(element, genericity.language.gbind.grammar.GbindGrammarInformationProvider.GBIND_79, foundFormattingElements); return; } if (element instanceof gbind.dsl.RenamingFeatureBinding) { printInternal(element, genericity.language.gbind.grammar.GbindGrammarInformationProvider.GBIND_80, foundFormattingElements); return; } if (element instanceof gbind.dsl.ConceptHelper) { printInternal(element, genericity.language.gbind.grammar.GbindGrammarInformationProvider.GBIND_81, foundFormattingElements); return; } if (element instanceof gbind.dsl.LocalHelper) { printInternal(element, genericity.language.gbind.grammar.GbindGrammarInformationProvider.GBIND_82, foundFormattingElements); return; } if (element instanceof gbind.dsl.HelperParameter) { printInternal(element, genericity.language.gbind.grammar.GbindGrammarInformationProvider.GBIND_83, foundFormattingElements); return; } if (element instanceof gbind.simpleocl.OclMetamodel) { printInternal(element, genericity.language.gbind.grammar.GbindGrammarInformationProvider.GBIND_4, foundFormattingElements); return; } if (element instanceof gbind.simpleocl.LocalVariable) { printInternal(element, genericity.language.gbind.grammar.GbindGrammarInformationProvider.GBIND_6, foundFormattingElements); return; } if (element instanceof gbind.simpleocl.TupleExp) { printInternal(element, genericity.language.gbind.grammar.GbindGrammarInformationProvider.GBIND_24, foundFormattingElements); return; } if (element instanceof gbind.simpleocl.OperatorCallExp) { printInternal(element, genericity.language.gbind.grammar.GbindGrammarInformationProvider.GBIND_33, foundFormattingElements); return; } if (element instanceof gbind.simpleocl.OperationCall) { printInternal(element, genericity.language.gbind.grammar.GbindGrammarInformationProvider.GBIND_44, foundFormattingElements); return; } if (element instanceof gbind.simpleocl.CollectionType) { printInternal(element, genericity.language.gbind.grammar.GbindGrammarInformationProvider.GBIND_50, foundFormattingElements); return; } if (element instanceof gbind.simpleocl.OclType) { printInternal(element, genericity.language.gbind.grammar.GbindGrammarInformationProvider.GBIND_60, foundFormattingElements); return; } addWarningToResource("The printer can not handle " + element.eClass().getName() + " elements", element); } public void printInternal(org.eclipse.emf.ecore.EObject eObject, genericity.language.gbind.grammar.GbindSyntaxElement ruleElement, java.util.List<genericity.language.gbind.grammar.GbindFormattingElement> foundFormattingElements) { java.util.List<genericity.language.gbind.mopp.GbindLayoutInformation> layoutInformations = getCopyOfLayoutInformation(eObject); genericity.language.gbind.mopp.GbindSyntaxElementDecorator decoratorTree = getDecoratorTree(ruleElement); decorateTree(decoratorTree, eObject); printTree(decoratorTree, eObject, foundFormattingElements, layoutInformations); } /** * creates a tree of decorator objects which reflects the syntax tree that is * attached to the given syntax element */ public genericity.language.gbind.mopp.GbindSyntaxElementDecorator getDecoratorTree(genericity.language.gbind.grammar.GbindSyntaxElement syntaxElement) { genericity.language.gbind.grammar.GbindSyntaxElement[] children = syntaxElement.getChildren(); int childCount = children.length; genericity.language.gbind.mopp.GbindSyntaxElementDecorator[] childDecorators = new genericity.language.gbind.mopp.GbindSyntaxElementDecorator[childCount]; for (int i = 0; i < childCount; i++) { childDecorators[i] = getDecoratorTree(children[i]); } genericity.language.gbind.mopp.GbindSyntaxElementDecorator decorator = new genericity.language.gbind.mopp.GbindSyntaxElementDecorator(syntaxElement, childDecorators); return decorator; } public void decorateTree(genericity.language.gbind.mopp.GbindSyntaxElementDecorator decorator, org.eclipse.emf.ecore.EObject eObject) { PrintCountingMap printCountingMap = initializePrintCountingMap(eObject); java.util.List<genericity.language.gbind.mopp.GbindSyntaxElementDecorator> keywordsToPrint = new java.util.ArrayList<genericity.language.gbind.mopp.GbindSyntaxElementDecorator>(); decorateTreeBasic(decorator, eObject, printCountingMap, keywordsToPrint); for (genericity.language.gbind.mopp.GbindSyntaxElementDecorator keywordToPrint : keywordsToPrint) { // for keywords the concrete index does not matter, but we must add one to // indicate that the keyword needs to be printed here. Thus, we use 0 as index. keywordToPrint.addIndexToPrint(0); } } /** * Tries to decorate the decorator with an attribute value, or reference held by * the given EObject. Returns true if an attribute value or reference was found. */ public boolean decorateTreeBasic(genericity.language.gbind.mopp.GbindSyntaxElementDecorator decorator, org.eclipse.emf.ecore.EObject eObject, PrintCountingMap printCountingMap, java.util.List<genericity.language.gbind.mopp.GbindSyntaxElementDecorator> keywordsToPrint) { boolean foundFeatureToPrint = false; genericity.language.gbind.grammar.GbindSyntaxElement syntaxElement = decorator.getDecoratedElement(); genericity.language.gbind.grammar.GbindCardinality cardinality = syntaxElement.getCardinality(); boolean isFirstIteration = true; while (true) { java.util.List<genericity.language.gbind.mopp.GbindSyntaxElementDecorator> subKeywordsToPrint = new java.util.ArrayList<genericity.language.gbind.mopp.GbindSyntaxElementDecorator>(); boolean keepDecorating = false; if (syntaxElement instanceof genericity.language.gbind.grammar.GbindKeyword) { subKeywordsToPrint.add(decorator); } else if (syntaxElement instanceof genericity.language.gbind.grammar.GbindTerminal) { genericity.language.gbind.grammar.GbindTerminal terminal = (genericity.language.gbind.grammar.GbindTerminal) syntaxElement; org.eclipse.emf.ecore.EStructuralFeature feature = terminal.getFeature(); if (feature == genericity.language.gbind.grammar.GbindGrammarInformationProvider.ANONYMOUS_FEATURE) { return false; } String featureName = feature.getName(); int countLeft = printCountingMap.getCountLeft(terminal); if (countLeft > terminal.getMandatoryOccurencesAfter()) { // normally we print the element at the next index int indexToPrint = printCountingMap.getNextIndexToPrint(featureName); // But, if there are type restrictions for containments, we must choose an index // of an element that fits (i.e., which has the correct type) if (terminal instanceof genericity.language.gbind.grammar.GbindContainment) { genericity.language.gbind.grammar.GbindContainment containment = (genericity.language.gbind.grammar.GbindContainment) terminal; indexToPrint = findElementWithCorrectType(eObject, feature, printCountingMap.getIndicesToPrint(featureName), containment); } if (indexToPrint >= 0) { decorator.addIndexToPrint(indexToPrint); printCountingMap.addIndexToPrint(featureName, indexToPrint); keepDecorating = true; } } } if (syntaxElement instanceof genericity.language.gbind.grammar.GbindChoice) { // for choices we do print only the choice which does print at least one feature genericity.language.gbind.mopp.GbindSyntaxElementDecorator childToPrint = null; for (genericity.language.gbind.mopp.GbindSyntaxElementDecorator childDecorator : decorator.getChildDecorators()) { // pick first choice as default, will be overridden if a choice that prints a // feature is found if (childToPrint == null) { childToPrint = childDecorator; } if (doesPrintFeature(childDecorator, eObject, printCountingMap)) { childToPrint = childDecorator; break; } } keepDecorating |= decorateTreeBasic(childToPrint, eObject, printCountingMap, subKeywordsToPrint); } else { // for all other syntax element we do print all children for (genericity.language.gbind.mopp.GbindSyntaxElementDecorator childDecorator : decorator.getChildDecorators()) { keepDecorating |= decorateTreeBasic(childDecorator, eObject, printCountingMap, subKeywordsToPrint); } } foundFeatureToPrint |= keepDecorating; // only print keywords if a feature was printed or the syntax element is mandatory if (cardinality == genericity.language.gbind.grammar.GbindCardinality.ONE) { keywordsToPrint.addAll(subKeywordsToPrint); } else if (cardinality == genericity.language.gbind.grammar.GbindCardinality.PLUS) { if (isFirstIteration) { keywordsToPrint.addAll(subKeywordsToPrint); } else { if (keepDecorating) { keywordsToPrint.addAll(subKeywordsToPrint); } } } else if (keepDecorating && (cardinality == genericity.language.gbind.grammar.GbindCardinality.STAR || cardinality == genericity.language.gbind.grammar.GbindCardinality.QUESTIONMARK)) { keywordsToPrint.addAll(subKeywordsToPrint); } if (cardinality == genericity.language.gbind.grammar.GbindCardinality.ONE || cardinality == genericity.language.gbind.grammar.GbindCardinality.QUESTIONMARK) { break; } else if (!keepDecorating) { break; } isFirstIteration = false; } return foundFeatureToPrint; } private int findElementWithCorrectType(org.eclipse.emf.ecore.EObject eObject, org.eclipse.emf.ecore.EStructuralFeature feature, java.util.Set<Integer> indicesToPrint, genericity.language.gbind.grammar.GbindContainment containment) { // By default the type restrictions that are defined in the CS definition are // considered when printing models. You can change this behavior by setting the // 'ignoreTypeRestrictionsForPrinting' option to true. boolean ignoreTypeRestrictions = false; org.eclipse.emf.ecore.EClass[] allowedTypes = containment.getAllowedTypes(); Object value = eObject.eGet(feature); if (value instanceof java.util.List<?>) { java.util.List<?> valueList = (java.util.List<?>) value; int listSize = valueList.size(); for (int index = 0; index < listSize; index++) { if (indicesToPrint.contains(index)) { continue; } Object valueAtIndex = valueList.get(index); if (eClassUtil.isInstance(valueAtIndex, allowedTypes) || ignoreTypeRestrictions) { return index; } } } else { if (eClassUtil.isInstance(value, allowedTypes) || ignoreTypeRestrictions) { return 0; } } return -1; } /** * Checks whether decorating the given node will use at least one attribute value, * or reference held by eObject. Returns true if a printable attribute value or * reference was found. This method is used to decide which choice to pick, when * multiple choices are available. We pick the choice that prints at least one * attribute or reference. */ public boolean doesPrintFeature(genericity.language.gbind.mopp.GbindSyntaxElementDecorator decorator, org.eclipse.emf.ecore.EObject eObject, PrintCountingMap printCountingMap) { genericity.language.gbind.grammar.GbindSyntaxElement syntaxElement = decorator.getDecoratedElement(); if (syntaxElement instanceof genericity.language.gbind.grammar.GbindTerminal) { genericity.language.gbind.grammar.GbindTerminal terminal = (genericity.language.gbind.grammar.GbindTerminal) syntaxElement; org.eclipse.emf.ecore.EStructuralFeature feature = terminal.getFeature(); if (feature == genericity.language.gbind.grammar.GbindGrammarInformationProvider.ANONYMOUS_FEATURE) { return false; } int countLeft = printCountingMap.getCountLeft(terminal); if (countLeft > terminal.getMandatoryOccurencesAfter()) { // found a feature to print return true; } } for (genericity.language.gbind.mopp.GbindSyntaxElementDecorator childDecorator : decorator.getChildDecorators()) { if (doesPrintFeature(childDecorator, eObject, printCountingMap)) { return true; } } return false; } public boolean printTree(genericity.language.gbind.mopp.GbindSyntaxElementDecorator decorator, org.eclipse.emf.ecore.EObject eObject, java.util.List<genericity.language.gbind.grammar.GbindFormattingElement> foundFormattingElements, java.util.List<genericity.language.gbind.mopp.GbindLayoutInformation> layoutInformations) { genericity.language.gbind.grammar.GbindSyntaxElement printElement = decorator.getDecoratedElement(); genericity.language.gbind.grammar.GbindCardinality cardinality = printElement.getCardinality(); java.util.List<genericity.language.gbind.grammar.GbindFormattingElement> cloned = new java.util.ArrayList<genericity.language.gbind.grammar.GbindFormattingElement>(); cloned.addAll(foundFormattingElements); boolean foundSomethingAtAll = false; boolean foundSomethingToPrint; while (true) { foundSomethingToPrint = false; Integer indexToPrint = decorator.getNextIndexToPrint(); if (indexToPrint != null) { if (printElement instanceof genericity.language.gbind.grammar.GbindKeyword) { printKeyword(eObject, (genericity.language.gbind.grammar.GbindKeyword) printElement, foundFormattingElements, layoutInformations); foundSomethingToPrint = true; } else if (printElement instanceof genericity.language.gbind.grammar.GbindPlaceholder) { genericity.language.gbind.grammar.GbindPlaceholder placeholder = (genericity.language.gbind.grammar.GbindPlaceholder) printElement; printFeature(eObject, placeholder, indexToPrint, foundFormattingElements, layoutInformations); foundSomethingToPrint = true; } else if (printElement instanceof genericity.language.gbind.grammar.GbindContainment) { genericity.language.gbind.grammar.GbindContainment containment = (genericity.language.gbind.grammar.GbindContainment) printElement; printContainedObject(eObject, containment, indexToPrint, foundFormattingElements, layoutInformations); foundSomethingToPrint = true; } else if (printElement instanceof genericity.language.gbind.grammar.GbindBooleanTerminal) { genericity.language.gbind.grammar.GbindBooleanTerminal booleanTerminal = (genericity.language.gbind.grammar.GbindBooleanTerminal) printElement; printBooleanTerminal(eObject, booleanTerminal, indexToPrint, foundFormattingElements, layoutInformations); foundSomethingToPrint = true; } else if (printElement instanceof genericity.language.gbind.grammar.GbindEnumerationTerminal) { genericity.language.gbind.grammar.GbindEnumerationTerminal enumTerminal = (genericity.language.gbind.grammar.GbindEnumerationTerminal) printElement; printEnumerationTerminal(eObject, enumTerminal, indexToPrint, foundFormattingElements, layoutInformations); foundSomethingToPrint = true; } } if (foundSomethingToPrint) { foundSomethingAtAll = true; } if (printElement instanceof genericity.language.gbind.grammar.GbindWhiteSpace) { foundFormattingElements.add((genericity.language.gbind.grammar.GbindWhiteSpace) printElement); } if (printElement instanceof genericity.language.gbind.grammar.GbindLineBreak) { foundFormattingElements.add((genericity.language.gbind.grammar.GbindLineBreak) printElement); } for (genericity.language.gbind.mopp.GbindSyntaxElementDecorator childDecorator : decorator.getChildDecorators()) { foundSomethingToPrint |= printTree(childDecorator, eObject, foundFormattingElements, layoutInformations); genericity.language.gbind.grammar.GbindSyntaxElement decoratedElement = decorator.getDecoratedElement(); if (foundSomethingToPrint && decoratedElement instanceof genericity.language.gbind.grammar.GbindChoice) { break; } } if (cardinality == genericity.language.gbind.grammar.GbindCardinality.ONE || cardinality == genericity.language.gbind.grammar.GbindCardinality.QUESTIONMARK) { break; } else if (!foundSomethingToPrint) { break; } } // only print formatting elements if a feature was printed or the syntax element // is mandatory if (!foundSomethingAtAll && (cardinality == genericity.language.gbind.grammar.GbindCardinality.STAR || cardinality == genericity.language.gbind.grammar.GbindCardinality.QUESTIONMARK)) { foundFormattingElements.clear(); foundFormattingElements.addAll(cloned); } return foundSomethingToPrint; } public void printKeyword(org.eclipse.emf.ecore.EObject eObject, genericity.language.gbind.grammar.GbindKeyword keyword, java.util.List<genericity.language.gbind.grammar.GbindFormattingElement> foundFormattingElements, java.util.List<genericity.language.gbind.mopp.GbindLayoutInformation> layoutInformations) { genericity.language.gbind.mopp.GbindLayoutInformation keywordLayout = getLayoutInformation(layoutInformations, keyword, null, eObject); printFormattingElements(eObject, foundFormattingElements, layoutInformations, keywordLayout); String value = keyword.getValue(); tokenOutputStream.add(new PrintToken(value, "'" + genericity.language.gbind.util.GbindStringUtil.escapeToANTLRKeyword(value) + "'", eObject)); } public void printFeature(org.eclipse.emf.ecore.EObject eObject, genericity.language.gbind.grammar.GbindPlaceholder placeholder, int count, java.util.List<genericity.language.gbind.grammar.GbindFormattingElement> foundFormattingElements, java.util.List<genericity.language.gbind.mopp.GbindLayoutInformation> layoutInformations) { org.eclipse.emf.ecore.EStructuralFeature feature = placeholder.getFeature(); if (feature instanceof org.eclipse.emf.ecore.EAttribute) { printAttribute(eObject, (org.eclipse.emf.ecore.EAttribute) feature, placeholder, count, foundFormattingElements, layoutInformations); } else { printReference(eObject, (org.eclipse.emf.ecore.EReference) feature, placeholder, count, foundFormattingElements, layoutInformations); } } public void printAttribute(org.eclipse.emf.ecore.EObject eObject, org.eclipse.emf.ecore.EAttribute attribute, genericity.language.gbind.grammar.GbindPlaceholder placeholder, int index, java.util.List<genericity.language.gbind.grammar.GbindFormattingElement> foundFormattingElements, java.util.List<genericity.language.gbind.mopp.GbindLayoutInformation> layoutInformations) { String result = null; Object attributeValue = genericity.language.gbind.util.GbindEObjectUtil.getFeatureValue(eObject, attribute, index); genericity.language.gbind.mopp.GbindLayoutInformation attributeLayout = getLayoutInformation(layoutInformations, placeholder, attributeValue, eObject); String visibleTokenText = getVisibleTokenText(attributeLayout); // if there is text for the attribute we use it if (visibleTokenText != null) { result = visibleTokenText; } if (result == null) { // if no text is available, the attribute is deresolved to obtain its textual // representation genericity.language.gbind.IGbindTokenResolver tokenResolver = tokenResolverFactory.createTokenResolver(placeholder.getTokenName()); tokenResolver.setOptions(getOptions()); String deResolvedValue = tokenResolver.deResolve(attributeValue, attribute, eObject); result = deResolvedValue; } if (result != null && !"".equals(result)) { printFormattingElements(eObject, foundFormattingElements, layoutInformations, attributeLayout); // write result to the output stream tokenOutputStream.add(new PrintToken(result, placeholder.getTokenName(), eObject)); } } public void printBooleanTerminal(org.eclipse.emf.ecore.EObject eObject, genericity.language.gbind.grammar.GbindBooleanTerminal booleanTerminal, int index, java.util.List<genericity.language.gbind.grammar.GbindFormattingElement> foundFormattingElements, java.util.List<genericity.language.gbind.mopp.GbindLayoutInformation> layoutInformations) { org.eclipse.emf.ecore.EAttribute attribute = booleanTerminal.getAttribute(); String result = null; Object attributeValue = genericity.language.gbind.util.GbindEObjectUtil.getFeatureValue(eObject, attribute, index); genericity.language.gbind.mopp.GbindLayoutInformation attributeLayout = getLayoutInformation(layoutInformations, booleanTerminal, attributeValue, eObject); String visibleTokenText = getVisibleTokenText(attributeLayout); // if there is text for the attribute we use it if (visibleTokenText != null) { result = visibleTokenText; } if (result == null) { // if no text is available, the boolean attribute is converted to its textual // representation using the literals of the boolean terminal if (Boolean.TRUE.equals(attributeValue)) { result = booleanTerminal.getTrueLiteral(); } else { result = booleanTerminal.getFalseLiteral(); } } if (result != null && !"".equals(result)) { printFormattingElements(eObject, foundFormattingElements, layoutInformations, attributeLayout); // write result to the output stream tokenOutputStream.add(new PrintToken(result, "'" + genericity.language.gbind.util.GbindStringUtil.escapeToANTLRKeyword(result) + "'", eObject)); } } public void printEnumerationTerminal(org.eclipse.emf.ecore.EObject eObject, genericity.language.gbind.grammar.GbindEnumerationTerminal enumTerminal, int index, java.util.List<genericity.language.gbind.grammar.GbindFormattingElement> foundFormattingElements, java.util.List<genericity.language.gbind.mopp.GbindLayoutInformation> layoutInformations) { org.eclipse.emf.ecore.EAttribute attribute = enumTerminal.getAttribute(); String result = null; Object attributeValue = genericity.language.gbind.util.GbindEObjectUtil.getFeatureValue(eObject, attribute, index); genericity.language.gbind.mopp.GbindLayoutInformation attributeLayout = getLayoutInformation(layoutInformations, enumTerminal, attributeValue, eObject); String visibleTokenText = getVisibleTokenText(attributeLayout); // if there is text for the attribute we use it if (visibleTokenText != null) { result = visibleTokenText; } if (result == null) { // if no text is available, the enumeration attribute is converted to its textual // representation using the literals of the enumeration terminal assert attributeValue instanceof org.eclipse.emf.common.util.Enumerator; result = enumTerminal.getText(((org.eclipse.emf.common.util.Enumerator) attributeValue).getName()); } if (result != null && !"".equals(result)) { printFormattingElements(eObject, foundFormattingElements, layoutInformations, attributeLayout); // write result to the output stream tokenOutputStream.add(new PrintToken(result, "'" + genericity.language.gbind.util.GbindStringUtil.escapeToANTLRKeyword(result) + "'", eObject)); } } public void printContainedObject(org.eclipse.emf.ecore.EObject eObject, genericity.language.gbind.grammar.GbindContainment containment, int index, java.util.List<genericity.language.gbind.grammar.GbindFormattingElement> foundFormattingElements, java.util.List<genericity.language.gbind.mopp.GbindLayoutInformation> layoutInformations) { org.eclipse.emf.ecore.EStructuralFeature reference = containment.getFeature(); Object o = genericity.language.gbind.util.GbindEObjectUtil.getFeatureValue(eObject, reference, index); // save current number of tabs to restore them after printing the contained object int oldTabsBeforeCurrentObject = tabsBeforeCurrentObject; int oldCurrentTabs = currentTabs; // use current number of tabs to indent contained object. we do not directly set // 'tabsBeforeCurrentObject' because the first element of the new object must be // printed with the old number of tabs. startedPrintingContainedObject = false; currentTabs = 0; doPrint((org.eclipse.emf.ecore.EObject) o, foundFormattingElements); // restore number of tabs after printing the contained object tabsBeforeCurrentObject = oldTabsBeforeCurrentObject; currentTabs = oldCurrentTabs; } public void printFormattingElements(org.eclipse.emf.ecore.EObject eObject, java.util.List<genericity.language.gbind.grammar.GbindFormattingElement> foundFormattingElements, java.util.List<genericity.language.gbind.mopp.GbindLayoutInformation> layoutInformations, genericity.language.gbind.mopp.GbindLayoutInformation layoutInformation) { String hiddenTokenText = getHiddenTokenText(layoutInformation); if (hiddenTokenText != null) { // removed used information if (layoutInformations != null) { layoutInformations.remove(layoutInformation); } tokenOutputStream.add(new PrintToken(hiddenTokenText, null, eObject)); foundFormattingElements.clear(); startedPrintingObject = false; setTabsBeforeCurrentObject(0); return; } int printedTabs = 0; if (foundFormattingElements.size() > 0) { for (genericity.language.gbind.grammar.GbindFormattingElement foundFormattingElement : foundFormattingElements) { if (foundFormattingElement instanceof genericity.language.gbind.grammar.GbindWhiteSpace) { int amount = ((genericity.language.gbind.grammar.GbindWhiteSpace) foundFormattingElement).getAmount(); for (int i = 0; i < amount; i++) { tokenOutputStream.add(createSpaceToken(eObject)); } } if (foundFormattingElement instanceof genericity.language.gbind.grammar.GbindLineBreak) { currentTabs = ((genericity.language.gbind.grammar.GbindLineBreak) foundFormattingElement).getTabs(); printedTabs += currentTabs; tokenOutputStream.add(createNewLineToken(eObject)); for (int i = 0; i < tabsBeforeCurrentObject + currentTabs; i++) { tokenOutputStream.add(createTabToken(eObject)); } } } foundFormattingElements.clear(); startedPrintingObject = false; } else { if (startedPrintingObject) { // if no elements have been printed yet, we do not add the default token space, // because spaces before the first element are not desired. startedPrintingObject = false; } else { if (!handleTokenSpaceAutomatically) { tokenOutputStream.add(new PrintToken(getWhiteSpaceString(tokenSpace), null, eObject)); } } } // after printing the first element, we can use the new number of tabs. setTabsBeforeCurrentObject(printedTabs); } private void setTabsBeforeCurrentObject(int tabs) { if (startedPrintingContainedObject) { return; } tabsBeforeCurrentObject = tabsBeforeCurrentObject + tabs; startedPrintingContainedObject = true; } @SuppressWarnings("unchecked") public void printReference(org.eclipse.emf.ecore.EObject eObject, org.eclipse.emf.ecore.EReference reference, genericity.language.gbind.grammar.GbindPlaceholder placeholder, int index, java.util.List<genericity.language.gbind.grammar.GbindFormattingElement> foundFormattingElements, java.util.List<genericity.language.gbind.mopp.GbindLayoutInformation> layoutInformations) { String tokenName = placeholder.getTokenName(); Object referencedObject = genericity.language.gbind.util.GbindEObjectUtil.getFeatureValue(eObject, reference, index, false); // first add layout before the reference genericity.language.gbind.mopp.GbindLayoutInformation referenceLayout = getLayoutInformation(layoutInformations, placeholder, referencedObject, eObject); printFormattingElements(eObject, foundFormattingElements, layoutInformations, referenceLayout); // proxy objects must be printed differently String deresolvedReference = null; if (referencedObject instanceof org.eclipse.emf.ecore.EObject) { org.eclipse.emf.ecore.EObject eObjectToDeResolve = (org.eclipse.emf.ecore.EObject) referencedObject; if (eObjectToDeResolve.eIsProxy()) { deresolvedReference = ((org.eclipse.emf.ecore.InternalEObject) eObjectToDeResolve).eProxyURI().fragment(); // If the proxy was created by EMFText, we can try to recover the identifier from // the proxy URI if (deresolvedReference != null && deresolvedReference.startsWith(genericity.language.gbind.IGbindContextDependentURIFragment.INTERNAL_URI_FRAGMENT_PREFIX)) { deresolvedReference = deresolvedReference.substring(genericity.language.gbind.IGbindContextDependentURIFragment.INTERNAL_URI_FRAGMENT_PREFIX.length()); deresolvedReference = deresolvedReference.substring(deresolvedReference.indexOf("_") + 1); } } } if (deresolvedReference == null) { // NC-References must always be printed by deresolving the reference. We cannot // use the visible token information, because deresolving usually depends on // attribute values of the referenced object instead of the object itself. @SuppressWarnings("rawtypes") genericity.language.gbind.IGbindReferenceResolver referenceResolver = getReferenceResolverSwitch().getResolver(reference); referenceResolver.setOptions(getOptions()); deresolvedReference = referenceResolver.deResolve((org.eclipse.emf.ecore.EObject) referencedObject, eObject, reference); } genericity.language.gbind.IGbindTokenResolver tokenResolver = tokenResolverFactory.createTokenResolver(tokenName); tokenResolver.setOptions(getOptions()); String deresolvedToken = tokenResolver.deResolve(deresolvedReference, reference, eObject); // write result to output stream tokenOutputStream.add(new PrintToken(deresolvedToken, tokenName, eObject)); } @SuppressWarnings("unchecked") public PrintCountingMap initializePrintCountingMap(org.eclipse.emf.ecore.EObject eObject) { // The PrintCountingMap contains a mapping from feature names to the number of // remaining elements that still need to be printed. The map is initialized with // the number of elements stored in each structural feature. For lists this is the // list size. For non-multiple features it is either 1 (if the feature is set) or // 0 (if the feature is null). PrintCountingMap printCountingMap = new PrintCountingMap(); java.util.List<org.eclipse.emf.ecore.EStructuralFeature> features = eObject.eClass().getEAllStructuralFeatures(); for (org.eclipse.emf.ecore.EStructuralFeature feature : features) { // We get the feature value without resolving it, because resolving is not // required to count the number of elements that are referenced by the feature. // Moreover, triggering reference resolving is not desired here, because we'd also // like to print models that contain unresolved references. Object featureValue = eObject.eGet(feature, false); if (featureValue != null) { if (featureValue instanceof java.util.List<?>) { printCountingMap.setFeatureValues(feature.getName(), (java.util.List<Object>) featureValue); } else { printCountingMap.setFeatureValues(feature.getName(), java.util.Collections.singletonList(featureValue)); } } else { printCountingMap.setFeatureValues(feature.getName(), null); } } return printCountingMap; } public java.util.Map<?,?> getOptions() { return options; } public void setOptions(java.util.Map<?,?> options) { this.options = options; } public String getEncoding() { return encoding; } public void setEncoding(String encoding) { if (encoding != null) { this.encoding = encoding; } } public genericity.language.gbind.IGbindTextResource getResource() { return resource; } protected genericity.language.gbind.mopp.GbindReferenceResolverSwitch getReferenceResolverSwitch() { return (genericity.language.gbind.mopp.GbindReferenceResolverSwitch) new genericity.language.gbind.mopp.GbindMetaInformation().getReferenceResolverSwitch(); } protected void addWarningToResource(final String errorMessage, org.eclipse.emf.ecore.EObject cause) { genericity.language.gbind.IGbindTextResource resource = getResource(); if (resource == null) { // the resource can be null if the printer is used stand alone return; } resource.addProblem(new genericity.language.gbind.mopp.GbindProblem(errorMessage, genericity.language.gbind.GbindEProblemType.PRINT_PROBLEM, genericity.language.gbind.GbindEProblemSeverity.WARNING), cause); } protected genericity.language.gbind.mopp.GbindLayoutInformationAdapter getLayoutInformationAdapter(org.eclipse.emf.ecore.EObject element) { for (org.eclipse.emf.common.notify.Adapter adapter : element.eAdapters()) { if (adapter instanceof genericity.language.gbind.mopp.GbindLayoutInformationAdapter) { return (genericity.language.gbind.mopp.GbindLayoutInformationAdapter) adapter; } } genericity.language.gbind.mopp.GbindLayoutInformationAdapter newAdapter = new genericity.language.gbind.mopp.GbindLayoutInformationAdapter(); element.eAdapters().add(newAdapter); return newAdapter; } private genericity.language.gbind.mopp.GbindLayoutInformation getLayoutInformation(java.util.List<genericity.language.gbind.mopp.GbindLayoutInformation> layoutInformations, genericity.language.gbind.grammar.GbindSyntaxElement syntaxElement, Object object, org.eclipse.emf.ecore.EObject container) { for (genericity.language.gbind.mopp.GbindLayoutInformation layoutInformation : layoutInformations) { if (syntaxElement == layoutInformation.getSyntaxElement()) { if (object == null) { return layoutInformation; } // The layout information adapter must only try to resolve the object it refers // to, if we compare with a non-proxy object. If we're printing a resource that // contains proxy objects, resolving must not be triggered. boolean isNoProxy = true; if (object instanceof org.eclipse.emf.ecore.EObject) { org.eclipse.emf.ecore.EObject eObject = (org.eclipse.emf.ecore.EObject) object; isNoProxy = !eObject.eIsProxy(); } if (isSame(object, layoutInformation.getObject(container, isNoProxy))) { return layoutInformation; } } } return null; } public java.util.List<genericity.language.gbind.mopp.GbindLayoutInformation> getCopyOfLayoutInformation(org.eclipse.emf.ecore.EObject eObject) { genericity.language.gbind.mopp.GbindLayoutInformationAdapter layoutInformationAdapter = getLayoutInformationAdapter(eObject); java.util.List<genericity.language.gbind.mopp.GbindLayoutInformation> originalLayoutInformations = layoutInformationAdapter.getLayoutInformations(); // create a copy of the original list of layout information object in order to be // able to remove used informations during printing java.util.List<genericity.language.gbind.mopp.GbindLayoutInformation> layoutInformations = new java.util.ArrayList<genericity.language.gbind.mopp.GbindLayoutInformation>(originalLayoutInformations.size()); layoutInformations.addAll(originalLayoutInformations); return layoutInformations; } private String getHiddenTokenText(genericity.language.gbind.mopp.GbindLayoutInformation layoutInformation) { if (layoutInformation != null) { return layoutInformation.getHiddenTokenText(); } else { return null; } } private String getVisibleTokenText(genericity.language.gbind.mopp.GbindLayoutInformation layoutInformation) { if (layoutInformation != null) { return layoutInformation.getVisibleTokenText(); } else { return null; } } protected String getWhiteSpaceString(int count) { return getRepeatingString(count, ' '); } private String getRepeatingString(int count, char character) { StringBuffer result = new StringBuffer(); for (int i = 0; i < count; i++) { result.append(character); } return result.toString(); } public void setHandleTokenSpaceAutomatically(boolean handleTokenSpaceAutomatically) { this.handleTokenSpaceAutomatically = handleTokenSpaceAutomatically; } public void setTokenSpace(int tokenSpace) { this.tokenSpace = tokenSpace; } /** * Prints the current tokenOutputStream to the given writer (as it is). */ public void printBasic(java.io.PrintWriter writer) throws java.io.IOException { for (PrintToken nextToken : tokenOutputStream) { writer.write(nextToken.getText()); } } /** * Prints the current tokenOutputStream to the given writer. * * This methods implements smart whitespace printing. It does so by writing output * to a token stream instead of printing the raw token text to a PrintWriter. * Tokens in this stream hold both the text and the type of the token (i.e., its * name). * * To decide where whitespace is needed, sequences of successive tokens are * searched that can be printed without separating whitespace. To determine such * groups we start with two successive non-whitespace tokens, concatenate their * text and use the generated ANTLR lexer to split the text. If the resulting * token sequence of the concatenated text is exactly the same as the one that is * to be printed, no whitespace is needed. The tokens in the sequence are checked * both regarding their type and their text. If two tokens successfully form a * group a third one is added and so on. */ public void printSmart(java.io.PrintWriter writer) throws java.io.IOException { // stores the text of the current group of tokens. this text is given to the lexer // to check whether it can be correctly scanned. StringBuilder currentBlock = new StringBuilder(); // stores the index of the first token of the current group. int currentBlockStart = 0; // stores the text that was already successfully checked (i.e., is can be scanned // correctly and can thus be printed). String validBlock = ""; char lastCharWritten = ' '; for (int i = 0; i < tokenOutputStream.size(); i++) { PrintToken tokenI = tokenOutputStream.get(i); currentBlock.append(tokenI.getText()); // if declared or preserved whitespace is found - print block if (tokenI.getTokenName() == null) { char[] charArray = currentBlock.toString().toCharArray(); writer.write(charArray); if (charArray.length > 0) { lastCharWritten = charArray[charArray.length - 1]; } // reset all values currentBlock = new StringBuilder(); currentBlockStart = i + 1; validBlock = ""; continue; } // now check whether the current block can be scanned genericity.language.gbind.IGbindTextScanner scanner = new genericity.language.gbind.mopp.GbindMetaInformation().createLexer(); scanner.setText(currentBlock.toString()); // retrieve all tokens from scanner and add them to list 'tempTokens' java.util.List<genericity.language.gbind.IGbindTextToken> tempTokens = new java.util.ArrayList<genericity.language.gbind.IGbindTextToken>(); genericity.language.gbind.IGbindTextToken nextToken = scanner.getNextToken(); while (nextToken != null && nextToken.getText() != null) { tempTokens.add(nextToken); nextToken = scanner.getNextToken(); } boolean sequenceIsValid = true; // check whether the current block was scanned to the same token sequence for (int t = 0; t < tempTokens.size(); t++) { PrintToken printTokenT = tokenOutputStream.get(currentBlockStart + t); genericity.language.gbind.IGbindTextToken tempToken = tempTokens.get(t); if (!tempToken.getText().equals(printTokenT.getText())) { sequenceIsValid = false; break; } String commonTokenName = tempToken.getName(); String printTokenName = printTokenT.getTokenName(); if (printTokenName.length() > 2 && printTokenName.startsWith("'") && printTokenName.endsWith("'")) { printTokenName = printTokenName.substring(1, printTokenName.length() - 1); } if (!commonTokenName.equals(printTokenName)) { sequenceIsValid = false; break; } } if (sequenceIsValid) { // sequence is still valid, try adding one more token in the next iteration of the // loop validBlock += tokenI.getText(); } else { // sequence is not valid, must print whitespace to separate tokens // print text that is valid so far char[] charArray = validBlock.toString().toCharArray(); writer.write(charArray); if (charArray.length > 0) { lastCharWritten = charArray[charArray.length - 1]; } // print separating whitespace // if no whitespace (or tab or linebreak) is already there if (lastCharWritten != ' ' && lastCharWritten != '\t' && lastCharWritten != '\n' && lastCharWritten != '\r') { lastCharWritten = ' '; writer.write(lastCharWritten); } // add current token as initial value for next iteration currentBlock = new StringBuilder(tokenI.getText()); currentBlockStart = i; validBlock = tokenI.getText(); } } // flush remaining valid text to writer writer.write(validBlock); } private boolean isSame(Object o1, Object o2) { if (o1 instanceof String || o1 instanceof Integer || o1 instanceof Long || o1 instanceof Byte || o1 instanceof Short || o1 instanceof Float || o2 instanceof Double) { return o1.equals(o2); } return o1 == o2; } protected java.util.List<Class<?>> getAllowedTypes(genericity.language.gbind.grammar.GbindTerminal terminal) { java.util.List<Class<?>> allowedTypes = new java.util.ArrayList<Class<?>>(); allowedTypes.add(terminal.getFeature().getEType().getInstanceClass()); if (terminal instanceof genericity.language.gbind.grammar.GbindContainment) { genericity.language.gbind.grammar.GbindContainment printingContainment = (genericity.language.gbind.grammar.GbindContainment) terminal; org.eclipse.emf.ecore.EClass[] typeRestrictions = printingContainment.getAllowedTypes(); if (typeRestrictions != null && typeRestrictions.length > 0) { allowedTypes.clear(); for (org.eclipse.emf.ecore.EClass eClass : typeRestrictions) { allowedTypes.add(eClass.getInstanceClass()); } } } return allowedTypes; } protected PrintToken createSpaceToken(org.eclipse.emf.ecore.EObject container) { return new PrintToken(" ", null, container); } protected PrintToken createTabToken(org.eclipse.emf.ecore.EObject container) { return new PrintToken("\t", null, container); } protected PrintToken createNewLineToken(org.eclipse.emf.ecore.EObject container) { return new PrintToken(NEW_LINE, null, container); } }
epl-1.0
elucash/eclipse-oxygen
org.eclipse.jdt.ui/src/org/eclipse/jdt/internal/ui/text/CombinedWordRule.java
10440
/******************************************************************************* * Copyright (c) 2000, 2011 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.ui.text; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.eclipse.core.runtime.Assert; import org.eclipse.jface.text.rules.ICharacterScanner; import org.eclipse.jface.text.rules.IRule; import org.eclipse.jface.text.rules.IToken; import org.eclipse.jface.text.rules.IWordDetector; import org.eclipse.jface.text.rules.Token; /** * An implementation of <code>IRule</code> capable of detecting words. * <p> * Word rules also allow for the association of tokens with specific words. * That is, not only can the rule be used to provide tokens for exact matches, * but also for the generalized notion of a word in the context in which it is used. * A word rules uses a word detector to determine what a word is.</p> * <p> * This word rule allows a word detector to be shared among different word matchers. * Its up to the word matchers to decide if a word matches and, in this a case, which * token is associated with that word. * </p> * * @see IWordDetector * @since 3.0 */ public class CombinedWordRule implements IRule { /** * Word matcher, that associates matched words with tokens. */ public static class WordMatcher { /** The table of predefined words and token for this matcher */ private Map<CharacterBuffer, IToken> fWords= new HashMap<>(); /** * Adds a word and the token to be returned if it is detected. * * @param word the word this rule will search for, may not be <code>null</code> * @param token the token to be returned if the word has been found, may not be <code>null</code> */ public void addWord(String word, IToken token) { Assert.isNotNull(word); Assert.isNotNull(token); fWords.put(new CharacterBuffer(word), token); } /** * Returns the token associated to the given word and the scanner state. * * @param scanner the scanner * @param word the word * @return the token or <code>null</code> if none is associated by this matcher */ public IToken evaluate(ICharacterScanner scanner, CharacterBuffer word) { IToken token= fWords.get(word); if (token != null) return token; return Token.UNDEFINED; } /** * Removes all words. */ public void clearWords() { fWords.clear(); } } /** * Character buffer, mutable <b>or</b> suitable for use as key in hash maps. */ public static class CharacterBuffer { /** Buffer content */ private char[] fContent; /** Buffer content size */ private int fLength= 0; /** Is hash code cached? */ private boolean fIsHashCached= false; /** The hash code */ private int fHashCode; /** * Initialize with the given capacity. * * @param capacity the initial capacity */ public CharacterBuffer(int capacity) { fContent= new char[capacity]; } /** * Initialize with the given content. * * @param content the initial content */ public CharacterBuffer(String content) { fContent= content.toCharArray(); fLength= content.length(); } /** * Empties this buffer. */ public void clear() { fIsHashCached= false; fLength= 0; } /** * Appends the given character to the buffer. * * @param c the character */ public void append(char c) { fIsHashCached= false; if (fLength == fContent.length) { char[] old= fContent; fContent= new char[old.length << 1]; System.arraycopy(old, 0, fContent, 0, old.length); } fContent[fLength++]= c; } /** * Returns the length of the content. * * @return the length */ public int length() { return fLength; } /** * Returns the content as string. * * @return the content */ @Override public String toString() { return new String(fContent, 0, fLength); } /** * Returns the character at the given position. * * @param i the position * @return the character at position <code>i</code> */ public char charAt(int i) { return fContent[i]; } /* * @see java.lang.Object#hashCode() */ @Override public int hashCode() { if (fIsHashCached) return fHashCode; int hash= 0; for (int i= 0, n= fLength; i < n; i++) hash= 29*hash + fContent[i]; fHashCode= hash; fIsHashCached= true; return hash; } /* * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (obj == this) return true; if (!(obj instanceof CharacterBuffer)) return false; CharacterBuffer buffer= (CharacterBuffer) obj; int length= buffer.length(); if (length != fLength) return false; for (int i= 0; i < length; i++) if (buffer.charAt(i) != fContent[i]) return false; return true; } /** * Is the content equal to the given string? * * @param string the string * @return <code>true</code> iff the content is the same character sequence as in the string */ public boolean equals(String string) { int length= string.length(); if (length != fLength) return false; for (int i= 0; i < length; i++) if (string.charAt(i) != fContent[i]) return false; return true; } } /** Internal setting for the uninitialized column constraint */ private static final int UNDEFINED= -1; /** The word detector used by this rule */ private IWordDetector fDetector; /** The default token to be returned on success and if nothing else has been specified. */ private IToken fDefaultToken; /** The column constraint */ private int fColumn= UNDEFINED; /** Buffer used for pattern detection */ private CharacterBuffer fBuffer= new CharacterBuffer(16); /** List of word matchers */ private List<WordMatcher> fMatchers= new ArrayList<>(); /** * Creates a rule which, with the help of an word detector, will return the token * associated with the detected word. If no token has been associated, the scanner * will be rolled back and an undefined token will be returned in order to allow * any subsequent rules to analyze the characters. * * @param detector the word detector to be used by this rule, may not be <code>null</code> * * @see WordMatcher#addWord(String, IToken) */ public CombinedWordRule(IWordDetector detector) { this(detector, null, Token.UNDEFINED); } /** * Creates a rule which, with the help of an word detector, will return the token * associated with the detected word. If no token has been associated, the * specified default token will be returned. * * @param detector the word detector to be used by this rule, may not be <code>null</code> * @param defaultToken the default token to be returned on success * if nothing else is specified, may not be <code>null</code> * * @see WordMatcher#addWord(String, IToken) */ public CombinedWordRule(IWordDetector detector, IToken defaultToken) { this(detector, null, defaultToken); } /** * Creates a rule which, with the help of an word detector, will return the token * associated with the detected word. If no token has been associated, the scanner * will be rolled back and an undefined token will be returned in order to allow * any subsequent rules to analyze the characters. * * @param detector the word detector to be used by this rule, may not be <code>null</code> * @param matcher the initial word matcher * * @see WordMatcher#addWord(String, IToken) */ public CombinedWordRule(IWordDetector detector, WordMatcher matcher) { this(detector, matcher, Token.UNDEFINED); } /** * Creates a rule which, with the help of an word detector, will return the token * associated with the detected word. If no token has been associated, the * specified default token will be returned. * * @param detector the word detector to be used by this rule, may not be <code>null</code> * @param matcher the initial word matcher * @param defaultToken the default token to be returned on success * if nothing else is specified, may not be <code>null</code> * * @see WordMatcher#addWord(String, IToken) */ public CombinedWordRule(IWordDetector detector, WordMatcher matcher, IToken defaultToken) { Assert.isNotNull(detector); Assert.isNotNull(defaultToken); fDetector= detector; fDefaultToken= defaultToken; if (matcher != null) addWordMatcher(matcher); } /** * Adds the given matcher. * * @param matcher the matcher */ public void addWordMatcher(WordMatcher matcher) { fMatchers.add(matcher); } /** * Sets a column constraint for this rule. If set, the rule's token * will only be returned if the pattern is detected starting at the * specified column. If the column is smaller then 0, the column * constraint is considered removed. * * @param column the column in which the pattern starts */ public void setColumnConstraint(int column) { if (column < 0) column= UNDEFINED; fColumn= column; } /* * @see IRule#evaluate(ICharacterScanner) */ @Override public IToken evaluate(ICharacterScanner scanner) { int c= scanner.read(); if (fDetector.isWordStart((char) c)) { if (fColumn == UNDEFINED || (fColumn == scanner.getColumn() - 1)) { fBuffer.clear(); do { fBuffer.append((char) c); c= scanner.read(); } while (c != ICharacterScanner.EOF && fDetector.isWordPart((char) c)); scanner.unread(); for (int i= 0, n= fMatchers.size(); i < n; i++) { IToken token= fMatchers.get(i).evaluate(scanner, fBuffer); if (!token.isUndefined()) return token; } if (fDefaultToken.isUndefined()) unreadBuffer(scanner); return fDefaultToken; } } scanner.unread(); return Token.UNDEFINED; } /** * Returns the characters in the buffer to the scanner. * * @param scanner the scanner to be used */ private void unreadBuffer(ICharacterScanner scanner) { for (int i= fBuffer.length() - 1; i >= 0; i--) scanner.unread(); } }
epl-1.0
hellonico/wife
src/com/prowidesoftware/swift/model/field/Field87E.java
8466
/* * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * */ package com.prowidesoftware.swift.model.field; import java.io.Serializable; import java.util.List; import java.util.ArrayList; import com.prowidesoftware.swift.model.BIC; import org.apache.commons.lang.StringUtils; import com.prowidesoftware.swift.model.*; import com.prowidesoftware.swift.utils.SwiftFormatUtils; /** * Field 87E<br /><br /> * * validation pattern: 4!a$[/&lt;DC&gt;][/34x][$]$&lt;SWIFTBIC&gt;|&lt;NON-SWIFTBIC&gt;<br /> * parser pattern: S$[/c][/S]S<br /> * components pattern: SSSB<br /> * * <h1>Components Data types</h1> * <ul> * <li>component1: <code>String</code></li> * <li>component2: <code>String</code></li> * <li>component3: <code>String</code></li> * <li>component4: <code>BIC</code></li> * </ul> * * <em>NOTE: this source code has been generated from template</em> * * @author www.prowidesoftware.com * */ @Deprecated @SuppressWarnings("unused") public class Field87E extends Field implements Serializable , BICContainer { private static final long serialVersionUID = 1L; /** * Constant with the field name 87E */ public static final String NAME = "87E"; /** * same as NAME, intended to be clear when using static imports */ public static final String F_87E = "87E"; public static final String PARSER_PATTERN ="S$[/c][/S]S"; public static final String COMPONENTS_PATTERN = "SSSB"; /** * Create a Tag with this field name and the given value. * Shorthand for <code>new Tag(NAME, value)</code> * @see #NAME * @since 7.5 */ public static Tag tag(final String value) { return new Tag(NAME, value); } /** * Create a Tag with this field name and an empty string as value * Shorthand for <code>new Tag(NAME, "")</code> * @see #NAME * @since 7.5 */ public static Tag emptyTag() { return new Tag(NAME, ""); } /** * Default constructor */ public Field87E() { super(4); } /** * Creates the field parsing the parameter value into fields' components * @param value */ public Field87E(String value) { this(); throw new org.apache.commons.lang.NotImplementedException("Missing parserPattern in Field.vm : S$[/c][/S]S"); } /** * Serializes the fields' components into the single string value (SWIFT format) */ @Override public String getValue() { final StringBuilder result = new StringBuilder(); //FIXME serialization // @NotImplemented int notImplemented; return result.toString(); } /** * Get the component1 * @return the component1 */ public String getComponent1() { return getComponent(1); } /** * Same as getComponent(1) */ @Deprecated public java.lang.String getComponent1AsString() { return getComponent(1); } /** * Set the component1. * @param component1 the component1 to set */ public Field87E setComponent1(String component1) { setComponent(1, component1); return this; } /** * Get the component2 * @return the component2 */ public String getComponent2() { return getComponent(2); } /** * Same as getComponent(2) */ @Deprecated public java.lang.String getComponent2AsString() { return getComponent(2); } /** * Set the component2. * @param component2 the component2 to set */ public Field87E setComponent2(String component2) { setComponent(2, component2); return this; } /** * Get the component3 * @return the component3 */ public String getComponent3() { return getComponent(3); } /** * Same as getComponent(3) */ @Deprecated public java.lang.String getComponent3AsString() { return getComponent(3); } /** * Set the component3. * @param component3 the component3 to set */ public Field87E setComponent3(String component3) { setComponent(3, component3); return this; } /** * Get the component4 * @return the component4 */ public String getComponent4() { return getComponent(4); } /** * Get the component4 as BIC * @return the component4 converted to BIC or <code>null</code> if cannot be converted */ public com.prowidesoftware.swift.model.BIC getComponent4AsBIC() { return SwiftFormatUtils.getBIC(getComponent(4)); } /** * Set the component4. * @param component4 the component4 to set */ public Field87E setComponent4(String component4) { setComponent(4, component4); return this; } /** * Set the component4. * @param component4 the BIC with the component4 content to set */ public Field87E setComponent4(com.prowidesoftware.swift.model.BIC component4) { setComponent(4, SwiftFormatUtils.getBIC(component4)); return this; } public List<BIC> bics () { final List<BIC> result = new ArrayList<BIC>(); result.add(SwiftFormatUtils.getBIC(getComponent(4))); return result; } public List<String> bicStrings () { final List<String> result = new ArrayList<String>(); result.add(getComponent(4)); return result; } /** * Given a component number it returns true if the component is optional, * regardless of the field being mandatory in a particular message.<br /> * Being the field's value conformed by a composition of one or several * internal component values, the field may be present in a message with * a proper value but with some of its internal components not set. * * @param component component number, first component of a field is referenced as 1 * @return true if the component is optional for this field, false otherwise */ @Override public boolean isOptional(int component) { if (component == 2) { return true; } if (component == 3) { return true; } return false; } /** * Returns true if the field is a GENERIC FIELD as specified by the standard. * * @return true if the field is generic, false otherwise */ @Override public boolean isGeneric() { return false; } public String componentsPattern() { return COMPONENTS_PATTERN; } public String parserPattern() { return PARSER_PATTERN; } /** * @deprecated use constant Field87E */ @Override public String getName() { return NAME; } /** * Get the first occurrence form the tag list or null if not found. * @returns null if not found o block is null or empty * @param block may be null or empty */ public static Field87E get(final SwiftTagListBlock block) { if (block == null || block.isEmpty()) { return null; } return (Field87E) block.getFieldByName(NAME); } /** * Get the first instance of Field87E in the given message. * @param msg may be empty or null * @returns null if not found or msg is empty or null * @see */ public static Field87E get(final SwiftMessage msg) { if (msg == null || msg.getBlock4()==null || msg.getBlock4().isEmpty()) return null; return get(msg.getBlock4()); } /** * Get a list of all occurrences of the field Field87E in the given message * an empty list is returned if none found. * @param msg may be empty or null in which case an empty list is returned * @see */ public static java.util.List<Field87E> getAll(final SwiftMessage msg) { if (msg == null || msg.getBlock4()==null || msg.getBlock4().isEmpty()) return null; return getAll(msg.getBlock4()); } /** * Get a list of all occurrences of the field Field87E from the given block * an empty list is returned if none found. * * @param block may be empty or null in which case an empty list is returned */ public static java.util.List<Field87E> getAll(final SwiftTagListBlock block) { if (block == null || block.isEmpty()) { return null; } final Field[] arr = block.getFieldsByName(NAME); if (arr != null && arr.length>0) { final java.util.ArrayList<Field87E> result = new java.util.ArrayList<Field87E>(arr.length); for (final Field f : arr) { result.add((Field87E) f); } return result; } return java.util.Collections.emptyList(); } }
epl-1.0
FraunhoferESK/ernest-eclipse-integration
de.fraunhofer.esk.ernest.core.analysismodel.editor/src/ernest/presentation/AnalysisEditorPlugin.java
2448
/******************************************************************************* * Copyright (c) 2015 Fraunhofer Institute for Embedded Systems and * Communication Technologies ESK * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * This file is part of ERNEST. * * Contributors: * Fraunhofer ESK - initial API and implementation *******************************************************************************/ package ernest.presentation; import org.eclipse.emf.common.EMFPlugin; import org.eclipse.emf.common.ui.EclipseUIPlugin; import org.eclipse.emf.common.util.ResourceLocator; /** * This is the central singleton for the Analysis editor plugin. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public final class AnalysisEditorPlugin extends EMFPlugin { /** * Keep track of the singleton. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public static final AnalysisEditorPlugin INSTANCE = new AnalysisEditorPlugin(); /** * Keep track of the singleton. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private static Implementation plugin; /** * Create the instance. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public AnalysisEditorPlugin() { super (new ResourceLocator [] { }); } /** * Returns the singleton instance of the Eclipse plugin. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the singleton instance. * @generated */ @Override public ResourceLocator getPluginResourceLocator() { return plugin; } /** * Returns the singleton instance of the Eclipse plugin. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the singleton instance. * @generated */ public static Implementation getPlugin() { return plugin; } /** * The actual implementation of the Eclipse <b>Plugin</b>. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public static class Implementation extends EclipseUIPlugin { /** * Creates an instance. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Implementation() { super(); // Remember the static instance. // plugin = this; } } }
epl-1.0
kopl/SPLevo
JaMoPPCartridge/org.splevo.jamopp.vpm.analyzer.clonedchange.test/src/org/splevo/jamopp/vpm/analyzer/clonedchange/test/ClonedChangeAnalyzerTest.java
4622
/******************************************************************************* * Copyright (c) 2014 * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Christian Busch *******************************************************************************/ package org.splevo.jamopp.vpm.analyzer.clonedchange.test; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.Test; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.CoreMatchers.notNullValue; import static org.hamcrest.CoreMatchers.instanceOf; import org.splevo.jamopp.vpm.analyzer.clonedchange.ClonedChangeAnalyzer; import org.splevo.jamopp.vpm.analyzer.clonedchange.Config; import org.splevo.vpm.analyzer.config.AbstractVPMAnalyzerConfiguration; import org.splevo.vpm.analyzer.config.ChoiceConfiguration; import org.splevo.vpm.analyzer.config.NumericConfiguration; import org.splevo.vpm.analyzer.config.VPMAnalyzerConfigurationSet; /** * Unit tests for the {@link ClonedChangeAnalyzer}. * */ public class ClonedChangeAnalyzerTest { private ClonedChangeAnalyzer analyzer; /** * Initialization before running the tests. */ @Before public void initialize() { analyzer = new ClonedChangeAnalyzer(); } /** * Check that the Analyzer has a name. */ @Test public void testAnalyzerNameSet() { assertThat("Analyzer name", analyzer.getName(), is(notNullValue())); assertThat("Analyzer name", analyzer.getName(), is(not(""))); } /** * Check that the Analyzer's relationship label is set. */ @Test public void testAnalyzerRelationshipLabelSet() { assertThat("Analyzer relationship label", analyzer.getRelationshipLabel(), is(notNullValue())); assertThat("Analyzer relationship label", analyzer.getRelationshipLabel(), is(not(""))); } /** * Check that the analyzer's configuration set contains all needed configurations and their * values are within reasonable limits. */ @Test public void testConfigurations() { VPMAnalyzerConfigurationSet confSet = analyzer.getConfigurations(); assertThat("Analyzer configuration", confSet, is(notNullValue())); checkMinElementThresholdConfig(confSet); checkDetectionTypeConfig(confSet); } private void checkMinElementThresholdConfig(VPMAnalyzerConfigurationSet confSet) { AbstractVPMAnalyzerConfiguration<?> threshConf = confSet.getConfiguration(Config.CONFIG_GROUP_GENERAL, Config.CONFIG_ID_INVOLVED_ELEMENT_THRESHOLD); assertThat("MinElementThresholdConfig", threshConf, is(notNullValue())); assertThat("MinElementThresholdConfig class", threshConf, is(instanceOf(NumericConfiguration.class))); NumericConfiguration numConf = (NumericConfiguration) threshConf; assertThat("ThresholdConfig label", numConf.getLabel(), is(notNullValue())); assertThat("ThresholdConfig label", numConf.getLabel(), is(not(""))); assertThat("ThresholdConfig explanation", numConf.getExplanation(), is(notNullValue())); assertThat("ThresholdConfig explanation", numConf.getExplanation(), is(not(""))); assertTrue("The lower boundary is non negative", numConf.getLowerBoundary() >= 0); } private void checkDetectionTypeConfig(VPMAnalyzerConfigurationSet confSet) { AbstractVPMAnalyzerConfiguration<?> detectionConf = confSet.getConfiguration(Config.CONFIG_GROUP_GENERAL, Config.CONFIG_ID_DETECTION_TYPE); assertThat("DetectionTypeConfig", detectionConf, is(notNullValue())); assertThat("DetectionTypeConfig class", detectionConf, is(instanceOf(ChoiceConfiguration.class))); ChoiceConfiguration choiceConf = (ChoiceConfiguration) detectionConf; assertThat("DetectionTypeConfig label", choiceConf.getLabel(), is(notNullValue())); assertThat("DetectionTypeConfig label", choiceConf.getLabel(), is(not(""))); assertThat("DetectionTypeConfig explanation", choiceConf.getExplanation(), is(notNullValue())); assertThat("DetectionTypeConfig explanation", choiceConf.getExplanation(), is(not(""))); assertThat("DetectionTypeConfig number of choices", choiceConf.getAvailableValues().size(), is(not(0))); } }
epl-1.0
nagyistoce/icafe
src/cafe/image/png/ColorType.java
1997
/** * Copyright (c) 2014-2015 by Wen Yu. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Any modifications to this file must keep this entire header intact. */ package cafe.image.png; import java.util.HashMap; import java.util.Map; /** * Define PNG image color types * * @author Wen Yu, yuwen_66@yahoo.com * @version 1.0 07/29/2013 */ public enum ColorType { // Image color formats GRAY_SCALE(0, "Gray-scale: each pixel is a grayscale sample."), TRUE_COLOR(2, "True-color: each pixel is a R,G,B triple."), INDEX_COLOR(3, "Index-color: each pixel is a palette index; a PLTE chunk must appear."), GRAY_SCALE_WITH_ALPHA(4, "Gray-scale-with-alpha: each pixel is a grayscale sample, followed by an alpha sample."), TRUE_COLOR_WITH_ALPHA(6, "True-color-with-alpha: each pixel is a R,G,B triple, followed by an alpha sample."), UNKNOWN(999, "UNKNOWN"); // We don't know this color format private ColorType(int value, String description) { this.value = value; this.description = description; } public String getDescription() { return this.description; } public int getValue() { return this.value; } @Override public String toString() {return "Image color format: " + getValue() + " - " + description;} public static ColorType fromInt(int value) { ColorType colorType = intMap.get(value); if (colorType == null) return UNKNOWN; return colorType; } private static final Map<Integer, ColorType> intMap = new HashMap<Integer, ColorType>(); static { for(ColorType color : values()) { intMap.put(color.getValue(), color); } } private final String description; private final int value; }
epl-1.0
elucash/eclipse-oxygen
org.eclipse.jdt.ui/src/org/eclipse/jdt/internal/ui/preferences/TypeFilterInputDialog.java
6158
/******************************************************************************* * Copyright (c) 2000, 2016 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.ui.preferences; import java.util.List; import org.eclipse.equinox.bidi.StructuredTextTypeHandlerFactory; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; import org.eclipse.core.runtime.Assert; import org.eclipse.core.runtime.IStatus; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.StatusDialog; import org.eclipse.jface.util.BidiUtils; import org.eclipse.ui.PlatformUI; import org.eclipse.jdt.core.IPackageFragment; import org.eclipse.jdt.core.JavaConventions; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.search.IJavaSearchScope; import org.eclipse.jdt.core.search.SearchEngine; import org.eclipse.jdt.internal.corext.util.Messages; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.dialogs.PackageSelectionDialog; import org.eclipse.jdt.internal.ui.dialogs.StatusInfo; import org.eclipse.jdt.internal.ui.dialogs.TextFieldNavigationHandler; import org.eclipse.jdt.internal.ui.util.BusyIndicatorRunnableContext; import org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.IDialogFieldListener; import org.eclipse.jdt.internal.ui.wizards.dialogfields.IStringButtonAdapter; import org.eclipse.jdt.internal.ui.wizards.dialogfields.LayoutUtil; import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringButtonDialogField; /** * Dialog to enter a new entry in the type filter preference page. */ public class TypeFilterInputDialog extends StatusDialog { private class TypeFilterInputAdapter implements IDialogFieldListener, IStringButtonAdapter { /* * @see IDialogFieldListener#dialogFieldChanged(DialogField) */ @Override public void dialogFieldChanged(DialogField field) { doValidation(); } /* * @see IStringButtonAdapter#changeControlPressed(DialogField) */ @Override public void changeControlPressed(DialogField field) { doButtonPressed(); } } private StringButtonDialogField fNameDialogField; private List<String> fExistingEntries; public TypeFilterInputDialog(Shell parent, List<String> existingEntries) { super(parent); fExistingEntries= existingEntries; setTitle(PreferencesMessages.TypeFilterInputDialog_title); TypeFilterInputAdapter adapter= new TypeFilterInputAdapter(); fNameDialogField= new StringButtonDialogField(adapter); fNameDialogField.setLabelText(PreferencesMessages.TypeFilterInputDialog_message); fNameDialogField.setButtonLabel(PreferencesMessages.TypeFilterInputDialog_browse_button); fNameDialogField.setDialogFieldListener(adapter); fNameDialogField.setText(""); //$NON-NLS-1$ } public void setInitialString(String input) { Assert.isNotNull(input); fNameDialogField.setText(input); } public Object getResult() { return fNameDialogField.getText(); } @Override protected Control createDialogArea(Composite parent) { Composite composite= (Composite) super.createDialogArea(parent); Composite inner= new Composite(composite, SWT.NONE); LayoutUtil.doDefaultLayout(inner, new DialogField[] { fNameDialogField }, true, 0, 0); int fieldWidthHint= convertWidthInCharsToPixels(60); Text text= fNameDialogField.getTextControl(null); LayoutUtil.setWidthHint(text, fieldWidthHint); LayoutUtil.setHorizontalGrabbing(text); BidiUtils.applyBidiProcessing(text, StructuredTextTypeHandlerFactory.JAVA); TextFieldNavigationHandler.install(text); fNameDialogField.postSetFocusOnDialogField(parent.getDisplay()); applyDialogFont(composite); return composite; } private void doButtonPressed() { IJavaSearchScope scope= SearchEngine.createWorkspaceScope(); BusyIndicatorRunnableContext context= new BusyIndicatorRunnableContext(); int flags= PackageSelectionDialog.F_SHOW_PARENTS | PackageSelectionDialog.F_HIDE_DEFAULT_PACKAGE | PackageSelectionDialog.F_REMOVE_DUPLICATES; PackageSelectionDialog dialog = new PackageSelectionDialog(getShell(), context, flags , scope); dialog.setTitle(PreferencesMessages.TypeFilterInputDialog_choosepackage_label); dialog.setMessage(PreferencesMessages.TypeFilterInputDialog_choosepackage_description); dialog.setMultipleSelection(false); dialog.setFilter(fNameDialogField.getText()); if (dialog.open() == IDialogConstants.OK_ID) { IPackageFragment res= (IPackageFragment) dialog.getFirstResult(); fNameDialogField.setText(res.getElementName() + "*"); //$NON-NLS-1$ } } private void doValidation() { StatusInfo status= new StatusInfo(); String newText= fNameDialogField.getText(); if (newText.length() == 0) { status.setError(PreferencesMessages.TypeFilterInputDialog_error_enterName); } else { newText= newText.replace('*', 'X').replace('?', 'Y'); IStatus val= JavaConventions.validatePackageName(newText, JavaCore.VERSION_1_3, JavaCore.VERSION_1_3); if (val.matches(IStatus.ERROR)) { status.setError(Messages.format(PreferencesMessages.TypeFilterInputDialog_error_invalidName, val.getMessage())); } else { if (fExistingEntries.contains(newText)) { status.setError(PreferencesMessages.TypeFilterInputDialog_error_entryExists); } } } updateStatus(status); } /* * @see org.eclipse.jface.window.Window#configureShell(Shell) */ @Override protected void configureShell(Shell newShell) { super.configureShell(newShell); PlatformUI.getWorkbench().getHelpSystem().setHelp(newShell, IJavaHelpContextIds.TYPE_FILTER_PREFERENCE_PAGE); } }
epl-1.0
MikeJMajor/openhab2-addons-dlinksmarthome
bundles/org.openhab.binding.openweathermap/src/main/java/org/openhab/binding/openweathermap/internal/handler/OpenWeatherMapOneCallHistoryHandler.java
15479
/** * Copyright (c) 2010-2021 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.openweathermap.internal.handler; import static org.openhab.binding.openweathermap.internal.OpenWeatherMapBindingConstants.*; import static org.openhab.core.library.unit.MetricPrefix.HECTO; import static org.openhab.core.library.unit.MetricPrefix.KILO; import static org.openhab.core.library.unit.MetricPrefix.MILLI; import static org.openhab.core.library.unit.SIUnits.*; import static org.openhab.core.library.unit.Units.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.Nullable; import org.openhab.binding.openweathermap.internal.config.OpenWeatherMapOneCallHistoryConfiguration; import org.openhab.binding.openweathermap.internal.connection.OpenWeatherMapCommunicationException; import org.openhab.binding.openweathermap.internal.connection.OpenWeatherMapConfigurationException; import org.openhab.binding.openweathermap.internal.connection.OpenWeatherMapConnection; import org.openhab.binding.openweathermap.internal.dto.onecallhist.*; import org.openhab.binding.openweathermap.internal.dto.onecallhist.OpenWeatherMapOneCallHistAPIData; import org.openhab.core.i18n.TimeZoneProvider; import org.openhab.core.library.types.QuantityType; import org.openhab.core.thing.ChannelUID; import org.openhab.core.thing.Thing; import org.openhab.core.thing.ThingStatus; import org.openhab.core.types.State; import org.openhab.core.types.UnDefType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.gson.JsonSyntaxException; /** * The {@link OpenWeatherMapOneCallHistoryHandler} is responsible for handling commands, which are sent to one of * the channels. * * @author Wolfgang Klimt - Initial contribution */ @NonNullByDefault public class OpenWeatherMapOneCallHistoryHandler extends AbstractOpenWeatherMapHandler { private final Logger logger = LoggerFactory.getLogger(OpenWeatherMapOneCallHistoryHandler.class); private static final String CHANNEL_GROUP_HOURLY_FORECAST_PREFIX = "historyHours"; private static final Pattern CHANNEL_GROUP_HOURLY_FORECAST_PREFIX_PATTERN = Pattern .compile(CHANNEL_GROUP_HOURLY_FORECAST_PREFIX + "([0-9]*)"); private @Nullable OpenWeatherMapOneCallHistAPIData weatherData; // the relative day in history. private int day = 0; public OpenWeatherMapOneCallHistoryHandler(Thing thing, final TimeZoneProvider timeZoneProvider) { super(thing, timeZoneProvider); } @Override public void initialize() { super.initialize(); OpenWeatherMapOneCallHistoryConfiguration config = getConfigAs(OpenWeatherMapOneCallHistoryConfiguration.class); if (config.historyDay <= 0) { logger.warn("historyDay value of {} is not supported", config.historyDay); return; } /* * As of now, only 5 days in history are supported by the one call API. As this may change in the future, * we allow any value here and only log a warning if the value exceeds 5. */ if (config.historyDay > 5) { logger.warn("History configuration of {} days may cause errors. You have been warned :-)", config.historyDay); } day = config.historyDay; logger.debug("Initialize OpenWeatherMapOneCallHistoryHandler handler '{}' with historyDay {}.", getThing().getUID(), day); updateStatus(ThingStatus.ONLINE); } @Override protected boolean requestData(OpenWeatherMapConnection connection) throws OpenWeatherMapCommunicationException, OpenWeatherMapConfigurationException { logger.debug("Update weather and forecast data of thing '{}'.", getThing().getUID()); try { weatherData = connection.getOneCallHistAPIData(location, day); return true; } catch (JsonSyntaxException e) { logger.debug("JsonSyntaxException occurred during execution: {}", e.getLocalizedMessage(), e); return false; } } @Override protected void updateChannel(ChannelUID channelUID) { String channelGroupId = channelUID.getGroupId(); switch (channelGroupId) { case CHANNEL_GROUP_ONECALL_HISTORY: updateHistoryCurrentChannel(channelUID); break; default: int i; Matcher hourlyForecastMatcher = CHANNEL_GROUP_HOURLY_FORECAST_PREFIX_PATTERN.matcher(channelGroupId); if (hourlyForecastMatcher.find() && (i = Integer.parseInt(hourlyForecastMatcher.group(1))) >= 1 && i <= 48) { updateHourlyHistoryChannel(channelUID, i - 1); break; } break; } } /** * Update the channel from the last OpenWeatherMap data retrieved. * * @param channelUID the id identifying the channel to be updated */ private void updateHistoryCurrentChannel(ChannelUID channelUID) { String channelId = channelUID.getIdWithoutGroup(); String channelGroupId = channelUID.getGroupId(); OpenWeatherMapOneCallHistAPIData localWeatherData = weatherData; if (localWeatherData != null) { State state = UnDefType.UNDEF; switch (channelId) { case CHANNEL_STATION_LOCATION: state = getPointTypeState(localWeatherData.getLat(), localWeatherData.getLon()); break; case CHANNEL_TIME_STAMP: state = getDateTimeTypeState(localWeatherData.getCurrent().getDt()); break; case CHANNEL_SUNRISE: state = getDateTimeTypeState(localWeatherData.getCurrent().getSunrise()); break; case CHANNEL_SUNSET: state = getDateTimeTypeState(localWeatherData.getCurrent().getSunset()); break; case CHANNEL_CONDITION: if (!localWeatherData.getCurrent().getWeather().isEmpty()) { state = getStringTypeState(localWeatherData.getCurrent().getWeather().get(0).getDescription()); } break; case CHANNEL_CONDITION_ID: if (!localWeatherData.getCurrent().getWeather().isEmpty()) { state = getStringTypeState( Integer.toString(localWeatherData.getCurrent().getWeather().get(0).getId())); } break; case CHANNEL_CONDITION_ICON: if (!localWeatherData.getCurrent().getWeather().isEmpty()) { state = getRawTypeState(OpenWeatherMapConnection .getWeatherIcon(localWeatherData.getCurrent().getWeather().get(0).getIcon())); } break; case CHANNEL_CONDITION_ICON_ID: if (!localWeatherData.getCurrent().getWeather().isEmpty()) { state = getStringTypeState(localWeatherData.getCurrent().getWeather().get(0).getIcon()); } break; case CHANNEL_TEMPERATURE: state = getQuantityTypeState(localWeatherData.getCurrent().getTemp(), CELSIUS); break; case CHANNEL_APPARENT_TEMPERATURE: state = getQuantityTypeState(localWeatherData.getCurrent().getFeelsLike(), CELSIUS); break; case CHANNEL_PRESSURE: state = getQuantityTypeState(localWeatherData.getCurrent().getPressure(), HECTO(PASCAL)); break; case CHANNEL_HUMIDITY: state = getQuantityTypeState(localWeatherData.getCurrent().getHumidity(), PERCENT); break; case CHANNEL_DEW_POINT: state = getQuantityTypeState(localWeatherData.getCurrent().getDewPoint(), CELSIUS); break; case CHANNEL_WIND_SPEED: state = getQuantityTypeState(localWeatherData.getCurrent().getWindSpeed(), METRE_PER_SECOND); break; case CHANNEL_WIND_DIRECTION: state = getQuantityTypeState(localWeatherData.getCurrent().getWindDeg(), DEGREE_ANGLE); break; case CHANNEL_GUST_SPEED: state = getQuantityTypeState(localWeatherData.getCurrent().getWindGust(), METRE_PER_SECOND); break; case CHANNEL_CLOUDINESS: state = getQuantityTypeState(localWeatherData.getCurrent().getClouds(), PERCENT); break; case CHANNEL_UVINDEX: state = getDecimalTypeState(localWeatherData.getCurrent().getUvi()); break; case CHANNEL_RAIN: Rain rain = localWeatherData.getCurrent().getRain(); state = getQuantityTypeState(rain == null ? 0 : rain.get1h(), MILLI(METRE)); break; case CHANNEL_SNOW: Snow snow = localWeatherData.getCurrent().getSnow(); state = getQuantityTypeState(snow == null ? 0 : snow.get1h(), MILLI(METRE)); break; case CHANNEL_VISIBILITY: @Nullable State tempstate = new QuantityType<>(localWeatherData.getCurrent().getVisibility(), METRE) .toUnit(KILO(METRE)); state = (tempstate == null ? state : tempstate); break; default: // This should not happen logger.warn("Unknown channel id {} in onecall current weather data", channelId); break; } logger.debug("Update channel '{}' of group '{}' with new state '{}'.", channelId, channelGroupId, state); updateState(channelUID, state); } else { logger.debug("No weather data available to update channel '{}' of group '{}'.", channelId, channelGroupId); } } /** * Update the channel from the last OpenWeatherMap data retrieved. * * @param channelUID the id identifying the channel to be updated * @param count the number of the hour referenced by the channel */ private void updateHourlyHistoryChannel(ChannelUID channelUID, int count) { String channelId = channelUID.getIdWithoutGroup(); String channelGroupId = channelUID.getGroupId(); logger.debug("Updating hourly history data for channel {}, group {}, count {}", channelId, channelGroupId, count); OpenWeatherMapOneCallHistAPIData localWeatherData = weatherData; if (localWeatherData != null && localWeatherData.getHourly().size() > count) { Hourly historyData = localWeatherData.getHourly().get(count); State state = UnDefType.UNDEF; switch (channelId) { case CHANNEL_TIME_STAMP: state = getDateTimeTypeState(historyData.getDt()); break; case CHANNEL_CONDITION: if (!historyData.getWeather().isEmpty()) { state = getStringTypeState(historyData.getWeather().get(0).getDescription()); } break; case CHANNEL_CONDITION_ID: if (!historyData.getWeather().isEmpty()) { state = getStringTypeState(Integer.toString(historyData.getWeather().get(0).getId())); } break; case CHANNEL_CONDITION_ICON: if (!historyData.getWeather().isEmpty()) { state = getRawTypeState( OpenWeatherMapConnection.getWeatherIcon(historyData.getWeather().get(0).getIcon())); } break; case CHANNEL_CONDITION_ICON_ID: if (!historyData.getWeather().isEmpty()) { state = getStringTypeState(historyData.getWeather().get(0).getIcon()); } break; case CHANNEL_TEMPERATURE: state = getQuantityTypeState(historyData.getTemp(), CELSIUS); break; case CHANNEL_APPARENT_TEMPERATURE: state = getQuantityTypeState(historyData.getFeelsLike(), CELSIUS); break; case CHANNEL_PRESSURE: state = getQuantityTypeState(historyData.getPressure(), HECTO(PASCAL)); break; case CHANNEL_HUMIDITY: state = getQuantityTypeState(historyData.getHumidity(), PERCENT); break; case CHANNEL_DEW_POINT: state = getQuantityTypeState(historyData.getDewPoint(), CELSIUS); break; case CHANNEL_WIND_SPEED: state = getQuantityTypeState(historyData.getWindSpeed(), METRE_PER_SECOND); break; case CHANNEL_WIND_DIRECTION: state = getQuantityTypeState(historyData.getWindDeg(), DEGREE_ANGLE); break; case CHANNEL_GUST_SPEED: state = getQuantityTypeState(historyData.getWindGust(), METRE_PER_SECOND); break; case CHANNEL_CLOUDINESS: state = getQuantityTypeState(historyData.getClouds(), PERCENT); break; case CHANNEL_VISIBILITY: @Nullable State tempstate = new QuantityType<>(historyData.getVisibility(), METRE).toUnit(KILO(METRE)); state = (tempstate == null ? state : tempstate); case CHANNEL_RAIN: Rain rain = historyData.getRain(); state = getQuantityTypeState(rain == null ? 0 : rain.get1h(), MILLI(METRE)); break; case CHANNEL_SNOW: Snow snow = historyData.getSnow(); state = getQuantityTypeState(snow == null ? 0 : snow.get1h(), MILLI(METRE)); break; default: // This should not happen logger.warn("Unknown channel id {} in onecall hourly weather data", channelId); break; } logger.debug("Update channel '{}' of group '{}' with new state '{}'.", channelId, channelGroupId, state); updateState(channelUID, state); } else { logger.debug("No weather data available to update channel '{}' of group '{}'.", channelId, channelGroupId); } } }
epl-1.0
intuit/Tank
tools/agent_debugger/src/main/java/org/fife/ui/rtextarea/VolatileImageBackgroundPainterStrategy.java
3955
/* * 01/22/2005 * * VolatileImageBackgroundPainterStrategy.java - Renders an RTextAreaBase's * background as an image using VolatileImages. * * This library is distributed under a modified BSD license. See the included * LICENSE file for details. */ package org.fife.ui.rtextarea; import java.awt.Graphics; import java.awt.Image; import java.awt.image.VolatileImage; /** * A strategy for painting the background of an <code>RTextAreaBase</code> * as an image. The image is always stretched to completely fill the * <code>RTextAreaBase</code>.<p> * * A <code>java.awt.image.VolatileImage</code> is used for rendering; * theoretically, this should be the best image format for performance.<p> * * You can set the scaling hint used when stretching/skewing the image * to fit in the <code>RTextAreaBase</code>'s background via the * <code>setScalingHint</code> method, but keep in mind the more * accurate the scaling hint, the less responsive your application will * be when stretching the window (as that's the only time the image's * size is recalculated). * * @author Robert Futrell * @version 0.1 * @see org.fife.ui.rtextarea.ImageBackgroundPainterStrategy * @see org.fife.ui.rtextarea.BufferedImageBackgroundPainterStrategy */ public class VolatileImageBackgroundPainterStrategy extends ImageBackgroundPainterStrategy { private VolatileImage bgImage; /** * Constructor. * * @param ta The text area whose background we'll be painting. */ public VolatileImageBackgroundPainterStrategy(RTextAreaBase ta) { super(ta); } /** * Paints the image at the specified location. This method assumes * scaling has already been done, and simply paints the background * image "as-is." * * @param g The graphics context. * @param x The x-coordinate at which to paint. * @param y The y-coordinate at which to paint. */ @Override protected void paintImage(Graphics g, int x, int y) { if (bgImage != null) { do { int rc = bgImage.validate(null);//getGraphicsConfiguration()); if (rc==VolatileImage.IMAGE_RESTORED) { // FIXME: If the image needs to be restored are its width // and height still valid?? If not, we'll need to cache // these values... renderImage(bgImage.getWidth(), bgImage.getHeight(), getScalingHint()); } g.drawImage(bgImage, x,y, null); } while (bgImage.contentsLost()); } } /** * Renders the image at the proper size into <code>bgImage</code>. * This method assumes that <code>bgImage</code> is not * <code>null</code>. * * @param width The width of the volatile image to render into. * @param height The height of the volatile image to render into. * @param hint The scaling hint to use. */ private void renderImage(int width, int height, int hint) { Image master = getMasterImage(); if (master!=null) { do { Image i = master.getScaledInstance(width,height, hint); tracker.addImage(i, 1); try { tracker.waitForID(1); } catch (InterruptedException e) { e.printStackTrace(); bgImage = null; return; } finally { tracker.removeImage(i, 1); } bgImage.getGraphics().drawImage(i, 0,0, null); tracker.addImage(bgImage, 0); try { tracker.waitForID(0); } catch (InterruptedException e) { e.printStackTrace(); bgImage = null; return; } finally { tracker.removeImage(bgImage, 0); } } while (bgImage.contentsLost()); } // End of if (master!=null). else { bgImage = null; } } /** * Rescales the displayed image to be the specified size. * * @param width The new width of the image. * @param height The new height of the image. * @param hint The scaling hint to use. */ @Override protected void rescaleImage(int width, int height, int hint) { bgImage = getRTextAreaBase().createVolatileImage(width, height); if (bgImage!=null) { renderImage(width, height, hint); } } }
epl-1.0
inocybe/odl-controller
opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/messages/InstallSnapshotReply.java
1507
/* * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.controller.cluster.raft.messages; public class InstallSnapshotReply extends AbstractRaftRPC { private static final long serialVersionUID = 642227896390779503L; // The followerId - this will be used to figure out which follower is // responding private final String followerId; private final int chunkIndex; private final boolean success; public InstallSnapshotReply(long term, String followerId, int chunkIndex, boolean success) { super(term); this.followerId = followerId; this.chunkIndex = chunkIndex; this.success = success; } public String getFollowerId() { return followerId; } public int getChunkIndex() { return chunkIndex; } public boolean isSuccess() { return success; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("InstallSnapshotReply [term=").append(getTerm()).append(", followerId=").append(followerId) .append(", chunkIndex=").append(chunkIndex).append(", success=").append(success).append("]"); return builder.toString(); } }
epl-1.0
pluessth/vms
ch.pproject.vms.client.core/src/main/java/ch/pproject/vms/client/core/ui/desktop/outlines/ActivityOutline.java
852
package ch.pproject.vms.client.core.ui.desktop.outlines; import org.eclipse.scout.rt.client.ui.desktop.outline.AbstractOutline; import org.eclipse.scout.rt.platform.classid.ClassId; import org.eclipse.scout.rt.shared.TEXTS; import org.eclipse.scout.rt.shared.services.common.security.ACCESS; import ch.pproject.vms.shared.core.Icons; import ch.pproject.vms.shared.core.activity.ReadActivityOutlinePermission; @ClassId("d983b5ad-fe4a-40f8-a9dc-8838dcbac1fe") public class ActivityOutline extends AbstractOutline { @Override protected String getConfiguredTitle() { return TEXTS.get("Activities"); } @Override protected String getConfiguredIconId() { return Icons.Calendar; } @Override protected boolean getConfiguredVisible() { return ACCESS.check(new ReadActivityOutlinePermission()); } }
epl-1.0
mashirui521/DBQuery
src/dbquery/DatabaseSettingHandler.java
787
package dbquery; import org.eclipse.core.commands.AbstractHandler; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; import org.eclipse.jface.window.Window; import org.eclipse.ui.handlers.HandlerUtil; import dbquery.dialogs.SettingDatabaseDialog; public class DatabaseSettingHandler extends AbstractHandler { /* (non-Javadoc) * @see org.eclipse.core.commands.AbstractHandler#execute(org.eclipse.core.commands.ExecutionEvent) */ @Override public Object execute(ExecutionEvent event) throws ExecutionException { SettingDatabaseDialog dialog = new SettingDatabaseDialog( HandlerUtil.getActiveWorkbenchWindow(event).getShell()); dialog.create(); if(dialog.open() == Window.OK) { } return null; } }
epl-1.0
Ladicek/windup
rules-java/api/src/main/java/org/jboss/windup/rules/apps/java/reporting/rules/CreateReportIndexRuleProvider.java
3615
package org.jboss.windup.rules.apps.java.reporting.rules; import org.jboss.windup.config.AbstractRuleProvider; import org.jboss.windup.config.GraphRewrite; import org.jboss.windup.config.metadata.MetadataBuilder; import org.jboss.windup.config.operation.GraphOperation; import org.jboss.windup.config.phase.ReportGenerationPhase; import org.jboss.windup.graph.GraphContext; import org.jboss.windup.graph.model.ProjectModel; import org.jboss.windup.graph.model.WindupConfigurationModel; import org.jboss.windup.graph.model.resource.FileModel; import org.jboss.windup.graph.service.WindupConfigurationService; import org.jboss.windup.reporting.model.ApplicationReportModel; import org.jboss.windup.reporting.model.TemplateType; import org.jboss.windup.reporting.service.ApplicationReportService; import org.jboss.windup.reporting.service.ReportService; import org.ocpsoft.rewrite.config.Configuration; import org.ocpsoft.rewrite.config.ConfigurationBuilder; import org.ocpsoft.rewrite.context.EvaluationContext; /** * Creates a report with a list of other reports, as well as summary information about the analysis findings. * * @author <a href="mailto:jesse.sightler@gmail.com">Jesse Sightler</a> */ public class CreateReportIndexRuleProvider extends AbstractRuleProvider { public static final String REPORT_INDEX = "Report Index"; public static final String TEMPLATE = "/reports/templates/report_index.ftl"; public CreateReportIndexRuleProvider() { super(MetadataBuilder.forProvider(CreateReportIndexRuleProvider.class).setPhase(ReportGenerationPhase.class)); } // @formatter:off @Override public Configuration getConfiguration(GraphContext context) { return ConfigurationBuilder.begin() .addRule() .perform(new GraphOperation() { @Override public void perform(GraphRewrite event, EvaluationContext context) { WindupConfigurationModel configuration = WindupConfigurationService.getConfigurationModel(event.getGraphContext()); for (FileModel inputPath : configuration.getInputPaths()) { createReportIndex(event.getGraphContext(), inputPath.getProjectModel()); } } }); } // @formatter:on private void createReportIndex(GraphContext context, ProjectModel projectModel) { ApplicationReportService service = new ApplicationReportService(context); ApplicationReportModel applicationReportModel = service.create(); applicationReportModel.setReportPriority(100); applicationReportModel.setDisplayInApplicationReportIndex(true); applicationReportModel.setReportName(REPORT_INDEX); applicationReportModel.setReportIconClass("glyphicon glyphicon-th-list"); applicationReportModel.setMainApplicationReport(true); applicationReportModel.setTemplatePath(TEMPLATE); applicationReportModel.setTemplateType(TemplateType.FREEMARKER); applicationReportModel.setProjectModel(projectModel); applicationReportModel.setDescription( "This report provides summary information about findings from the migration analysis, as well as links to additional reports with detailed information."); // Set the filename for the report ReportService reportService = new ReportService(context); reportService.setUniqueFilename(applicationReportModel, "report_index_" + projectModel.getName(), "html"); } }
epl-1.0
usethesource/rascal-value
src/main/java/io/usethesource/vallang/type/FunctionType.java
16049
/******************************************************************************* * Copyright (c) 2009-2013 CWI * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * * Jurgen J. Vinju - Jurgen.Vinju@cwi.nl - CWI * * Mark Hills - Mark.Hills@cwi.nl (CWI) * * Arnold Lankamp - Arnold.Lankamp@cwi.nl * * Anastasia Izmaylova - A.Izmaylova@cwi.nl - CWI *******************************************************************************/ package io.usethesource.vallang.type; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Collectors; import org.checkerframework.checker.nullness.qual.Nullable; import io.usethesource.vallang.IConstructor; import io.usethesource.vallang.IList; import io.usethesource.vallang.IListWriter; import io.usethesource.vallang.ISetWriter; import io.usethesource.vallang.IValue; import io.usethesource.vallang.IValueFactory; import io.usethesource.vallang.exceptions.FactTypeUseException; import io.usethesource.vallang.exceptions.IllegalOperationException; import io.usethesource.vallang.type.TypeFactory.RandomTypesConfig; import io.usethesource.vallang.type.TypeFactory.TypeReifier; /** * Function types are here to prepare for the coming of `IFunction extends IValue` to vallang. * They are used by the Rascal run-time system. They are build on top of (implementation details of) * tuple types in the interest of reuse and brevity, but there is a significant difference * between tuple types and parameter lists. Namely when when of the parameters is of type `void` * the argument list does not reduce to `void` itself. Instead the tuple remains with its arity fixed. * This is essential and it is managed by avoiding the reduction of tuple types with void fields which is implemented * in the TypeFactory. Other interesting details are the subtype and lub implementation of functions, * which follow the typing rules of Rascal functions (co and contra-variant in their argument types). */ public class FunctionType extends DefaultSubtypeOfValue { private final Type returnType; private final TupleType argumentTypes; private final @Nullable TupleType keywordParameters; /*package*/ FunctionType(Type returnType, TupleType argumentTypes, TupleType keywordParameters) { this.argumentTypes = argumentTypes; this.returnType = returnType; this.keywordParameters = keywordParameters == null ? null : (keywordParameters.getArity() == 0 ? null : keywordParameters); } public static class Reifier implements TypeReifier { @Override public Type getSymbolConstructorType() { throw new UnsupportedOperationException(); } @Override public Set<Type> getSymbolConstructorTypes() { return Arrays.stream(new Type[] { normalFunctionSymbol() }).collect(Collectors.toSet()); } private Type normalFunctionSymbol() { return symbols().typeSymbolConstructor("func", symbols().symbolADT(), "ret", TF.listType(symbols().symbolADT()), "parameters", TF.listType(symbols().symbolADT()), "kwTypes"); } @Override public Type fromSymbol(IConstructor symbol, TypeStore store, Function<IConstructor, Set<IConstructor>> grammar) { Type returnType = symbols().fromSymbol((IConstructor) symbol.get("ret"), store, grammar); Type parameters = symbols().fromSymbols((IList) symbol.get("parameters"), store, grammar); Type kwTypes = symbols().fromSymbols((IList) symbol.get("kwTypes"), store, grammar); return TypeFactory.getInstance().functionType(returnType, parameters, kwTypes); } @Override public boolean isRecursive() { return true; } @Override public Type randomInstance(Supplier<Type> next, TypeStore store, RandomTypesConfig rnd) { // TODO: as we do not have IFunction yet in vallang, we should not generate random // function types either. It will lead to exceptions otherwise. // return TF.functionType(next.get(), (TupleType) TF.tupleType(next.get()), (TupleType) TF.tupleEmpty()); return TF.integerType(); } @Override public void asProductions(Type type, IValueFactory vf, TypeStore store, ISetWriter grammar, Set<IConstructor> done) { ((FunctionType) type).getReturnType().asProductions(vf, store, grammar, done); for (Type arg : ((FunctionType) type).getFieldTypes()) { arg.asProductions(vf, store, grammar, done); } } @Override public IConstructor toSymbol(Type type, IValueFactory vf, TypeStore store, ISetWriter grammar, Set<IConstructor> done) { IListWriter w = vf.listWriter(); int i = 0; Type args = ((FunctionType) type).getFieldTypes(); for (Type arg : args) { IConstructor sym = arg.asSymbol(vf, store, grammar, done); if (args.hasFieldNames()) { sym = symbols().labelSymbol(vf, sym, args.getFieldName(i)); } i++; w.append(sym); } IListWriter kw = vf.listWriter(); i = 0; Type kwArgs = ((FunctionType) type).getKeywordParameterTypes(); if (kwArgs != null && !kwArgs.isBottom()) { for (Type arg : kwArgs) { IConstructor sym = arg.asSymbol(vf, store, grammar, done); if (kwArgs.hasFieldNames()) { sym = symbols().labelSymbol(vf, sym, kwArgs.getFieldName(i)); } i++; kw.append(sym); } } return vf.constructor(normalFunctionSymbol(), ((FunctionType) type).getReturnType().asSymbol(vf, store, grammar, done), w.done(), kw.done()); } } @Override public TypeReifier getTypeReifier() { return new Reifier(); } @Override public boolean isFunction() { return true; } @Override public Type getFieldType(int i) { return argumentTypes.getFieldType(i); } @Override public Type getFieldType(String fieldName) throws FactTypeUseException { return argumentTypes.getFieldType(fieldName); } @Override public int getFieldIndex(String fieldName) { return argumentTypes.getFieldIndex(fieldName); } @Override public String getFieldName(int i) { return argumentTypes.getFieldName(i); } @Override public String[] getFieldNames() { return argumentTypes.getFieldNames(); } @Override public Type getFieldTypes() { return argumentTypes; } @Override public <T, E extends Throwable> T accept(ITypeVisitor<T, E> visitor) throws E { return visitor.visitFunction(this); } @Override public Type getReturnType() { return returnType; } @Override public int getArity() { return argumentTypes.getArity(); } @Override public Type getKeywordParameterTypes() { return keywordParameters == null ? TypeFactory.getInstance().tupleEmpty() : keywordParameters; } @Override public @Nullable Type getKeywordParameterType(String label) { return keywordParameters != null ? keywordParameters.getFieldType(label) : null; } @Override public boolean hasKeywordParameter(String label) { return keywordParameters != null ? keywordParameters.hasField(label) : false; } @Override public boolean hasKeywordParameters() { return keywordParameters != null; } @Override protected boolean isSupertypeOf(Type type) { return type.isSubtypeOfFunction(this); } @Override public Type lub(Type type) { return type.lubWithFunction(this); } @Override public Type glb(Type type) { return type.glbWithFunction(this); } @Override public boolean intersects(Type type) { return type.intersectsWithFunction(this); } @Override protected boolean intersectsWithFunction(Type other) { FunctionType otherType = (FunctionType) other; if (other.getArity() != getArity()) { return false; } if (otherType.getReturnType().isBottom() && getReturnType().isBottom()) { return otherType.getFieldTypes().intersects(getFieldTypes()); } // TODO should the return type intersect or just be comparable? return otherType.getReturnType().intersects(getReturnType()) && otherType.getFieldTypes().intersects(getFieldTypes()); } @Override public boolean isSubtypeOfFunction(Type other) { // Vallang functions are co-variant in the return type position and // *variant* (co- _and_ contra-variant) in their argument positions, such that a sub-function // can safely simulate a super function and in particular overloaded functions may have contributions which // do not match the currently requested function type. // For example, an overloadeded function `X f(int) + X f(str)` is substitutable at high-order parameter positions of type `X (int)` // even though its function type is `X (value)`. Rascal's type system does not check completeness of function definitions, // only _possible_ applicability in this manner. Every function may throw `CallFailed` at run-time // if non of their arguments match for none of their alternatives. FunctionType otherType = (FunctionType) other; if (getReturnType().isSubtypeOf(otherType.getReturnType())) { Type argTypes = getFieldTypes(); Type otherArgTypes = otherType.getFieldTypes(); if (argTypes.getArity() != otherArgTypes.getArity()) { return false; } int N = argTypes.getArity(); for (int i = 0; i < N; i++) { Type field = argTypes.getFieldType(i); Type otherField = otherArgTypes.getFieldType(i); if (field.isBottom() || otherField.isBottom()) { continue; } if (!field.intersects(otherField)) { return false; } } return true; } return false; } @Override protected Type lubWithFunction(Type type) { if (this == type) { return this; } FunctionType f = (FunctionType) type; Type returnType = getReturnType().lub(f.getReturnType()); Type argumentTypes = getFieldTypes().lub(f.getFieldTypes()); if (argumentTypes.isTuple() && argumentTypes.getArity() == getArity()) { return TypeFactory.getInstance().functionType(returnType, argumentTypes, getKeywordParameterTypes() == f.getKeywordParameterTypes() ? getKeywordParameterTypes() : TF.tupleEmpty()); } return TF.valueType(); } @Override protected Type glbWithFunction(Type type) { if (this == type) { return this; } FunctionType f = (FunctionType) type; Type returnType = getReturnType().glb(f.getReturnType()); Type argumentTypes = getFieldTypes().lub(f.getFieldTypes()); if (argumentTypes.isTuple()) { // TODO: figure out what glb means for keyword parameters return TF.functionType(returnType, argumentTypes, TF.tupleEmpty()); } return TF.voidType(); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(returnType); sb.append(' '); sb.append('('); int i = 0; for (Type arg : argumentTypes) { if (i > 0) { sb.append(", "); } sb.append(arg.toString()); if (argumentTypes.hasFieldNames()) { sb.append(" " + argumentTypes.getFieldName(i)); } i++; } if (keywordParameters != null) { i = 0; for (Type arg : keywordParameters) { sb.append(", "); sb.append(arg.toString()); if (keywordParameters.hasFieldNames()) { sb.append(" " + keywordParameters.getFieldName(i) + " = ..."); } i++; } } sb.append(')'); return sb.toString(); } @Override public int hashCode() { return 19 + 19 * returnType.hashCode() + 23 * argumentTypes.hashCode() + (keywordParameters != null ? 29 * keywordParameters.hashCode() : 0) ; } @Override public boolean equals(@Nullable Object o) { if (o == null) { return false; } if (o == this) { return true; } if (o instanceof FunctionType) { FunctionType other = (FunctionType) o; if (returnType != other.returnType) { return false; } if (argumentTypes != other.argumentTypes) { return false; } if (keywordParameters != other.keywordParameters) { return false; } return true; } return false; } @Override public Type instantiate(Map<Type, Type> bindings) { return TF.functionType(returnType.instantiate(bindings), instantiateTuple(argumentTypes, bindings), keywordParameters != null ? instantiateTuple(keywordParameters, bindings) : TypeFactory.getInstance().tupleEmpty()); } /** * Instantiate a tuple but do not reduce to void like TupleType.instantiate would * if one of the parameters was substituted by void */ private Type instantiateTuple(TupleType t, Map<Type, Type> bindings) { Type[] fChildren = new Type[t.getArity()]; for (int i = t.fFieldTypes.length - 1; i >= 0; i--) { fChildren[i] = t.getFieldType(i).instantiate(bindings); } return TypeFactory.getInstance().getFromCache(new TupleType(fChildren)); } @Override public boolean isOpen() { return returnType.isOpen() || argumentTypes.isOpen(); } @Override public boolean match(Type matched, Map<Type, Type> bindings) throws FactTypeUseException { if (matched.isBottom()) { return argumentTypes.match(matched, bindings) && returnType.match(matched, bindings); } else { // Fix for cases where we have aliases to function types, aliases to aliases to function types, etc while (matched.isAliased()) { matched = matched.getAliased(); } if (matched.isFunction()) { FunctionType matchedFunction = (FunctionType) matched; if (argumentTypes.getArity() != matchedFunction.getArity()) { return false; } for (int i = argumentTypes.getArity() - 1; i >= 0; i--) { Type fieldType = argumentTypes.getFieldType(i); Type otherFieldType = matchedFunction.getFieldTypes().getFieldType(i); Map<Type, Type> originalBindings = new HashMap<>(); originalBindings.putAll(bindings); if (!fieldType.match(otherFieldType, bindings)) { bindings = originalBindings; if (!otherFieldType.match(matchedFunction, bindings)) { // neither co nor contra-variant return false; } } } return returnType.match(matchedFunction.getReturnType(), bindings); } else { return false; } } } @Override public Type compose(Type right) { if (right.isBottom()) { return right; } if (right.isFunction()) { if (TF.tupleType(right.getReturnType()).isSubtypeOf(this.argumentTypes)) { return TF.functionType(this.returnType, right.getFieldTypes(), right.getKeywordParameterTypes()); } } else { throw new IllegalOperationException("compose", this, right); } return TF.voidType(); } @Override public IValue randomValue(Random random, IValueFactory vf, TypeStore store, Map<Type, Type> typeParameters, int maxDepth, int maxBreadth) { throw new RuntimeException("randomValue on FunctionType not yet implemented"); } }
epl-1.0
wugian/work_study
Fuck/src/com/fuck/activity/SideBar.java
3459
package com.fuck.activity; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; public class SideBar extends View { // 是否点击 private boolean showBkg = false; OnTouchingLetterChangedListener onTouchingLetterChangedListener; public static String[] b = { "@", "#", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" }; // 选择的值 int choose = -1; // 画笔 Paint paint = new Paint(); public SideBar(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } public SideBar(Context context, AttributeSet attrs) { super(context, attrs); } public SideBar(Context context) { super(context); } protected void onDraw(Canvas canvas) { super.onDraw(canvas); // 如果面板处于点击状态就将面板的背景色绘制为灰色 if (showBkg) { canvas.drawColor(Color.parseColor("#40000000")); } // 获得View的高 int height = getHeight(); // 获得View的宽 int width = getWidth(); // 计算得出每一个字体大概的高度 int singleHeight = height / b.length; for (int i = 0; i < b.length; i++) { // 设置锯齿 paint.setAntiAlias(true); // 设置字体大小 paint.setTextSize(15); // 点击的字体和26个字母中的任意一个相等就 if (i == choose) { // 绘制点击的字体的颜色为蓝色 paint.setColor(Color.parseColor("#3399ff")); paint.setFakeBoldText(true); } // 得到字体的X坐标 float xPos = width / 2 - paint.measureText(b[i]) / 2; // 得到字体的Y坐标 float yPos = singleHeight * i + singleHeight + 3; // 将字体绘制到面板上 canvas.drawText(b[i], xPos, yPos, paint); // 还原画布 paint.reset(); } } @Override public boolean dispatchTouchEvent(MotionEvent event) { // 得到点击的状态 final int action = event.getAction(); // 点击的Y坐标 final float y = event.getY(); final int oldChoose = choose; // 监听 final OnTouchingLetterChangedListener listener = onTouchingLetterChangedListener; // 得到当前的值 final int c = (int) (y / getHeight() * b.length); switch (action) { // 按下 case MotionEvent.ACTION_DOWN: // 将开关设置为true showBkg = true; if (oldChoose != c && listener != null) { if (c > 0 && c < b.length) { listener.onTouchingLetterChanged(b[c]); choose = c; // 刷新界面 invalidate(); } } break; // 移动 case MotionEvent.ACTION_MOVE: if (oldChoose != c && listener != null) { if (c > 0 && c < b.length) { listener.onTouchingLetterChanged(b[c]); choose = c; invalidate(); } } break; // 松开 还原数据 并刷新界面 case MotionEvent.ACTION_UP: showBkg = false; choose = -1; invalidate(); break; } return true; } @Override public boolean onTouchEvent(MotionEvent event) { return super.onTouchEvent(event); } public void setOnTouchingLetterChangedListener( OnTouchingLetterChangedListener onTouchingLetterChangedListener) { this.onTouchingLetterChangedListener = onTouchingLetterChangedListener; } public interface OnTouchingLetterChangedListener { public void onTouchingLetterChanged(String s); } }
epl-1.0
SINTEF-9012/SPLCATool
de.ovgu.featureide.fm.core/src/de/ovgu/featureide/fm/core/editing/evaluation/Generator.java
13877
/* FeatureIDE - An IDE to support feature-oriented software development * Copyright (C) 2005-2011 FeatureIDE Team, University of Magdeburg * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see http://www.gnu.org/licenses/. * * See http://www.fosd.de/featureide/ for further information. */ package de.ovgu.featureide.fm.core.editing.evaluation; import java.util.LinkedList; import java.util.List; import java.util.Random; import org.prop4j.And; import org.prop4j.AtMost; import org.prop4j.Equals; import org.prop4j.Implies; import org.prop4j.Literal; import org.prop4j.Node; import org.prop4j.Not; import org.prop4j.Or; import org.sat4j.specs.TimeoutException; import de.ovgu.featureide.fm.core.FMCorePlugin; import de.ovgu.featureide.fm.core.Feature; import de.ovgu.featureide.fm.core.FeatureModel; public abstract class Generator { public static final int TIMEOUT = 60; public final static int maxChildren = 10; public final static int minLiterals = 2; public final static int maxLiterals = 5; public static FeatureModel generateFeatureModel(long id, int numberOfFeatures) { Random random = new Random(id); FeatureModel fm = generateFeatureDiagram(random, numberOfFeatures); generateConstraints(fm, random, numberOfFeatures / 10); return fm; } public static FeatureModel generateFeatureDiagram(Random random, int numberOfFeatures) { FeatureModel fm = new FeatureModel(); List<Feature> leaves = new LinkedList<Feature>(); leaves.add(fm.getFeature("C1")); int count = 1; while (count < numberOfFeatures) { int parentIndex = random.nextInt(leaves.size()); Feature parent = leaves.remove(parentIndex); fm.renameFeature(parent.getName(), "A" + parent.getName().substring(1)); int childrenCount = random.nextInt(maxChildren) + 1; childrenCount = Math.min(childrenCount, numberOfFeatures - count); for (int i = 1; i <= childrenCount; i++) { Feature child = new Feature(fm, "C" + (count + i)); fm.addFeature(child); parent.addChild(child); leaves.add(child); } if (random.nextBoolean()) { parent.changeToAnd(); for (Feature child : parent.getChildren()) child.setMandatory(random.nextBoolean()); } else if (random.nextBoolean()) parent.changeToOr(); count += childrenCount; } fm.performRenamings(); return fm; } public static void generateConstraints(FeatureModel fm, Random random, int numberOfConstraints) { boolean valid = true; try { valid = fm.isValid(); if (!valid) FMCorePlugin.getDefault().logInfo("Feature model not valid!"); } catch (TimeoutException e) { FMCorePlugin.getDefault().logError(e); } Object[] names = fm.getOldFeatureNames().toArray(); int k = 0; for (int i = 0; i < numberOfConstraints;) { Node node = getRandomLiteral(names, random); for (int j = random.nextInt(maxLiterals - minLiterals + 1) + minLiterals; j > 1; j--) { if (random.nextBoolean()) { if (random.nextBoolean()) node = new And(node, getRandomLiteral(names, random)); else node = new Or(node, getRandomLiteral(names, random)); } else { if (random.nextBoolean()) node = new Implies(node, getRandomLiteral(names, random)); else node = new Equals(node, getRandomLiteral(names, random)); } if (random.nextBoolean() && random.nextBoolean()) node = new Not(node); } fm.addPropositionalNode(node); try { if (!valid || fm.isValid()) { i++; System.out.println("E\t" + i + "\t" + node); } else { fm.removePropositionalNode(node); FMCorePlugin.getDefault().logInfo("F\t" + ++k + "\t" + node); } } catch (TimeoutException e) { FMCorePlugin.getDefault().logError(e); fm.removePropositionalNode(node); } } } public static FeatureModel refactoring(FeatureModel originalFM, long id, int numberOfEdits) { FeatureModel fm = (FeatureModel) originalFM.clone(); Random random = new Random(id); for (int i = 0; i < numberOfEdits; i++) { List<Feature> list = new LinkedList<Feature>(fm.getFeatures()); List<Feature> randomizedList = new LinkedList<Feature>(); while (!list.isEmpty()) randomizedList.add(list.remove(random.nextInt(list.size()))); int r = random.nextInt(3); if (r == 0) { //Alternative to Or+Constraint for (Feature feature : randomizedList) if (feature.getChildrenCount() > 1 && feature.isAlternative()) { feature.changeToOr(); LinkedList<Node> nodes = new LinkedList<Node>(); for (Feature child : feature.getChildren()) nodes.add(new Literal(child.getName())); fm.addPropositionalNode(new AtMost(1,nodes).toCNF()); break; } } else if (r == 1) { //Mandatory to Optional+Constraint for (Feature feature : randomizedList) { Feature parent = feature.getParent(); if (parent != null && parent.isAnd() && !parent.isFirstChild(feature) && feature.isMandatory()) { feature.setMandatory(false); fm.addPropositionalNode(new Implies(new Literal(parent.getName()),new Literal(feature.getName()))); break; } } } else { //move feature to parent's parent for (Feature child : randomizedList) { Feature feature = child.getParent(); if (feature != null && feature.isMandatory() && feature.isAnd() && !feature.isFirstChild(child)) { Feature parent = feature.getParent(); if (parent != null && parent.isAnd()) { feature.removeChild(child); parent.addChild(child); break; } } } } } return fm; } public static FeatureModel generalization(FeatureModel originalFM, long id, int numberOfEdits) { FeatureModel fm = (FeatureModel) originalFM.clone(); Random random = new Random(id); for (int i = 0; i < numberOfEdits; i++) { List<Feature> list = new LinkedList<Feature>(fm.getFeatures()); List<Feature> randomizedList = new LinkedList<Feature>(); while (!list.isEmpty()) randomizedList.add(list.remove(random.nextInt(list.size()))); int r = 1 + random.nextInt(9); if (r == 1) { //Alternative to Or for (Feature feature : randomizedList) if (feature.getChildrenCount() > 1 && feature.isAlternative()) { feature.changeToOr(); break; } } else if (r == 2) { //move Optional into Or r2: for (Feature feature : randomizedList) { Feature parent = feature.getParent(); if (parent != null && parent.isAnd() && feature.isMandatory() && feature.isOr()) { for (Feature child : parent.getChildren()) if (!child.isMandatory()) { parent.removeChild(child); feature.addChild(child); break r2; } } } } else if (r == 3) { //And to Or for (Feature feature : randomizedList) if (feature.getChildrenCount() > 1 && feature.isAnd()) { feature.changeToOr(); break; } } else if (r == 4) { //new feature in Alternative for (Feature feature : randomizedList) if (feature.hasChildren() && feature.isAlternative()) { int j = 1; Feature child; do { child = new Feature(fm, "C" + j++); } while (!fm.addFeature(child)); feature.addChild(child); break; } } else if (r == 5) { //Or to And for (Feature feature : randomizedList) if (feature.getChildrenCount() > 1 && feature.isOr()) { Feature parent = feature.getParent(); if (parent != null && !parent.isFirstChild(feature) && parent.isAnd()) { parent.removeChild(feature); for (Feature child : feature.getChildren()) { parent.addChild(child); child.setMandatory(false); } break; } } } else if (r == 6) { //Mandatory to Optional for (Feature feature : randomizedList) { Feature parent = feature.getParent(); if (parent != null && parent.isAnd() && !parent.isFirstChild(feature) && feature.isMandatory()) { feature.setMandatory(false); fm.addPropositionalNode(new Implies(new Literal(parent.getName()),new Literal(feature.getName()))); break; } } } else if (r == 7) { //Alternative to And for (Feature feature : randomizedList) if (feature.getChildrenCount() > 1 && feature.isAlternative()) { Feature parent = feature.getParent(); if (parent != null && !parent.isFirstChild(feature) && parent.isAnd()) { parent.removeChild(feature); for (Feature child : feature.getChildren()) { parent.addChild(child); child.setMandatory(false); } break; } } } else if (r == 8) { //new Optional in And for (Feature feature : randomizedList) if (feature.hasChildren() && feature.isAnd()) { int j = 1; Feature child; do { child = new Feature(fm, "C" + j++); } while (!fm.addFeature(child)); child.setMandatory(false); feature.addChild(child); break; } } else { //remove Constraint List<Node> nodes = fm.getPropositionalNodes(); if (!nodes.isEmpty()) { int index = random.nextInt(nodes.size()); fm.removePropositionalNode(nodes.get(index)); } } } return fm; } public static FeatureModel arbitraryEdits(FeatureModel originalFM, long id, int numberOfEdits) { boolean valid = false; try { valid = originalFM.isValid(); } catch (TimeoutException e) { FMCorePlugin.getDefault().logError(e); } FeatureModel fm = (FeatureModel) originalFM.clone(); Random random = new Random(id); for (int i = 0; i < numberOfEdits; i++) { FeatureModel backup = valid ? fm.clone() : null; List<Feature> list = new LinkedList<Feature>(fm.getFeatures()); List<Feature> randomizedList = new LinkedList<Feature>(); while (!list.isEmpty()) randomizedList.add(list.remove(random.nextInt(list.size()))); int r = 1 + random.nextInt(5); if (r == 1) { //delete or add feature if (random.nextBoolean()) for (Feature feature : randomizedList) { Feature parent = feature.getParent(); if (!feature.hasChildren() && parent != null && !parent.isFirstChild(feature)) { fm.deleteFeature(feature); break; } } else for (Feature feature : randomizedList) if (feature.hasChildren()) { int j = 1; Feature child; do { child = new Feature(fm, "C" + j++); } while (!fm.addFeature(child)); feature.addChild(child); break; } } else if (r == 2) { //alter group type for (Feature feature : randomizedList) { if (feature.hasChildren()) { if (feature.isAlternative()) if (random.nextBoolean()) feature.changeToAnd(); else feature.changeToOr(); else if (feature.isAnd()) if (random.nextBoolean()) feature.changeToAlternative(); else feature.changeToOr(); else if (random.nextBoolean()) feature.changeToAnd(); else feature.changeToAlternative(); break; } } } else if (r == 3) { //change mandatory/optional for (Feature feature : randomizedList) { Feature parent = feature.getParent(); if (parent != null && parent.isAnd() && !parent.isFirstChild(feature)) { feature.setMandatory(!feature.isMandatory()); break; } } } else if (r == 4) { //move a concrete feature to another branch for (Feature feature : randomizedList) { Feature parent = feature.getParent(); if (!feature.hasChildren() && parent != null && !parent.isFirstChild(feature)) { parent.removeChild(feature); Feature newParent = parent; for (Feature compound : randomizedList) if (compound != parent && compound.hasChildren()) newParent = compound; newParent.addChild(feature); break; } } } else { //delete or add constraint if (fm.getPropositionalNodes().size() > 0 && random.nextBoolean()) { int index = random.nextInt(fm.getPropositionalNodes().size()); fm.removePropositionalNode(index); } else generateConstraints(fm, random, 1); } try { if (valid && !fm.isValid()) { System.out.println("Void feature model by arbitrary edit " + r); fm = backup; i--; } } catch (TimeoutException e) { FMCorePlugin.getDefault().logError(e); } } return fm; } private static Literal getRandomLiteral(Object[] names, Random random) { int index = random.nextInt(names.length); return new Literal(names[index], random.nextBoolean()); } public static String getTimeString(long dur) { if (dur < 1000000) return dur + "nsec"; dur /= 1000000; if (dur < 1000) return dur + "msec"; dur /= 1000; if (dur < 60) return dur + "sec"; dur /= 60; if (dur < 60) return dur + "min"; dur /= 60; return dur + "h"; } }
epl-1.0
debrief/debrief
org.mwc.cmap.legacy/src/MWC/GUI/Tools/AWT/AWTToolbarButton.java
3823
/******************************************************************************* * Debrief - the Open Source Maritime Analysis Application * http://debrief.info * * (C) 2000-2020, Deep Blue C Technology Ltd * * This library is free software; you can redistribute it and/or * modify it under the terms of the Eclipse Public License v1.0 * (http://www.eclipse.org/legal/epl-v10.html) * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *******************************************************************************/ // $RCSfile: AWTToolbarButton.java,v $ // $Author: Ian.Mayo $ // $Log: AWTToolbarButton.java,v $ // Revision 1.2 2004/05/25 15:41:11 Ian.Mayo // Commit updates from home // // Revision 1.1.1.1 2004/03/04 20:31:25 ian // no message // // Revision 1.1.1.1 2003/07/17 10:07:42 Ian.Mayo // Initial import // // Revision 1.3 2003-02-07 09:49:16+00 ian_mayo // rationalise unnecessary to da comments (that's do really) // // Revision 1.2 2002-05-28 09:25:58+01 ian_mayo // after switch to new system // // Revision 1.1 2002-05-28 09:14:11+01 ian_mayo // Initial revision // // Revision 1.1 2002-04-11 13:03:47+01 ian_mayo // Initial revision // // Revision 1.0 2001-07-17 08:42:59+01 administrator // Initial revision // // Revision 1.1 2001-01-03 13:41:55+00 novatech // Initial revision // // Revision 1.1.1.1 2000/12/12 21:51:12 ianmayo // initial version // // Revision 1.1 1999-10-12 15:36:25+01 ian_mayo // Initial revision // // Revision 1.1 1999-07-27 10:50:32+01 administrator // Initial revision // // Revision 1.1 1999-07-07 11:10:02+01 administrator // Initial revision // // Revision 1.1 1999-06-16 15:37:56+01 sm11td // Initial revision // // Revision 1.3 1999-06-01 16:49:23+01 sm11td // Reading in tracks aswell as fixes, commenting large portions of source code // // Revision 1.2 1999-02-01 16:08:50+00 sm11td // creating new sessions & panes, starting import management // // Revision 1.1 1999-02-01 14:25:08+00 sm11td // Initial revision // package MWC.GUI.Tools.AWT; import java.awt.Button; import java.awt.Dimension; import java.awt.event.ActionListener; import MWC.GUI.Tool; /** * extension of AWT button, to create one which implements one of our Debrief * tools */ public class AWTToolbarButton extends Button implements ActionListener { ///////////////////////////////////////////////////////// // member variables ///////////////////////////////////////////////////////// /** * */ private static final long serialVersionUID = 1L; protected Tool _theTool; public AWTToolbarButton(final String theLabel, final Tool theTool) { super(theLabel); _theTool = theTool; this.addActionListener(this); } ///////////////////////////////////////////////////////// // constructor ///////////////////////////////////////////////////////// /** * convenience constructor, calls normal one */ public AWTToolbarButton(final Tool theTool) { this(theTool.getLabel(), theTool); } ///////////////////////////////////////////////////////// // member functions ///////////////////////////////////////////////////////// /** * callback function for a button being pressed */ @Override public void actionPerformed(final java.awt.event.ActionEvent e) { /** * check that we have a tool declared */ if (_theTool != null) _theTool.execute(); } @Override public Dimension getMaximumSize() { return super.getMinimumSize(); } /** * return the tool for this button */ protected Tool getTool() { return _theTool; } }
epl-1.0
miklossy/xtext-core
org.eclipse.xtext.tests/src-gen/org/eclipse/xtext/parsetree/reconstr/serializationerror/SerializationerrorPackage.java
16995
/** * generated by Xtext */ package org.eclipse.xtext.parsetree.reconstr.serializationerror; import org.eclipse.emf.ecore.EAttribute; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EPackage; import org.eclipse.emf.ecore.EReference; /** * <!-- begin-user-doc --> * The <b>Package</b> for the model. * It contains accessors for the meta objects to represent * <ul> * <li>each class,</li> * <li>each feature of each class,</li> * <li>each enum,</li> * <li>and each data type</li> * </ul> * <!-- end-user-doc --> * @see org.eclipse.xtext.parsetree.reconstr.serializationerror.SerializationerrorFactory * @model kind="package" * @generated */ public interface SerializationerrorPackage extends EPackage { /** * The package name. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ String eNAME = "serializationerror"; /** * The package namespace URI. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ String eNS_URI = "http://www.eclipse.org/2009/tmf/xtext/serializationerror"; /** * The package namespace name. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ String eNS_PREFIX = "serializationerror"; /** * The singleton instance of the package. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ SerializationerrorPackage eINSTANCE = org.eclipse.xtext.parsetree.reconstr.serializationerror.impl.SerializationerrorPackageImpl.init(); /** * The meta object id for the '{@link org.eclipse.xtext.parsetree.reconstr.serializationerror.impl.ModelImpl <em>Model</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see org.eclipse.xtext.parsetree.reconstr.serializationerror.impl.ModelImpl * @see org.eclipse.xtext.parsetree.reconstr.serializationerror.impl.SerializationerrorPackageImpl#getModel() * @generated */ int MODEL = 0; /** * The feature id for the '<em><b>Test</b></em>' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int MODEL__TEST = 0; /** * The number of structural features of the '<em>Model</em>' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int MODEL_FEATURE_COUNT = 1; /** * The meta object id for the '{@link org.eclipse.xtext.parsetree.reconstr.serializationerror.impl.TestImpl <em>Test</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see org.eclipse.xtext.parsetree.reconstr.serializationerror.impl.TestImpl * @see org.eclipse.xtext.parsetree.reconstr.serializationerror.impl.SerializationerrorPackageImpl#getTest() * @generated */ int TEST = 1; /** * The number of structural features of the '<em>Test</em>' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int TEST_FEATURE_COUNT = 0; /** * The meta object id for the '{@link org.eclipse.xtext.parsetree.reconstr.serializationerror.impl.TwoRequiredImpl <em>Two Required</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see org.eclipse.xtext.parsetree.reconstr.serializationerror.impl.TwoRequiredImpl * @see org.eclipse.xtext.parsetree.reconstr.serializationerror.impl.SerializationerrorPackageImpl#getTwoRequired() * @generated */ int TWO_REQUIRED = 2; /** * The feature id for the '<em><b>One</b></em>' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int TWO_REQUIRED__ONE = TEST_FEATURE_COUNT + 0; /** * The feature id for the '<em><b>Two</b></em>' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int TWO_REQUIRED__TWO = TEST_FEATURE_COUNT + 1; /** * The number of structural features of the '<em>Two Required</em>' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int TWO_REQUIRED_FEATURE_COUNT = TEST_FEATURE_COUNT + 2; /** * The meta object id for the '{@link org.eclipse.xtext.parsetree.reconstr.serializationerror.impl.TwoOptionsImpl <em>Two Options</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see org.eclipse.xtext.parsetree.reconstr.serializationerror.impl.TwoOptionsImpl * @see org.eclipse.xtext.parsetree.reconstr.serializationerror.impl.SerializationerrorPackageImpl#getTwoOptions() * @generated */ int TWO_OPTIONS = 3; /** * The feature id for the '<em><b>One</b></em>' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int TWO_OPTIONS__ONE = TEST_FEATURE_COUNT + 0; /** * The feature id for the '<em><b>Two</b></em>' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int TWO_OPTIONS__TWO = TEST_FEATURE_COUNT + 1; /** * The number of structural features of the '<em>Two Options</em>' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int TWO_OPTIONS_FEATURE_COUNT = TEST_FEATURE_COUNT + 2; /** * The meta object id for the '{@link org.eclipse.xtext.parsetree.reconstr.serializationerror.impl.IndentImpl <em>Indent</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see org.eclipse.xtext.parsetree.reconstr.serializationerror.impl.IndentImpl * @see org.eclipse.xtext.parsetree.reconstr.serializationerror.impl.SerializationerrorPackageImpl#getIndent() * @generated */ int INDENT = 4; /** * The feature id for the '<em><b>Req</b></em>' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int INDENT__REQ = TEST_FEATURE_COUNT + 0; /** * The feature id for the '<em><b>Opt</b></em>' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int INDENT__OPT = TEST_FEATURE_COUNT + 1; /** * The feature id for the '<em><b>Indent</b></em>' containment reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int INDENT__INDENT = TEST_FEATURE_COUNT + 2; /** * The number of structural features of the '<em>Indent</em>' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int INDENT_FEATURE_COUNT = TEST_FEATURE_COUNT + 3; /** * Returns the meta object for class '{@link org.eclipse.xtext.parsetree.reconstr.serializationerror.Model <em>Model</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for class '<em>Model</em>'. * @see org.eclipse.xtext.parsetree.reconstr.serializationerror.Model * @generated */ EClass getModel(); /** * Returns the meta object for the containment reference '{@link org.eclipse.xtext.parsetree.reconstr.serializationerror.Model#getTest <em>Test</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the containment reference '<em>Test</em>'. * @see org.eclipse.xtext.parsetree.reconstr.serializationerror.Model#getTest() * @see #getModel() * @generated */ EReference getModel_Test(); /** * Returns the meta object for class '{@link org.eclipse.xtext.parsetree.reconstr.serializationerror.Test <em>Test</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for class '<em>Test</em>'. * @see org.eclipse.xtext.parsetree.reconstr.serializationerror.Test * @generated */ EClass getTest(); /** * Returns the meta object for class '{@link org.eclipse.xtext.parsetree.reconstr.serializationerror.TwoRequired <em>Two Required</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for class '<em>Two Required</em>'. * @see org.eclipse.xtext.parsetree.reconstr.serializationerror.TwoRequired * @generated */ EClass getTwoRequired(); /** * Returns the meta object for the attribute '{@link org.eclipse.xtext.parsetree.reconstr.serializationerror.TwoRequired#getOne <em>One</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the attribute '<em>One</em>'. * @see org.eclipse.xtext.parsetree.reconstr.serializationerror.TwoRequired#getOne() * @see #getTwoRequired() * @generated */ EAttribute getTwoRequired_One(); /** * Returns the meta object for the attribute '{@link org.eclipse.xtext.parsetree.reconstr.serializationerror.TwoRequired#getTwo <em>Two</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the attribute '<em>Two</em>'. * @see org.eclipse.xtext.parsetree.reconstr.serializationerror.TwoRequired#getTwo() * @see #getTwoRequired() * @generated */ EAttribute getTwoRequired_Two(); /** * Returns the meta object for class '{@link org.eclipse.xtext.parsetree.reconstr.serializationerror.TwoOptions <em>Two Options</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for class '<em>Two Options</em>'. * @see org.eclipse.xtext.parsetree.reconstr.serializationerror.TwoOptions * @generated */ EClass getTwoOptions(); /** * Returns the meta object for the attribute '{@link org.eclipse.xtext.parsetree.reconstr.serializationerror.TwoOptions#getOne <em>One</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the attribute '<em>One</em>'. * @see org.eclipse.xtext.parsetree.reconstr.serializationerror.TwoOptions#getOne() * @see #getTwoOptions() * @generated */ EAttribute getTwoOptions_One(); /** * Returns the meta object for the attribute '{@link org.eclipse.xtext.parsetree.reconstr.serializationerror.TwoOptions#getTwo <em>Two</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the attribute '<em>Two</em>'. * @see org.eclipse.xtext.parsetree.reconstr.serializationerror.TwoOptions#getTwo() * @see #getTwoOptions() * @generated */ EAttribute getTwoOptions_Two(); /** * Returns the meta object for class '{@link org.eclipse.xtext.parsetree.reconstr.serializationerror.Indent <em>Indent</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for class '<em>Indent</em>'. * @see org.eclipse.xtext.parsetree.reconstr.serializationerror.Indent * @generated */ EClass getIndent(); /** * Returns the meta object for the containment reference '{@link org.eclipse.xtext.parsetree.reconstr.serializationerror.Indent#getReq <em>Req</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the containment reference '<em>Req</em>'. * @see org.eclipse.xtext.parsetree.reconstr.serializationerror.Indent#getReq() * @see #getIndent() * @generated */ EReference getIndent_Req(); /** * Returns the meta object for the containment reference '{@link org.eclipse.xtext.parsetree.reconstr.serializationerror.Indent#getOpt <em>Opt</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the containment reference '<em>Opt</em>'. * @see org.eclipse.xtext.parsetree.reconstr.serializationerror.Indent#getOpt() * @see #getIndent() * @generated */ EReference getIndent_Opt(); /** * Returns the meta object for the containment reference list '{@link org.eclipse.xtext.parsetree.reconstr.serializationerror.Indent#getIndent <em>Indent</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the containment reference list '<em>Indent</em>'. * @see org.eclipse.xtext.parsetree.reconstr.serializationerror.Indent#getIndent() * @see #getIndent() * @generated */ EReference getIndent_Indent(); /** * Returns the factory that creates the instances of the model. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the factory that creates the instances of the model. * @generated */ SerializationerrorFactory getSerializationerrorFactory(); /** * <!-- begin-user-doc --> * Defines literals for the meta objects that represent * <ul> * <li>each class,</li> * <li>each feature of each class,</li> * <li>each enum,</li> * <li>and each data type</li> * </ul> * <!-- end-user-doc --> * @generated */ interface Literals { /** * The meta object literal for the '{@link org.eclipse.xtext.parsetree.reconstr.serializationerror.impl.ModelImpl <em>Model</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see org.eclipse.xtext.parsetree.reconstr.serializationerror.impl.ModelImpl * @see org.eclipse.xtext.parsetree.reconstr.serializationerror.impl.SerializationerrorPackageImpl#getModel() * @generated */ EClass MODEL = eINSTANCE.getModel(); /** * The meta object literal for the '<em><b>Test</b></em>' containment reference feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EReference MODEL__TEST = eINSTANCE.getModel_Test(); /** * The meta object literal for the '{@link org.eclipse.xtext.parsetree.reconstr.serializationerror.impl.TestImpl <em>Test</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see org.eclipse.xtext.parsetree.reconstr.serializationerror.impl.TestImpl * @see org.eclipse.xtext.parsetree.reconstr.serializationerror.impl.SerializationerrorPackageImpl#getTest() * @generated */ EClass TEST = eINSTANCE.getTest(); /** * The meta object literal for the '{@link org.eclipse.xtext.parsetree.reconstr.serializationerror.impl.TwoRequiredImpl <em>Two Required</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see org.eclipse.xtext.parsetree.reconstr.serializationerror.impl.TwoRequiredImpl * @see org.eclipse.xtext.parsetree.reconstr.serializationerror.impl.SerializationerrorPackageImpl#getTwoRequired() * @generated */ EClass TWO_REQUIRED = eINSTANCE.getTwoRequired(); /** * The meta object literal for the '<em><b>One</b></em>' attribute feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EAttribute TWO_REQUIRED__ONE = eINSTANCE.getTwoRequired_One(); /** * The meta object literal for the '<em><b>Two</b></em>' attribute feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EAttribute TWO_REQUIRED__TWO = eINSTANCE.getTwoRequired_Two(); /** * The meta object literal for the '{@link org.eclipse.xtext.parsetree.reconstr.serializationerror.impl.TwoOptionsImpl <em>Two Options</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see org.eclipse.xtext.parsetree.reconstr.serializationerror.impl.TwoOptionsImpl * @see org.eclipse.xtext.parsetree.reconstr.serializationerror.impl.SerializationerrorPackageImpl#getTwoOptions() * @generated */ EClass TWO_OPTIONS = eINSTANCE.getTwoOptions(); /** * The meta object literal for the '<em><b>One</b></em>' attribute feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EAttribute TWO_OPTIONS__ONE = eINSTANCE.getTwoOptions_One(); /** * The meta object literal for the '<em><b>Two</b></em>' attribute feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EAttribute TWO_OPTIONS__TWO = eINSTANCE.getTwoOptions_Two(); /** * The meta object literal for the '{@link org.eclipse.xtext.parsetree.reconstr.serializationerror.impl.IndentImpl <em>Indent</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see org.eclipse.xtext.parsetree.reconstr.serializationerror.impl.IndentImpl * @see org.eclipse.xtext.parsetree.reconstr.serializationerror.impl.SerializationerrorPackageImpl#getIndent() * @generated */ EClass INDENT = eINSTANCE.getIndent(); /** * The meta object literal for the '<em><b>Req</b></em>' containment reference feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EReference INDENT__REQ = eINSTANCE.getIndent_Req(); /** * The meta object literal for the '<em><b>Opt</b></em>' containment reference feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EReference INDENT__OPT = eINSTANCE.getIndent_Opt(); /** * The meta object literal for the '<em><b>Indent</b></em>' containment reference list feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EReference INDENT__INDENT = eINSTANCE.getIndent_Indent(); } } //SerializationerrorPackage
epl-1.0
bfg-repo-cleaner-demos/eclipselink.runtime-bfg-strip-big-blobs
moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/typemappinginfo/JavaTypeAdapterMapTypeTestCases.java
3663
/******************************************************************************* * Copyright (c) 1998, 2009 Oracle. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * dmccann - November 17/2009 - 2.0 - Initial implementation ******************************************************************************/ package org.eclipse.persistence.testing.jaxb.typemappinginfo; import java.io.InputStream; import java.lang.annotation.Annotation; import java.util.HashMap; import java.util.Map; import javax.xml.bind.JAXBElement; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import javax.xml.namespace.QName; import org.eclipse.persistence.jaxb.TypeMappingInfo; import org.eclipse.persistence.jaxb.TypeMappingInfo.ElementScope; public class JavaTypeAdapterMapTypeTestCases extends TypeMappingInfoWithJSONTestCases { protected final static String XML_RESOURCE = "org/eclipse/persistence/testing/jaxb/typemappinginfo/maptypeoverride.xml"; protected final static String JSON_RESOURCE = "org/eclipse/persistence/testing/jaxb/typemappinginfo/maptypeoverride.json"; @XmlJavaTypeAdapter(StringStringToIntegerIntegerMapAdapter.class) public Object javaTypeAdapterField; public Map<String, String> theMapField; public JavaTypeAdapterMapTypeTestCases(String name) throws Exception { super(name); init(); } public void init() throws Exception { setControlDocument(XML_RESOURCE); setControlJSON(JSON_RESOURCE); setTypeMappingInfos(getTypeMappingInfos()); } protected TypeMappingInfo[] getTypeMappingInfos()throws Exception { if(typeMappingInfos == null) { typeMappingInfos = new TypeMappingInfo[1]; TypeMappingInfo tmi = new TypeMappingInfo(); tmi.setXmlTagName(new QName("","testTagname")); tmi.setElementScope(ElementScope.Global); tmi.setType(getClass().getField("theMapField").getGenericType()); Annotation[] annotations = new Annotation[1]; annotations[0] = getClass().getField("javaTypeAdapterField").getAnnotations()[0]; tmi.setAnnotations(annotations); typeMappingInfos[0] = tmi; } return typeMappingInfos; } protected Object getControlObject() { Map<String, String> map = new HashMap<String, String>(); map.put("one", "two"); map.put("three", "four"); QName qname = new QName("", "testTagName"); JAXBElement jaxbElement = new JAXBElement(qname,Object.class, null); jaxbElement.setValue(map); return jaxbElement; } public Map<String, InputStream> getControlSchemaFiles(){ InputStream instream = ClassLoader.getSystemResourceAsStream("org/eclipse/persistence/testing/jaxb/typemappinginfo/maptypeoverride.xsd"); Map<String, InputStream> controlSchema = new HashMap<String, InputStream>(); controlSchema.put("", instream); return controlSchema; } protected String getNoXsiTypeControlResourceName() { return XML_RESOURCE; } }
epl-1.0
omcri/cloudrobotics
plugins/omcri.core/src-gen/omcricore/impl/SensorImpl.java
2001
/** * Copyright (c) 2015-2017 Obeo, Inria * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * - William Piers <william.piers@obeo.fr> * - Philippe Merle <philippe.merle@inria.fr> * - Faiez Zalila <faiez.zalila@inria.fr> */ package omcricore.impl; import java.lang.reflect.InvocationTargetException; import java.util.Map; import omcricore.OmcricorePackage; import omcricore.OmcricoreTables; import omcricore.Sensor; import org.eclipse.cmf.occi.core.Entity; import org.eclipse.cmf.occi.core.impl.MixinBaseImpl; import org.eclipse.emf.common.util.DiagnosticChain; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EClass; import org.eclipse.ocl.pivot.evaluation.Executor; import org.eclipse.ocl.pivot.ids.IdResolver; import org.eclipse.ocl.pivot.ids.TypeId; import org.eclipse.ocl.pivot.internal.utilities.PivotUtilInternal; import org.eclipse.ocl.pivot.library.oclany.OclAnyOclIsKindOfOperation; import org.eclipse.ocl.pivot.library.oclany.OclComparableLessThanEqualOperation; import org.eclipse.ocl.pivot.library.string.CGStringGetSeverityOperation; import org.eclipse.ocl.pivot.library.string.CGStringLogDiagnosticOperation; import org.eclipse.ocl.pivot.utilities.ValueUtil; import org.eclipse.ocl.pivot.values.IntegerValue; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Sensor</b></em>'. * <!-- end-user-doc --> * * @generated */ public class SensorImpl extends MixinBaseImpl implements Sensor { /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected SensorImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return OmcricorePackage.Literals.SENSOR; } } //SensorImpl
epl-1.0
orangehero/tc
com.keba.tracecompass.jitter.ui/src/com/keba/tracecompass/jitter/ui/JitterIntervalNodeList.java
1153
/******************************************************************************* * Copyright (c) 2015 * * All rights reserved. This program and the accompanying materials are * made available under the terms of the Eclipse Public License v1.0 which * accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * orangehero - Initial API and implementation *******************************************************************************/ package com.keba.tracecompass.jitter.ui; import java.util.ArrayList; public class JitterIntervalNodeList { private ArrayList<JitterIntervalNode> intervalNodeList; private double jitter; JitterIntervalNodeList(double jit) { jitter = jit; intervalNodeList = new ArrayList<JitterIntervalNode>(); } public boolean addIntervalNode(JitterIntervalNode node) { return intervalNodeList.add(node); } public int size () { return intervalNodeList.size(); } public double getJitter() { return jitter; } public Object [] getContentNodes() { return intervalNodeList.toArray(); } }
epl-1.0
ateso96/HundirLaFlota
Ordenador.java
548
package packModelo; public class Ordenador extends Usuario { private static Ordenador miOrdenador; private Ordenador() { super(); } public static Ordenador getOrdenador() { if(miOrdenador==null){ miOrdenador= new Ordenador(); } return miOrdenador; } public void ponerBarcos() { getFlota().colocarOrdenador(); } public void ponerEscudo() { Escudo miEscudo = delEscudo(); getFlota().ponerEscudoOrdenador(miEscudo); } private Escudo delEscudo() { return getArmamento().delEscudo(); } }
epl-1.0
fqqb/yamcs-studio
bundles/org.csstudio.opibuilder.widgets/src/org/csstudio/opibuilder/widgets/feedback/PointListCreationTool.java
13459
/* * Copyright (c) 2006 Stiftung Deutsches Elektronen-Synchroton, * Member of the Helmholtz Association, (DESY), HAMBURG, GERMANY. * * THIS SOFTWARE IS PROVIDED UNDER THIS LICENSE ON AN "../AS IS" BASIS. * WITHOUT WARRANTY OF ANY KIND, EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED * TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR PARTICULAR PURPOSE AND * NON-INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE * FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR * THE USE OR OTHER DEALINGS IN THE SOFTWARE. SHOULD THE SOFTWARE PROVE DEFECTIVE * IN ANY RESPECT, THE USER ASSUMES THE COST OF ANY NECESSARY SERVICING, REPAIR OR * CORRECTION. THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. * NO USE OF ANY SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER THIS DISCLAIMER. * DESY HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, * OR MODIFICATIONS. * THE FULL LICENSE SPECIFYING FOR THE SOFTWARE THE REDISTRIBUTION, MODIFICATION, * USAGE AND OTHER RIGHTS AND OBLIGATIONS IS INCLUDED WITH THE DISTRIBUTION OF THIS * PROJECT IN THE FILE LICENSE.HTML. IF THE LICENSE IS NOT INCLUDED YOU MAY FIND A COPY * AT HTTP://WWW.DESY.DE/LEGAL/LICENSE.HTM */ package org.csstudio.opibuilder.widgets.feedback; import java.util.ArrayList; import org.eclipse.draw2d.PositionConstants; import org.eclipse.draw2d.geometry.Point; import org.eclipse.draw2d.geometry.PointList; import org.eclipse.draw2d.geometry.PrecisionPoint; import org.eclipse.draw2d.geometry.PrecisionRectangle; import org.eclipse.draw2d.geometry.Rectangle; import org.eclipse.gef.EditPart; import org.eclipse.gef.EditPartViewer; import org.eclipse.gef.Request; import org.eclipse.gef.SnapToHelper; import org.eclipse.gef.requests.CreateRequest; import org.eclipse.gef.requests.CreationFactory; import org.eclipse.gef.tools.TargetingTool; /** * A custom creation tool for PointList dependend widgets. The tool produces a * point list, by interpreting each left click as location for a new point. * * @author Sven Wende, Xihui Chen * */ public final class PointListCreationTool extends TargetingTool { /** * Property to be used in AbstractTool#setProperties(java.util.Map) for * {@link #setFactory(CreationFactory)}. */ public static final Object PROPERTY_CREATION_FACTORY = "factory"; /** * The creation factory. */ private CreationFactory _factory; /** * The point list, which is manipulated by this tool. */ private PointList _points = new PointList(); /** * List of common EditPart. * * This maintains the list of common EditParts where all * the points belong to. The first element of this * list is the descendant EditPart where all points belong * to. The second element is the parent of the first, and * the third element is the parent of the second, and so * on. The last element of this list is the root EditPart. */ private ArrayList<EditPart> commonEditParts = null; /** * A SnapToHelper. */ private SnapToHelper _snap2Helper; /** * Default constructor. */ public PointListCreationTool() { super(); } /** * {@inheritDoc} */ @Override protected void applyProperty(final Object key, final Object value) { if (PROPERTY_CREATION_FACTORY.equals(key)) { if (value instanceof CreationFactory) { setFactory((CreationFactory) value); } return; } super.applyProperty(key, value); } /** * {@inheritDoc} */ @Override protected Request createTargetRequest() { _points = new PointList(); CreateRequest request = new CreateRequest(); request.setFactory(getFactory()); return request; } /** * {@inheritDoc} */ @Override public void deactivate() { super.deactivate(); _snap2Helper = null; } /** * {@inheritDoc} */ @Override protected String getCommandName() { return REQ_CREATE; } /** * Cast the target request to a CreateRequest and returns it. * * @return the target request as a CreateRequest * @see TargetingTool#getTargetRequest() */ protected CreateRequest getCreateRequest() { return (CreateRequest) getTargetRequest(); } /** * {@inheritDoc} */ @Override protected String getDebugName() { return "Creation Tool"; } /** * Returns the creation factory used to create the new EditParts. * * @return the creation factory */ protected CreationFactory getFactory() { return _factory; } @Override protected boolean handleDoubleClick(int button) { // only react on left clicks if (button != 1) { setState(STATE_INVALID); return true; } // remove the last point, which was just created for previewing the // next axis _points.removePoint(_points.size() - 1); // perform creation of the material if (stateTransition(STATE_DRAG | STATE_DRAG_IN_PROGRESS, STATE_TERMINAL)) { eraseTargetFeedback(); unlockTargetEditPart(); performCreation(button); } // terminate setState(STATE_TERMINAL); handleFinished(); updateTargetRequest(); setCurrentCommand(getCommand()); return true; } /** * {@inheritDoc} */ @Override protected boolean handleButtonDown(final int button) { if (getTargetEditPart() != null) { _snap2Helper = getTargetEditPart().getAdapter(SnapToHelper.class); } // only react on left clicks if (button != 1) { setState(STATE_INVALID); return true; } // the tool is in progress mode, until a doubleclick occurs setState(STATE_DRAG_IN_PROGRESS); // handle clicks Point p = getSnapedLocation(); if (_points.size() == 0) { // add a new point _points.addPoint(p); } else { // override the last point, which was the "preview" point before _points.setPoint(p, _points.size() - 1); } // add an additional point, which is just for previewing the next // axis in the graphical feedback _points.addPoint(p); if (commonEditParts == null) { // This is the first point. Register all ancestors to the list. commonEditParts = new ArrayList<EditPart>(); EditPart ep = getTargetEditPart(); while (ep != null) { commonEditParts.add(ep); ep = ep.getParent(); } } else { // Remove all EditParts which the added point does not belong to. int index = commonEditParts.indexOf(getTargetEditPart()); if (index == -1) { commonEditParts.clear(); } else { for (int i=0; i<index; i++) { commonEditParts.remove(i); } } } updateTargetRequest(); setCurrentCommand(getCommand()); return true; } /** * {@inheritDoc} */ @Override protected boolean handleButtonUp(final int button) { return true; } /** * {@inheritDoc} */ @Override protected boolean handleDragInProgress() { if (isInState(STATE_DRAG_IN_PROGRESS)) { updateTargetRequest(); setCurrentCommand(getCommand()); showTargetFeedback(); } return true; } /** * {@inheritDoc} */ @Override protected boolean handleDragStarted() { return stateTransition(STATE_DRAG, STATE_DRAG_IN_PROGRESS); } /** * {@inheritDoc} */ @Override protected boolean handleFocusLost() { if (isInState(STATE_DRAG | STATE_DRAG_IN_PROGRESS)) { eraseTargetFeedback(); setState(STATE_INVALID); handleFinished(); return true; } return false; } /** * {@inheritDoc} */ @Override protected boolean handleHover() { if (isInState(STATE_INITIAL)) { updateAutoexposeHelper(); } return true; } /** * {@inheritDoc} */ @Override protected boolean handleMove() { if (getState() != STATE_TERMINAL && getState() != STATE_INVALID) { if (_points.size() > 0) { // snap PrecisionPoint location = getSnapedLocation(); // update the last point in the list to update the graphical // feedback _points.setPoint(location, _points.size() - 1); } updateTargetRequest(); updateTargetUnderMouse(); setCurrentCommand(getCommand()); showTargetFeedback(); return true; } return false; } /** * Gets the "snapped" location based on the current location of the mouse. * * @return the point of the snapped location */ private PrecisionPoint getSnapedLocation() { CreateRequest req = getCreateRequest(); PrecisionPoint location = new PrecisionPoint(getLocation().x, getLocation().y); if (_snap2Helper != null) { _snap2Helper.snapPoint(req, PositionConstants.NORTH_WEST, new PrecisionPoint(getLocation().x, getLocation().y), location); } return location; } /** * Executes the current command and selects the newly created object. The * button that was released to cause this creation is passed in, but since * {@link #handleButtonDown(int)} goes into the invalid state if the button * pressed is not button 1, this will always be button 1. * * @param button * the button that was pressed */ protected void performCreation(final int button) { EditPartViewer viewer = getCurrentViewer(); executeCurrentCommand(); selectAddedObject(viewer); } /** * Add the newly created object to the viewer's selected objects. * * @param viewer * the EditPartViewer */ private void selectAddedObject(final EditPartViewer viewer) { final Object model = getCreateRequest().getNewObject(); if (model == null || viewer == null) { return; } Object editpart = viewer.getEditPartRegistry().get(model); if (editpart instanceof EditPart) { // Force the new object to get positioned in the viewer. viewer.flush(); if(((EditPart) editpart).isSelectable()) viewer.select((EditPart) editpart); } } /** * Sets the creation factory used to create the new edit parts. * * @param factory * the factory */ public void setFactory(final CreationFactory factory) { _factory = factory; } /** * {@inheritDoc} */ @Override @SuppressWarnings("unchecked") protected void updateTargetRequest() { CreateRequest req = getCreateRequest(); if (isInState(STATE_DRAG_IN_PROGRESS)) { // use the rectangle, which is defined by the point lists as new // bounds Rectangle bounds = _points.getBounds(); req.setSize(bounds.getSize()); req.setLocation(bounds.getLocation()); req.getExtendedData().put(AbstractPolyFeedbackFactory.PROP_POINTS, _points); // req.getExtendedData().clear(); if (!getCurrentInput().isAltKeyDown() && _snap2Helper != null) { PrecisionRectangle baseRect = new PrecisionRectangle(bounds); PrecisionRectangle result = baseRect.getPreciseCopy(); _snap2Helper.snapRectangle(req, PositionConstants.NSEW, baseRect, result); req.setLocation(result.getLocation()); req.setSize(result.getSize()); } } else { req.setSize(null); req.setLocation(getLocation()); } } @Override protected EditPartViewer.Conditional getTargetingConditional() { return new EditPartViewer.Conditional() { public boolean evaluate(EditPart editpart) { EditPart targetEditPart = editpart.getTargetEditPart(getTargetRequest()); if (targetEditPart == null) return false; // If there is no point, the EditPart under the mouse is the target. if (commonEditParts == null) return true; // If the EditPart under the mouse is not listed in the list of EditPart, // it cannot be the target. return commonEditParts.contains(targetEditPart); } }; } }
epl-1.0
akervern/che
wsmaster/che-core-api-devfile/src/test/java/org/eclipse/che/api/devfile/server/convert/component/dockerimage/DockerimageComponentProvisionerTest.java
16219
/* * Copyright (c) 2012-2018 Red Hat, Inc. * This program and the accompanying materials are made * available under the terms of the Eclipse Public License 2.0 * which is available at https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 * * Contributors: * Red Hat, Inc. - initial API and implementation */ package org.eclipse.che.api.devfile.server.convert.component.dockerimage; import static java.util.Arrays.asList; import static java.util.Collections.emptyList; import static java.util.Collections.emptyMap; import static org.eclipse.che.api.core.model.workspace.config.MachineConfig.MEMORY_LIMIT_ATTRIBUTE; import static org.eclipse.che.api.devfile.server.Constants.PUBLIC_ENDPOINT_ATTRIBUTE; import static org.eclipse.che.api.workspace.shared.Constants.PROJECTS_VOLUME_NAME; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; import com.google.common.collect.ImmutableMap; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import org.eclipse.che.api.devfile.server.exception.WorkspaceExportException; import org.eclipse.che.api.workspace.server.model.impl.EnvironmentImpl; import org.eclipse.che.api.workspace.server.model.impl.MachineConfigImpl; import org.eclipse.che.api.workspace.server.model.impl.RecipeImpl; import org.eclipse.che.api.workspace.server.model.impl.ServerConfigImpl; import org.eclipse.che.api.workspace.server.model.impl.WorkspaceConfigImpl; import org.eclipse.che.api.workspace.server.model.impl.devfile.ComponentImpl; import org.eclipse.che.api.workspace.server.model.impl.devfile.DevfileImpl; import org.eclipse.che.api.workspace.server.model.impl.devfile.EndpointImpl; import org.eclipse.che.api.workspace.server.model.impl.devfile.EnvImpl; import org.eclipse.che.api.workspace.server.model.impl.devfile.VolumeImpl; import org.eclipse.che.workspace.infrastructure.docker.environment.dockerimage.DockerImageEnvironment; import org.eclipse.che.workspace.infrastructure.kubernetes.environment.util.EntryPoint; import org.eclipse.che.workspace.infrastructure.kubernetes.environment.util.EntryPointParser; import org.mockito.Mock; import org.mockito.testng.MockitoTestNGListener; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Listeners; import org.testng.annotations.Test; /** @author Sergii Leshchenko */ @Listeners(MockitoTestNGListener.class) public class DockerimageComponentProvisionerTest { private DockerimageComponentProvisioner dockerimageComponentProvisioner; @Mock private EntryPointParser entryPointParser; @BeforeMethod public void setUp() throws Exception { dockerimageComponentProvisioner = new DockerimageComponentProvisioner(entryPointParser); when(entryPointParser.parse(any())).thenReturn(new EntryPoint(emptyList(), emptyList())); } @Test( expectedExceptions = WorkspaceExportException.class, expectedExceptionsMessageRegExp = "Workspace with multiple `dockerimage` environments can not be converted to devfile") public void shouldThrowExceptionIfWorkspaceHasMultipleEnvironmentsWithKubernetesOpenShiftRecipes() throws Exception { // given WorkspaceConfigImpl workspaceConfig = new WorkspaceConfigImpl(); EnvironmentImpl dockerimageEnv1 = new EnvironmentImpl(); dockerimageEnv1.setRecipe(new RecipeImpl(DockerImageEnvironment.TYPE, null, null, null)); workspaceConfig.getEnvironments().put("dockerimage1", dockerimageEnv1); EnvironmentImpl dockerimageEnv2 = new EnvironmentImpl(); dockerimageEnv2.setRecipe(new RecipeImpl(DockerImageEnvironment.TYPE, null, null, null)); workspaceConfig.getEnvironments().put("dockerimage2", dockerimageEnv2); // when dockerimageComponentProvisioner.provision(new DevfileImpl(), workspaceConfig); } @Test public void shouldNoNothingIfWorkspaceDoesNotHaveEnvironmentsWithKubernetesOpenShiftRecipes() throws Exception { // given WorkspaceConfigImpl workspaceConfig = new WorkspaceConfigImpl(); EnvironmentImpl anotherEnv = new EnvironmentImpl(); anotherEnv.setRecipe(new RecipeImpl("nonDockerimage", null, null, null)); workspaceConfig.getEnvironments().put("anotherEnv", anotherEnv); // when dockerimageComponentProvisioner.provision(new DevfileImpl(), workspaceConfig); } @Test public void shouldProvisionDockerimageComponentWhenDockerimageEnvironmentHasNoMachineConfiguration() throws Exception { // given EnvironmentImpl dockerEnv = new EnvironmentImpl(); dockerEnv.setRecipe(new RecipeImpl("dockerimage", null, "eclipse/ubuntu_jdk8:latest", null)); WorkspaceConfigImpl workspaceConfig = new WorkspaceConfigImpl(); workspaceConfig.getEnvironments().put("dockerEnv", dockerEnv); DevfileImpl devfile = new DevfileImpl(); // when dockerimageComponentProvisioner.provision(devfile, workspaceConfig); // then assertEquals(devfile.getComponents().size(), 1); ComponentImpl dockerimageComponent = devfile.getComponents().get(0); assertEquals(dockerimageComponent.getAlias(), "dockerEnv"); assertEquals(dockerimageComponent.getImage(), "eclipse/ubuntu_jdk8:latest"); } @Test( expectedExceptions = WorkspaceExportException.class, expectedExceptionsMessageRegExp = "Environment with 'dockerimage' recipe must contain only one machine configuration") public void shouldThrowAnExceptionIfTryToProvisionDockerimageComponentWhenDockerimageEnvironmentWithMultipleMachinesConfiguration() throws Exception { // given EnvironmentImpl dockerEnv = new EnvironmentImpl(); dockerEnv.setRecipe(new RecipeImpl("dockerimage", null, "eclipse/ubuntu_jdk8:latest", null)); dockerEnv .getMachines() .put( "machine1", new MachineConfigImpl(emptyList(), emptyMap(), emptyMap(), emptyMap(), emptyMap())); dockerEnv .getMachines() .put( "machine2", new MachineConfigImpl(emptyList(), emptyMap(), emptyMap(), emptyMap(), emptyMap())); WorkspaceConfigImpl workspaceConfig = new WorkspaceConfigImpl(); workspaceConfig.getEnvironments().put("dockerEnv", dockerEnv); DevfileImpl devfile = new DevfileImpl(); // when dockerimageComponentProvisioner.provision(devfile, workspaceConfig); // then assertEquals(devfile.getComponents().size(), 1); ComponentImpl dockerimageComponent = devfile.getComponents().get(0); assertEquals(dockerimageComponent.getAlias(), "dockerEnv"); assertEquals(dockerimageComponent.getId(), "eclipse/ubuntu_jdk8:latest"); } @Test public void shouldProvisionDockerimageComponentIfDockerimageEnvironmentWithMachineConfigurationWithServerIsProvided() throws Exception { // given EnvironmentImpl dockerEnv = new EnvironmentImpl(); dockerEnv.setRecipe(new RecipeImpl("dockerimage", null, "eclipse/ubuntu_jdk8:latest", null)); ServerConfigImpl serverConfig = new ServerConfigImpl( "8080/TCP", "http", "/api", ImmutableMap.of(PUBLIC_ENDPOINT_ATTRIBUTE, "true")); dockerEnv .getMachines() .put( "myMachine", new MachineConfigImpl( emptyList(), ImmutableMap.of("server", serverConfig), emptyMap(), emptyMap(), emptyMap())); WorkspaceConfigImpl workspaceConfig = new WorkspaceConfigImpl(); workspaceConfig.getEnvironments().put("dockerEnv", dockerEnv); DevfileImpl devfile = new DevfileImpl(); // when dockerimageComponentProvisioner.provision(devfile, workspaceConfig); // then assertEquals(devfile.getComponents().size(), 1); ComponentImpl dockerimageComponent = devfile.getComponents().get(0); assertEquals(dockerimageComponent.getEndpoints().size(), 1); EndpointImpl endpoint = dockerimageComponent.getEndpoints().get(0); assertEquals(endpoint.getName(), "server"); assertEquals(endpoint.getPort(), new Integer(8080)); assertEquals(endpoint.getAttributes().size(), 3); assertEquals(endpoint.getAttributes().get("protocol"), "http"); assertEquals(endpoint.getAttributes().get("path"), "/api"); assertEquals(endpoint.getAttributes().get(PUBLIC_ENDPOINT_ATTRIBUTE), "true"); } @Test public void shouldProvisionDockerimageComponentIfDockerimageEnvironmentWithMachineConfigurationWithServerIsSpecifiedButPathAndProtocolAreMissing() throws Exception { // given EnvironmentImpl dockerEnv = new EnvironmentImpl(); dockerEnv.setRecipe(new RecipeImpl("dockerimage", null, "eclipse/ubuntu_jdk8:latest", null)); ServerConfigImpl serverConfig = new ServerConfigImpl("8080/TCP", null, null, emptyMap()); dockerEnv .getMachines() .put( "myMachine", new MachineConfigImpl( emptyList(), ImmutableMap.of("server", serverConfig), emptyMap(), emptyMap(), emptyMap())); WorkspaceConfigImpl workspaceConfig = new WorkspaceConfigImpl(); workspaceConfig.getEnvironments().put("dockerEnv", dockerEnv); DevfileImpl devfile = new DevfileImpl(); // when dockerimageComponentProvisioner.provision(devfile, workspaceConfig); // then assertEquals(devfile.getComponents().size(), 1); ComponentImpl dockerimageComponent = devfile.getComponents().get(0); assertEquals(dockerimageComponent.getEndpoints().size(), 1); EndpointImpl endpoint = dockerimageComponent.getEndpoints().get(0); assertEquals(endpoint.getName(), "server"); assertEquals(endpoint.getPort(), new Integer(8080)); assertTrue(endpoint.getAttributes().isEmpty()); } @Test public void shouldProvisionDockerimageComponentIfDockerimageEnvironmentWithMachineConfigurationWithEnvVarsIsSpecified() throws Exception { // given EnvironmentImpl dockerEnv = new EnvironmentImpl(); dockerEnv.setRecipe(new RecipeImpl("dockerimage", null, "eclipse/ubuntu_jdk8:latest", null)); Map<String, String> env = ImmutableMap.of("key1", "value1", "key2", "value2"); dockerEnv .getMachines() .put( "myMachine", new MachineConfigImpl(emptyList(), emptyMap(), env, emptyMap(), emptyMap())); WorkspaceConfigImpl workspaceConfig = new WorkspaceConfigImpl(); workspaceConfig.getEnvironments().put("dockerEnv", dockerEnv); DevfileImpl devfile = new DevfileImpl(); // when dockerimageComponentProvisioner.provision(devfile, workspaceConfig); // then assertEquals(devfile.getComponents().size(), 1); ComponentImpl dockerimageComponent = devfile.getComponents().get(0); List<EnvImpl> ComponentEnv = dockerimageComponent.getEnv(); assertEquals(ComponentEnv.size(), 2); Optional<EnvImpl> env1Opt = ComponentEnv.stream().filter(e -> e.getName().equals("key1")).findAny(); assertTrue(env1Opt.isPresent()); assertEquals(env1Opt.get().getValue(), "value1"); Optional<EnvImpl> env2Opt = ComponentEnv.stream().filter(e -> e.getName().equals("key2")).findAny(); assertTrue(env2Opt.isPresent()); assertEquals(env2Opt.get().getValue(), "value2"); } @Test public void shouldProvisionDockerimageComponentIfDockerimageEnvironmentWithMachineConfigurationWithVolumesIsSpecified() throws Exception { // given EnvironmentImpl dockerEnv = new EnvironmentImpl(); dockerEnv.setRecipe(new RecipeImpl("dockerimage", null, "eclipse/ubuntu_jdk8:latest", null)); Map<String, org.eclipse.che.api.workspace.server.model.impl.VolumeImpl> volumes = ImmutableMap.of( "data", new org.eclipse.che.api.workspace.server.model.impl.VolumeImpl().withPath("/tmp/data")); dockerEnv .getMachines() .put( "myMachine", new MachineConfigImpl(emptyList(), emptyMap(), emptyMap(), emptyMap(), volumes)); WorkspaceConfigImpl workspaceConfig = new WorkspaceConfigImpl(); workspaceConfig.getEnvironments().put("dockerEnv", dockerEnv); DevfileImpl devfile = new DevfileImpl(); // when dockerimageComponentProvisioner.provision(devfile, workspaceConfig); // then assertEquals(devfile.getComponents().size(), 1); ComponentImpl dockerimageComponent = devfile.getComponents().get(0); assertEquals(dockerimageComponent.getVolumes().size(), 1); VolumeImpl volume = dockerimageComponent.getVolumes().get(0); assertEquals(volume.getName(), "data"); assertEquals(volume.getContainerPath(), "/tmp/data"); } @Test public void shouldProvisionDockerimageComponentIfDockerimageEnvironmentWithMachineConfigurationWithProjectVolumeIfSpecified() throws Exception { // given EnvironmentImpl dockerEnv = new EnvironmentImpl(); dockerEnv.setRecipe(new RecipeImpl("dockerimage", null, "eclipse/ubuntu_jdk8:latest", null)); Map<String, org.eclipse.che.api.workspace.server.model.impl.VolumeImpl> volumes = ImmutableMap.of( PROJECTS_VOLUME_NAME, new org.eclipse.che.api.workspace.server.model.impl.VolumeImpl().withPath("/projects")); dockerEnv .getMachines() .put( "myMachine", new MachineConfigImpl(emptyList(), emptyMap(), emptyMap(), emptyMap(), volumes)); WorkspaceConfigImpl workspaceConfig = new WorkspaceConfigImpl(); workspaceConfig.getEnvironments().put("dockerEnv", dockerEnv); DevfileImpl devfile = new DevfileImpl(); // when dockerimageComponentProvisioner.provision(devfile, workspaceConfig); // then assertEquals(devfile.getComponents().size(), 1); ComponentImpl dockerimageComponent = devfile.getComponents().get(0); assertTrue(dockerimageComponent.getVolumes().isEmpty()); assertTrue(dockerimageComponent.getMountSources()); } @Test public void shouldProvisionDockerimageComponentIfDockerimageEnvironmentWithMachineConfigurationWithMemoryLimitSet() throws Exception { // given EnvironmentImpl dockerEnv = new EnvironmentImpl(); dockerEnv.setRecipe(new RecipeImpl("dockerimage", null, "eclipse/ubuntu_jdk8:latest", null)); Map<String, String> attributes = new HashMap<>(); attributes.put(MEMORY_LIMIT_ATTRIBUTE, "1G"); dockerEnv .getMachines() .put( "myMachine", new MachineConfigImpl(emptyList(), emptyMap(), emptyMap(), attributes, emptyMap())); WorkspaceConfigImpl workspaceConfig = new WorkspaceConfigImpl(); workspaceConfig.getEnvironments().put("dockerEnv", dockerEnv); DevfileImpl devfile = new DevfileImpl(); // when dockerimageComponentProvisioner.provision(devfile, workspaceConfig); // then assertEquals(devfile.getComponents().size(), 1); ComponentImpl dockerimageComponent = devfile.getComponents().get(0); assertEquals(dockerimageComponent.getMemoryLimit(), "1G"); } @Test public void shouldIncludeEntrypointPropertiesWhenSpecifiedInTheEnvironment() throws Exception { // given EnvironmentImpl dockerEnv = new EnvironmentImpl(); dockerEnv.setRecipe(new RecipeImpl("dockerimage", null, "eclipse/ubuntu_jdk8:latest", null)); dockerEnv .getMachines() .put( "myMachine", new MachineConfigImpl(emptyList(), emptyMap(), emptyMap(), emptyMap(), emptyMap())); WorkspaceConfigImpl workspaceConfig = new WorkspaceConfigImpl(); workspaceConfig.getEnvironments().put("dockerEnv", dockerEnv); when(entryPointParser.parse(any())) .thenReturn(new EntryPoint(asList("/bin/sh", "-c"), asList("echo", "hi"))); DevfileImpl devfile = new DevfileImpl(); // when dockerimageComponentProvisioner.provision(devfile, workspaceConfig); // then assertEquals(devfile.getComponents().size(), 1); ComponentImpl Component = devfile.getComponents().get(0); assertEquals(Component.getCommand(), asList("/bin/sh", "-c")); assertEquals(Component.getArgs(), asList("echo", "hi")); } }
epl-1.0
muros-ct/kapua
locator/service/src/main/java/org/eclipse/kapua/model/query/KapuaQuery.java
2305
/******************************************************************************* * Copyright (c) 2011, 2016 Eurotech and/or its affiliates and others * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Eurotech - initial API and implementation * *******************************************************************************/ package org.eclipse.kapua.model.query; import org.eclipse.kapua.model.KapuaEntity; import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.model.query.predicate.KapuaPredicate; /** * Kapua query definition. * * @param <E> query entity domain */ public interface KapuaQuery<E extends KapuaEntity> { /** * Get the query offset * * @return */ public Integer getOffset(); /** * Get the query limit * * @return */ public Integer getLimit(); /** * set the query offset * * @param offset */ public void setOffset(Integer offset); /** * Set the query limit * * @param limit */ public void setLimit(Integer limit); /** * Set the code identifier * * @param scopeId */ public void setScopeId(KapuaId scopeId); /** * get the scope identifier * * @return */ public KapuaId getScopeId(); /** * Set the query predicate * * @param queryPredicate */ public void setPredicate(KapuaPredicate queryPredicate); /** * Get the query predicate * * @return */ public KapuaPredicate getPredicate(); /** * Set query sort criteria * * @param sortCriteria */ public void setSortCriteria(KapuaSortCriteria sortCriteria); /** * Get query sort criteria * * @return */ public KapuaSortCriteria getSortCriteria(); /** * Get query fetch style * * @return */ public KapuaFetchStyle getFetchStyle(); /** * Set query fetch style * * @param fetchStyle */ public void setFetchStyle(KapuaFetchStyle fetchStyle); }
epl-1.0
boniatillo-com/PhaserEditor
source/v2/phasereditor/phasereditor.webrun.core/src/phasereditor/webrun/core/PhaserExampleCategoryServlet.java
3276
// The MIT License (MIT) // // Copyright (c) 2015, 2017 Arian Fornaris // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: The above copyright notice and this permission // notice shall be included in all copies or substantial portions of the // Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. package phasereditor.webrun.core; import java.io.IOException; import java.io.PrintStream; import java.nio.file.Path; import java.util.Optional; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import phasereditor.inspect.core.InspectCore; import phasereditor.inspect.core.examples.PhaserExampleCategoryModel; import phasereditor.inspect.core.examples.PhaserExampleModel; /** * @author arian * */ public class PhaserExampleCategoryServlet extends HttpServlet { private static final long serialVersionUID = 1L; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { PrintStream out = new PrintStream(resp.getOutputStream()); String name = req.getParameter("n"); String fname = name.replace("%20", " "); resp.setContentType("text/html"); out.println("<!DOCTYPE html>"); out.println("<html>"); out.println("<body style='font-family:arial;margin:1em'>"); Optional<PhaserExampleCategoryModel> opt = InspectCore.getPhaserExamplesRepoModel().getExamplesCategories().stream() .filter(c -> c.getName().equals(fname)).findFirst(); if (opt.isPresent()) { PhaserExampleCategoryModel cat = opt.get(); out.println("<h1>" + cat.getName() + "</h1>"); out.println("<small><i>Hosted locally by Phaser Editor</i></small><br><br>"); out.println("<a href='/phaser-examples'>Examples</a><br><br>"); Path root = InspectCore.getBundleFile(InspectCore.RESOURCES_EXAMPLES_PLUGIN, "phaser3-examples/public/"); for (PhaserExampleModel example : cat.getTemplates()) { String url = root.relativize(example.getMainFilePath()).toString().replace("\\", "/"); out.println("<a href='/phaser-example?n=" + url + "'>" + example.getName() + "</a>"); out.println("<br>"); } } else { out.println("Category '" + fname + "' not found."); } out.println("</body>"); out.println("</html>"); } }
epl-1.0
paulianttila/openhab2
bundles/org.openhab.binding.nikohomecontrol/src/main/java/org/openhab/binding/nikohomecontrol/internal/handler/NikoHomeControlThermostatHandler.java
12982
/** * Copyright (c) 2010-2021 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.nikohomecontrol.internal.handler; import static org.openhab.binding.nikohomecontrol.internal.NikoHomeControlBindingConstants.*; import static org.openhab.core.library.unit.SIUnits.CELSIUS; import static org.openhab.core.types.RefreshType.REFRESH; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import javax.measure.quantity.Temperature; import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.Nullable; import org.openhab.binding.nikohomecontrol.internal.protocol.NhcThermostat; import org.openhab.binding.nikohomecontrol.internal.protocol.NhcThermostatEvent; import org.openhab.binding.nikohomecontrol.internal.protocol.NikoHomeControlCommunication; import org.openhab.binding.nikohomecontrol.internal.protocol.nhc2.NhcThermostat2; import org.openhab.core.library.types.DecimalType; import org.openhab.core.library.types.QuantityType; import org.openhab.core.thing.Bridge; import org.openhab.core.thing.ChannelUID; import org.openhab.core.thing.Thing; import org.openhab.core.thing.ThingStatus; import org.openhab.core.thing.ThingStatusDetail; import org.openhab.core.thing.binding.BaseThingHandler; import org.openhab.core.types.Command; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The {@link NikoHomeControlThermostatHandler} is responsible for handling commands, which are * sent to one of the channels. * * @author Mark Herwege - Initial Contribution */ @NonNullByDefault public class NikoHomeControlThermostatHandler extends BaseThingHandler implements NhcThermostatEvent { private final Logger logger = LoggerFactory.getLogger(NikoHomeControlThermostatHandler.class); private volatile @Nullable NhcThermostat nhcThermostat; private String thermostatId = ""; private int overruleTime; private volatile @Nullable ScheduledFuture<?> refreshTimer; // used to refresh the remaining overrule time every // minute public NikoHomeControlThermostatHandler(Thing thing) { super(thing); } @Override public void handleCommand(ChannelUID channelUID, Command command) { NikoHomeControlCommunication nhcComm = getCommunication(); if (nhcComm == null) { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "Bridge communication not initialized when trying to execute thermostat command on " + thermostatId); return; } // This can be expensive, therefore do it in a job. scheduler.submit(() -> { if (!nhcComm.communicationActive()) { restartCommunication(nhcComm); } if (nhcComm.communicationActive()) { handleCommandSelection(channelUID, command); } }); } private void handleCommandSelection(ChannelUID channelUID, Command command) { NhcThermostat nhcThermostat = this.nhcThermostat; if (nhcThermostat == null) { logger.debug("thermostat with ID {} not initialized", thermostatId); return; } logger.debug("handle command {} for {}", command, channelUID); if (REFRESH.equals(command)) { thermostatEvent(nhcThermostat.getMeasured(), nhcThermostat.getSetpoint(), nhcThermostat.getMode(), nhcThermostat.getOverrule(), nhcThermostat.getDemand()); return; } switch (channelUID.getId()) { case CHANNEL_MEASURED: case CHANNEL_DEMAND: updateStatus(ThingStatus.ONLINE); break; case CHANNEL_MODE: if (command instanceof DecimalType) { nhcThermostat.executeMode(((DecimalType) command).intValue()); } updateStatus(ThingStatus.ONLINE); break; case CHANNEL_SETPOINT: QuantityType<Temperature> setpoint = null; if (command instanceof QuantityType) { setpoint = ((QuantityType<Temperature>) command).toUnit(CELSIUS); // Always set the new setpoint temperature as an overrule // If no overrule time is given yet, set the overrule time to the configuration parameter int time = nhcThermostat.getOverruletime(); if (time <= 0) { time = overruleTime; } if (setpoint != null) { nhcThermostat.executeOverrule(Math.round(setpoint.floatValue() * 10), time); } } updateStatus(ThingStatus.ONLINE); break; case CHANNEL_OVERRULETIME: if (command instanceof DecimalType) { int overruletime = ((DecimalType) command).intValue(); int overrule = nhcThermostat.getOverrule(); if (overruletime <= 0) { overruletime = 0; overrule = 0; } nhcThermostat.executeOverrule(overrule, overruletime); } updateStatus(ThingStatus.ONLINE); break; default: updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, "Channel unknown " + channelUID.getId()); } } @Override public void initialize() { NikoHomeControlThermostatConfig config = getConfig().as(NikoHomeControlThermostatConfig.class); thermostatId = config.thermostatId; overruleTime = config.overruleTime; NikoHomeControlCommunication nhcComm = getCommunication(); if (nhcComm == null) { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, "Connection with controller not started yet, could not initialize thermostat " + thermostatId); return; } // We need to do this in a separate thread because we may have to wait for the // communication to become active scheduler.submit(() -> { if (!nhcComm.communicationActive()) { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, "No connection with controller, could not initialize thermostat " + thermostatId); return; } NhcThermostat nhcThermostat = nhcComm.getThermostats().get(thermostatId); if (nhcThermostat == null) { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "Thermostat " + thermostatId + " does not match a thermostat in the controller"); return; } nhcThermostat.setEventHandler(this); updateProperties(); String thermostatLocation = nhcThermostat.getLocation(); if (thing.getLocation() == null) { thing.setLocation(thermostatLocation); } thermostatEvent(nhcThermostat.getMeasured(), nhcThermostat.getSetpoint(), nhcThermostat.getMode(), nhcThermostat.getOverrule(), nhcThermostat.getDemand()); this.nhcThermostat = nhcThermostat; logger.debug("thermostat intialized {}", thermostatId); Bridge bridge = getBridge(); if ((bridge != null) && (bridge.getStatus() == ThingStatus.ONLINE)) { updateStatus(ThingStatus.ONLINE); } else { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_OFFLINE); } }); } private void updateProperties() { Map<String, String> properties = new HashMap<>(); if (nhcThermostat instanceof NhcThermostat2) { NhcThermostat2 thermostat = (NhcThermostat2) nhcThermostat; properties.put("model", thermostat.getModel()); properties.put("technology", thermostat.getTechnology()); } thing.setProperties(properties); } @Override public void thermostatEvent(int measured, int setpoint, int mode, int overrule, int demand) { NhcThermostat nhcThermostat = this.nhcThermostat; if (nhcThermostat == null) { logger.debug("thermostat with ID {} not initialized", thermostatId); return; } updateState(CHANNEL_MEASURED, new QuantityType<>(nhcThermostat.getMeasured() / 10.0, CELSIUS)); int overruletime = nhcThermostat.getRemainingOverruletime(); updateState(CHANNEL_OVERRULETIME, new DecimalType(overruletime)); // refresh the remaining time every minute scheduleRefreshOverruletime(nhcThermostat); // If there is an overrule temperature set, use this in the setpoint channel, otherwise use the original // setpoint temperature if (overruletime == 0) { updateState(CHANNEL_SETPOINT, new QuantityType<>(setpoint / 10.0, CELSIUS)); } else { updateState(CHANNEL_SETPOINT, new QuantityType<>(overrule / 10.0, CELSIUS)); } updateState(CHANNEL_MODE, new DecimalType(mode)); updateState(CHANNEL_DEMAND, new DecimalType(demand)); updateStatus(ThingStatus.ONLINE); } /** * Method to update state of overruletime channel every minute with remaining time. * * @param NhcThermostat object * */ private void scheduleRefreshOverruletime(NhcThermostat nhcThermostat) { cancelRefreshTimer(); if (nhcThermostat.getRemainingOverruletime() <= 0) { return; } refreshTimer = scheduler.scheduleWithFixedDelay(() -> { int remainingTime = nhcThermostat.getRemainingOverruletime(); updateState(CHANNEL_OVERRULETIME, new DecimalType(remainingTime)); if (remainingTime <= 0) { cancelRefreshTimer(); } }, 1, 1, TimeUnit.MINUTES); } private void cancelRefreshTimer() { ScheduledFuture<?> timer = refreshTimer; if (timer != null) { timer.cancel(true); } refreshTimer = null; } @Override public void thermostatInitialized() { Bridge bridge = getBridge(); if ((bridge != null) && (bridge.getStatus() == ThingStatus.ONLINE)) { updateStatus(ThingStatus.ONLINE); } } @Override public void thermostatRemoved() { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "Thermostat " + thermostatId + " has been removed from the controller"); } private void restartCommunication(NikoHomeControlCommunication nhcComm) { // We lost connection but the connection object is there, so was correctly started. // Try to restart communication. nhcComm.restartCommunication(); // If still not active, take thing offline and return. if (!nhcComm.communicationActive()) { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, "Communication error"); return; } // Also put the bridge back online NikoHomeControlBridgeHandler nhcBridgeHandler = getBridgeHandler(); if (nhcBridgeHandler != null) { nhcBridgeHandler.bridgeOnline(); } } private @Nullable NikoHomeControlCommunication getCommunication() { NikoHomeControlBridgeHandler nhcBridgeHandler = getBridgeHandler(); if (nhcBridgeHandler == null) { updateStatus(ThingStatus.UNINITIALIZED, ThingStatusDetail.BRIDGE_UNINITIALIZED, "No bridge initialized for thermostat " + thermostatId); return null; } NikoHomeControlCommunication nhcComm = nhcBridgeHandler.getCommunication(); return nhcComm; } private @Nullable NikoHomeControlBridgeHandler getBridgeHandler() { Bridge nhcBridge = getBridge(); if (nhcBridge == null) { updateStatus(ThingStatus.UNINITIALIZED, ThingStatusDetail.BRIDGE_UNINITIALIZED, "No bridge initialized for thermostat " + thermostatId); return null; } NikoHomeControlBridgeHandler nhcBridgeHandler = (NikoHomeControlBridgeHandler) nhcBridge.getHandler(); return nhcBridgeHandler; } }
epl-1.0