code
stringlengths 5
1.04M
| repo_name
stringlengths 7
108
| path
stringlengths 6
299
| language
stringclasses 1
value | license
stringclasses 15
values | size
int64 5
1.04M
|
---|---|---|---|---|---|
package org.jruby.mains;
import java.net.URL;
import java.security.ProtectionDomain;
import java.util.Properties;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.bio.SocketConnector;
import org.eclipse.jetty.webapp.WebAppContext;
public class JettyRunMain {
public static void main(String... args) throws Exception {
if (args.length == 0) {
main(System.getProperties());
}
else {
WarMain.main(args);
}
}
public static void main(Properties props) {
Server server = new Server();
SocketConnector connector = new SocketConnector();
// Set some timeout options to make debugging easier.
connector.setMaxIdleTime(1000 * 60 * 60);
connector.setSoLingerTime(-1);
connector.setPort(Integer.parseInt(props.getProperty("port", "8989")));
connector.setHost(props.getProperty("host"));
server.setConnectors(new Connector[] { connector });
WebAppContext context = new WebAppContext();
context.setServer(server);
context.setContextPath("/");
context.setExtractWAR(false);
context.setCopyWebInf(true);
ProtectionDomain protectionDomain = JettyRunMain.class
.getProtectionDomain();
URL location = protectionDomain.getCodeSource().getLocation();
context.setWar(location.toExternalForm());
server.setHandler(context);
Runtime.getRuntime().addShutdownHook(new JettyStop(server));
try {
server.start();
}
catch (Exception e) {
e.printStackTrace();
System.exit(100);
}
}
}
| mkristian/jruby-mains | src/main/java/org/jruby/mains/JettyRunMain.java | Java | lgpl-3.0 | 1,726 |
/*
* SonarQube, open source software quality management tool.
* Copyright (C) 2008-2014 SonarSource
* mailto:contact AT sonarsource DOT com
*
* SonarQube 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 3 of the License, or (at your option) any later version.
*
* SonarQube is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.search.ws;
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.utils.text.JsonWriter;
import org.sonar.server.search.QueryContext;
import org.sonar.server.search.Result;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
/**
* Generic options for search web services
*
* TODO {@link org.sonar.server.search.ws.SearchRequestHandler} should be used instead
*/
public class SearchOptions {
public static final String PARAM_TEXT_QUERY = "q";
public static final String PARAM_PAGE = "p";
public static final String PARAM_PAGE_SIZE = "ps";
public static final String PARAM_FIELDS = "f";
public static final String PARAM_SORT = "s";
public static final String PARAM_ASCENDING = "asc";
private int pageSize;
private int page;
private List<String> fields;
public int pageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
/**
* 1-based page id
*/
public int page() {
return page;
}
public void setPage(int page) {
this.page = page;
}
/**
* The fields to be returned in JSON response. <code>null</code> means that
* all the fields must be returned.
*/
@CheckForNull
public List<String> fields() {
return fields;
}
public SearchOptions setFields(@Nullable List<String> fields) {
this.fields = fields;
return this;
}
public boolean hasField(String key) {
return fields == null || fields.contains(key);
}
public SearchOptions writeStatistics(JsonWriter json, Result searchResult) {
json.prop("total", searchResult.getTotal());
json.prop(PARAM_PAGE, page);
json.prop(PARAM_PAGE_SIZE, pageSize);
return this;
}
public static SearchOptions create(Request request) {
SearchOptions options = new SearchOptions();
// both parameters have default values
options.setPage(request.mandatoryParamAsInt(PARAM_PAGE));
options.setPageSize(request.mandatoryParamAsInt(PARAM_PAGE_SIZE));
// optional field
options.setFields(request.paramAsStrings(PARAM_FIELDS));
return options;
}
public static void defineFieldsParam(WebService.NewAction action, @Nullable Collection<String> possibleFields) {
WebService.NewParam newParam = action
.createParam(PARAM_FIELDS)
.setDescription("Comma-separated list of the fields to be returned in response. All the fields are returned by default.")
.setPossibleValues(possibleFields);
if (possibleFields != null && possibleFields.size() > 1) {
Iterator<String> it = possibleFields.iterator();
newParam.setExampleValue(String.format("%s,%s", it.next(), it.next()));
}
}
public static void definePageParams(WebService.NewAction action) {
action
.createParam(PARAM_PAGE)
.setDescription("1-based page number")
.setExampleValue("42")
.setDefaultValue("1");
action
.createParam(PARAM_PAGE_SIZE)
.setDescription("Page size. Must be greater than 0.")
.setExampleValue("20")
.setDefaultValue(String.valueOf(QueryContext.DEFAULT_LIMIT));
}
}
| teryk/sonarqube | server/sonar-server/src/main/java/org/sonar/server/search/ws/SearchOptions.java | Java | lgpl-3.0 | 4,124 |
// Copyright (C) 2016 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.extensions.common;
import com.google.gerrit.extensions.client.ChangeStatus;
public class ChangeInput {
public String project;
public String branch;
public String subject;
public String topic;
public ChangeStatus status;
public String baseChange;
public Boolean newBranch;
}
| joshuawilson/merrit | gerrit-extension-api/src/main/java/com/google/gerrit/extensions/common/ChangeInput.java | Java | apache-2.0 | 926 |
/**
* Copyright (C) 2015 Red Hat, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.fabric8.elasticsearch.plugin;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.io.IOUtils;
public enum Samples {
ROLES_ACL("searchguard_roles_acl.yml"),
ROLESMAPPING_ACL("searchguard_rolesmapping_acl.yml"),
OPENSHIFT_ROLES_ACL("searchguard_roles_acl_with_openshift_projects.yml"),
OPENSHIFT_ROLESMAPPING_ACL("searchguard_rolesmapping_acl_with_openshift_projects.yml"),
PASSWORDS("passwords.yml"),
PROJECT_STRATEGY_ROLES_SHARED_OPS_KIBANA_MODE("project_strategy_roles_shared_ops_kibana_mode.yml"),
PROJECT_STRATEGY_ROLES_SHARED_NON_OPS_KIBANA_MODE("project_strategy_roles_shared_non_ops_kibana_mode.yml"),
PROJECT_STRATEGY_ROLES_UNIQUE_KIBANA_MODE("project_strategy_roles_unique_kibana_mode.yml"),
PROJECT_STRATEGY_ROLESMAPPING_UNIQUE_KIBANA_MODE("project_strategy_rolesmapping_unique_kibana_mode.yml"),
PROJECT_STRATEGY_ROLESMAPPING_SHARED_OPS_KIBANA_MODE("project_strategy_rolesmapping_shared_ops_kibana_mode.yml"),
PROJECT_STRATEGY_ROLESMAPPING_SHARED_NON_OPS_KIBANA_MODE("project_strategy_rolesmapping_shared_non_ops_kibana_mode.yml"),
USER_STRATEGY_ROLESMAPPING_SHARED_OPS_KIBANA_MODE("user_strategy_rolesmapping_shared_ops_kibana_mode.yml"),
USER_STRATEGY_ROLESMAPPING_SHARED_NON_OPS_KIBANA_MODE("user_strategy_rolesmapping_shared_non_ops_kibana_mode.yml"),
USER_STRATEGY_ROLESMAPPING_UNIQUE_KIBANA_MODE("user_strategy_rolesmapping_unique_kibana_mode.yml"),
USER_STRATEGY_ROLES_SHARED_OPS_KIBANA_MODE("user_strategy_roles_shared_ops_kibana_mode.yml"),
USER_STRATEGY_ROLES_SHARED_NON_OPS_KIBANA_MODE("user_strategy_roles_shared_non_ops_kibana_mode.yml"),
USER_STRATEGY_ROLES_UNIQUE_KIBANA_MODE("user_strategy_roles_unique_kibana_mode.yml");
private String path;
Samples(String path) {
this.path = path;
}
public String getContent() {
InputStream is = Samples.class.getResourceAsStream(path);
try {
return IOUtils.toString(is, "UTF-8");
} catch (IOException e) {
throw new RuntimeException(String.format("Unable to read file {}", path), e);
}
}
}
| fabric8io/openshift-elasticsearch-plugin | src/test/java/io/fabric8/elasticsearch/plugin/Samples.java | Java | apache-2.0 | 2,770 |
package com.ibm.streamsx.health.demo.service;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import com.ibm.streamsx.topology.Topology;
import com.ibm.streamsx.topology.context.StreamsContextFactory;
import com.ibm.streamsx.topology.context.StreamsContext.Type;
import com.ibm.streamsx.topology.spl.SPL;
public class UIWrapperService {
private Topology topo;
public UIWrapperService() throws Exception {
topo = new Topology("UIService");
SPL.addToolkit(topo, new File(System.getProperty("user.dir")));
SPL.addToolkit(topo, new File(System.getenv("STREAMS_INSTALL") + "/toolkits/com.ibm.streamsx.messaging"));
SPL.addToolkit(topo, new File(System.getenv("STREAMS_INSTALL") + "/toolkits/com.ibm.streamsx.json"));
SPL.addToolkit(topo, new File(System.getenv("STREAMS_INSTALL") + "/toolkits/com.ibm.streams.rulescompiler"));
SPL.addToolkit(topo, new File("../../ingest/common/com.ibm.streamsx.health.ingest"));
SPL.addToolkit(topo, new File(System.getProperty("user.dir") + "/.toolkits/com.ibm.streamsx.health.analyze.vital"));
SPL.addToolkit(topo, new File(System.getProperty("user.dir") + "/.toolkits/com.ibm.streamsx.inet"));
SPL.addToolkit(topo, new File("../PatientsMonitoringDemo.rules/com.ibm.streamsx.health.sample.patientsmonitoring.rules"));
}
public void build() {
SPL.invokeOperator(topo, "UIService", "com.ibm.streamsx.health.demo.ui::UIService", null, null, new HashMap<String, Object>());
}
public void run(Type type, Map<String, Object> submissionParams) throws Exception {
build();
StreamsContextFactory.getStreamsContext(type).submit(topo).get();
}
}
| ibmkendrick/streamsx.health | samples/PatientsMonitoringDemo/impl/java/src/com/ibm/streamsx/health/demo/service/UIWrapperService.java | Java | apache-2.0 | 1,631 |
/**
* Author: Bob Chen
*/
package com.jcommerce.core.action;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;
import org.springframework.context.ApplicationContext;
import com.jcommerce.core.model.ModelObject;
public class MapReadAction extends MapAction {
public MapReadAction(ApplicationContext ctx, BeanConfig config) {
super(ctx, config);
}
public Map<String, Object> getBean(String modelName, String id) {
System.out.println("getBean("+modelName);
Map<String, Object> data = new HashMap<String, Object>();
if (id.equals("")) {
new Exception("id:"+id).printStackTrace();
}
ModelObject model = getModelObject(modelName, id);
try {
if (model != null) {
data = getProperties(model);
} else {
throw new RuntimeException("model == null when modelName="+modelName+" id="+id);
}
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
return data;
}
}
| jbosschina/jcommerce | spring/core/src/main/java/com/jcommerce/core/action/MapReadAction.java | Java | apache-2.0 | 1,286 |
/*
* Copyright 2002-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.servlet.handler;
import javax.servlet.Servlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerAdapter;
import org.springframework.web.servlet.ModelAndView;
/**
* Adapter to use the Servlet interface with the generic DispatcherServlet.
* Calls the Servlet's <code>service</code> method to handle a request.
*
* <p>Last-modified checking is not explicitly supported: This is typically
* handled by the Servlet implementation itself (usually deriving from
* the HttpServlet base class).
*
* <p>This adapter is not activated by default; it needs to be defined as a
* bean in the DispatcherServlet context. It will automatically apply to
* mapped handler beans that implement the Servlet interface then.
*
* <p>Note that Servlet instances defined as bean will not receive initialization
* and destruction callbacks, unless a special post-processor such as
* SimpleServletPostProcessor is defined in the DispatcherServlet context.
*
* <p><b>Alternatively, consider wrapping a Servlet with Spring's
* ServletWrappingController.</b> This is particularly appropriate for
* existing Servlet classes, allowing to specify Servlet initialization
* parameters etc.
*
* @author Juergen Hoeller
* @since 1.1.5
* @see javax.servlet.Servlet
* @see javax.servlet.http.HttpServlet
* @see SimpleServletPostProcessor
* @see org.springframework.web.servlet.mvc.ServletWrappingController
*/
public class SimpleServletHandlerAdapter implements HandlerAdapter {
public boolean supports(Object handler) {
return (handler instanceof Servlet);
}
public ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
((Servlet) handler).service(request, response);
return null;
}
public long getLastModified(HttpServletRequest request, Object handler) {
return -1;
}
}
| cbeams-archive/spring-framework-2.5.x | src/org/springframework/web/servlet/handler/SimpleServletHandlerAdapter.java | Java | apache-2.0 | 2,589 |
package de.bbcdaas.uima_components.xing_tagcloud_html_extractor;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
/**
*
* @author Robert Illers
*/
public class XingTagCloudHtmlExtractorTests {
/**
*
*/
@Before
public void setUp() {}
/**
*
*/
@After
public void tearDown() {}
/**
*
*/
@Test
@Ignore
public void SimpleTest() {}
}
| christianherta/BBC-DaaS | uima_components/uima_components/bbcdaas_xing-tagcloud-html-extractor/src/test/java/de/bbcdaas/uima_components/xing_tagcloud_html_extractor/XingTagCloudHtmlExtractorTests.java | Java | apache-2.0 | 438 |
// Copyright (C) 2017 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.server.mail;
import static java.util.stream.Collectors.joining;
import com.google.common.flogger.FluentLogger;
import com.google.gerrit.mail.MailMessage;
import com.google.gerrit.server.config.GerritServerConfig;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import java.util.Arrays;
import java.util.regex.Pattern;
import org.eclipse.jgit.lib.Config;
@Singleton
public class ListMailFilter implements MailFilter {
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
public enum ListFilterMode {
OFF,
WHITELIST,
BLACKLIST
}
private final ListFilterMode mode;
private final Pattern mailPattern;
@Inject
ListMailFilter(@GerritServerConfig Config cfg) {
this.mode = cfg.getEnum("receiveemail", "filter", "mode", ListFilterMode.OFF);
String[] addresses = cfg.getStringList("receiveemail", "filter", "patterns");
String concat = Arrays.asList(addresses).stream().collect(joining("|"));
this.mailPattern = Pattern.compile(concat);
}
@Override
public boolean shouldProcessMessage(MailMessage message) {
if (mode == ListFilterMode.OFF) {
return true;
}
boolean match = mailPattern.matcher(message.from().getEmail()).find();
if ((mode == ListFilterMode.WHITELIST && !match)
|| (mode == ListFilterMode.BLACKLIST && match)) {
logger.atInfo().log("Mail message from %s rejected by list filter", message.from());
return false;
}
return true;
}
}
| WANdisco/gerrit | java/com/google/gerrit/server/mail/ListMailFilter.java | Java | apache-2.0 | 2,124 |
/*
* Copyright 2014,2015 agwlvssainokuni
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cherry.foundation.validator.groups;
public interface G7 {
}
| agwlvssainokuni/springapp | foundation/src/main/java/cherry/foundation/validator/groups/G7.java | Java | apache-2.0 | 694 |
/**
* Copyright © 2014 - 2017 Leipzig University (Database Research Group)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradoop.flink.model.impl.functions.graphcontainment;
import org.apache.flink.api.common.functions.FilterFunction;
import org.gradoop.common.model.api.entities.EPGMGraphElement;
/**
* True, if the element has not graph ids.
*
* @param <EL> epgm graph element
*/
public class InNoGraph<EL extends EPGMGraphElement> implements FilterFunction<EL> {
@Override
public boolean filter(EL value) throws Exception {
return value.getGraphIds() == null || value.getGraphIds().isEmpty();
}
}
| p3et/gradoop | gradoop-flink/src/main/java/org/gradoop/flink/model/impl/functions/graphcontainment/InNoGraph.java | Java | apache-2.0 | 1,147 |
/*
* Copyright 2015 Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.bgp.controller.impl;
import java.util.Map;
import java.util.TreeMap;
import org.onosproject.bgpio.protocol.BgpLSNlri;
import org.onosproject.bgpio.protocol.linkstate.BgpLinkLSIdentifier;
import org.onosproject.bgpio.protocol.linkstate.BgpLinkLsNlriVer4;
import org.onosproject.bgpio.protocol.linkstate.BgpNodeLSIdentifier;
import org.onosproject.bgpio.protocol.linkstate.BgpNodeLSNlriVer4;
import org.onosproject.bgpio.protocol.linkstate.BgpPrefixIPv4LSNlriVer4;
import org.onosproject.bgpio.protocol.linkstate.BgpPrefixLSIdentifier;
import org.onosproject.bgpio.protocol.linkstate.PathAttrNlriDetails;
import com.google.common.base.MoreObjects;
/**
* Implementation of Adj-RIB-In for each peer.
*/
public class AdjRibIn {
private Map<BgpNodeLSIdentifier, PathAttrNlriDetails> nodeTree = new TreeMap<>();
private Map<BgpLinkLSIdentifier, PathAttrNlriDetails> linkTree = new TreeMap<>();
private Map<BgpPrefixLSIdentifier, PathAttrNlriDetails> prefixTree = new TreeMap<>();
/**
* Returns the adjacency node.
*
* @return node adjacency RIB node
*/
public Map<BgpNodeLSIdentifier, PathAttrNlriDetails> nodeTree() {
return nodeTree;
}
/**
* Returns the adjacency link.
*
* @return link adjacency RIB node
*/
public Map<BgpLinkLSIdentifier, PathAttrNlriDetails> linkTree() {
return linkTree;
}
/**
* Returns the adjacency prefix.
*
* @return prefix adjacency RIB node
*/
public Map<BgpPrefixLSIdentifier, PathAttrNlriDetails> prefixTree() {
return prefixTree;
}
/**
* Update nlri identifier into the tree if nlri identifier exists in tree otherwise add this to the tree.
*
* @param nlri NLRI Info
* @param details has pathattribute , protocolID and identifier
*/
public void add(BgpLSNlri nlri, PathAttrNlriDetails details) {
if (nlri instanceof BgpNodeLSNlriVer4) {
BgpNodeLSIdentifier nodeLSIdentifier = ((BgpNodeLSNlriVer4) nlri).getLocalNodeDescriptors();
if (nodeTree.containsKey(nodeLSIdentifier)) {
nodeTree.replace(nodeLSIdentifier, details);
} else {
nodeTree.put(nodeLSIdentifier, details);
}
} else if (nlri instanceof BgpLinkLsNlriVer4) {
BgpLinkLSIdentifier linkLSIdentifier = ((BgpLinkLsNlriVer4) nlri).getLinkIdentifier();
if (linkTree.containsKey(linkLSIdentifier)) {
linkTree.replace(linkLSIdentifier, details);
} else {
linkTree.put(linkLSIdentifier, details);
}
} else if (nlri instanceof BgpPrefixIPv4LSNlriVer4) {
BgpPrefixLSIdentifier prefixIdentifier = ((BgpPrefixIPv4LSNlriVer4) nlri).getPrefixIdentifier();
if (prefixTree.containsKey(prefixIdentifier)) {
prefixTree.replace(prefixIdentifier, details);
} else {
prefixTree.put(prefixIdentifier, details);
}
}
}
/**
* Removes nlri identifier if it exists in the adjacency tree.
*
* @param nlri NLRI Info
*/
public void remove(BgpLSNlri nlri) {
if (nlri instanceof BgpNodeLSNlriVer4) {
BgpNodeLSIdentifier nodeLSIdentifier = ((BgpNodeLSNlriVer4) nlri).getLocalNodeDescriptors();
if (nodeTree.containsKey(nodeLSIdentifier)) {
nodeTree.remove(nodeLSIdentifier);
}
} else if (nlri instanceof BgpLinkLsNlriVer4) {
BgpLinkLSIdentifier linkLSIdentifier = ((BgpLinkLsNlriVer4) nlri).getLinkIdentifier();
if (linkTree.containsKey(linkLSIdentifier)) {
linkTree.remove(linkLSIdentifier);
}
} else if (nlri instanceof BgpPrefixIPv4LSNlriVer4) {
BgpPrefixLSIdentifier prefixIdentifier = ((BgpPrefixIPv4LSNlriVer4) nlri).getPrefixIdentifier();
if (prefixTree.containsKey(prefixIdentifier)) {
prefixTree.remove(prefixIdentifier);
}
}
}
@Override
public String toString() {
return MoreObjects.toStringHelper(getClass())
.omitNullValues()
.add("nodeTree", nodeTree)
.add("linkTree", linkTree)
.add("prefixTree", prefixTree)
.toString();
}
} | sonu283304/onos | protocols/bgp/ctl/src/main/java/org/onosproject/bgp/controller/impl/AdjRibIn.java | Java | apache-2.0 | 4,999 |
/*
* Copyright 2017 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jbpm.kie.services.impl;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.drools.core.command.impl.ExecutableCommand;
import org.drools.core.command.impl.RegistryContext;
import org.drools.core.command.runtime.process.SetProcessInstanceVariablesCommand;
import org.drools.core.command.runtime.process.StartProcessCommand;
import org.drools.core.process.instance.WorkItemManager;
import org.jbpm.process.instance.impl.ProcessInstanceImpl;
import org.jbpm.process.instance.impl.util.VariableUtil;
import org.jbpm.services.api.DeploymentNotFoundException;
import org.jbpm.services.api.DeploymentService;
import org.jbpm.services.api.ProcessInstanceNotFoundException;
import org.jbpm.services.api.ProcessService;
import org.jbpm.services.api.RuntimeDataService;
import org.jbpm.services.api.WorkItemNotFoundException;
import org.jbpm.services.api.model.DeployedUnit;
import org.jbpm.services.api.model.NodeInstanceDesc;
import org.jbpm.services.api.model.ProcessInstanceDesc;
import org.jbpm.services.api.service.ServiceRegistry;
import org.jbpm.workflow.instance.impl.WorkflowProcessInstanceImpl;
import org.jbpm.workflow.instance.node.CompositeNodeInstance;
import org.jbpm.workflow.instance.node.EventNodeInstance;
import org.kie.api.command.Command;
import org.kie.api.runtime.EnvironmentName;
import org.kie.api.runtime.KieSession;
import org.kie.api.runtime.manager.Context;
import org.kie.api.runtime.manager.RuntimeEngine;
import org.kie.api.runtime.manager.RuntimeManager;
import org.kie.api.runtime.process.NodeInstance;
import org.kie.api.runtime.process.ProcessInstance;
import org.kie.api.runtime.process.WorkItem;
import org.kie.api.runtime.process.WorkflowProcessInstance;
import org.kie.internal.process.CorrelationAwareProcessRuntime;
import org.kie.internal.process.CorrelationKey;
import org.kie.internal.runtime.manager.InternalRuntimeManager;
import org.kie.internal.runtime.manager.SessionNotFoundException;
import org.kie.internal.runtime.manager.context.CaseContext;
import org.kie.internal.runtime.manager.context.CorrelationKeyContext;
import org.kie.internal.runtime.manager.context.ProcessInstanceIdContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ProcessServiceImpl implements ProcessService, VariablesAware {
private static final Logger logger = LoggerFactory.getLogger(ProcessServiceImpl.class);
protected DeploymentService deploymentService;
protected RuntimeDataService dataService;
public ProcessServiceImpl() {
ServiceRegistry.get().register(ProcessService.class.getSimpleName(), this);
}
public void setDeploymentService(DeploymentService deploymentService) {
this.deploymentService = deploymentService;
}
public void setDataService(RuntimeDataService dataService) {
this.dataService = dataService;
}
@Override
public Long startProcess(String deploymentId, String processId) {
return startProcess(deploymentId, processId, new HashMap<>());
}
@Override
public Long startProcess(String deploymentId, String processId, Map<String, Object> params) {
DeployedUnit deployedUnit = deploymentService.getDeployedUnit(deploymentId);
if (deployedUnit == null) {
throw new DeploymentNotFoundException("No deployments available for " + deploymentId);
}
if (!deployedUnit.isActive()) {
throw new DeploymentNotFoundException("Deployments " + deploymentId + " is not active");
}
RuntimeManager manager = deployedUnit.getRuntimeManager();
params = process(params, ((InternalRuntimeManager) manager).getEnvironment().getClassLoader());
RuntimeEngine engine = manager.getRuntimeEngine(getContext(params));
KieSession ksession = engine.getKieSession();
ProcessInstance pi;
try {
pi = ksession.startProcess(processId, params);
return pi.getId();
} finally {
disposeRuntimeEngine(manager, engine);
}
}
@Override
public Long startProcess(String deploymentId, String processId, CorrelationKey correlationKey) {
return startProcess(deploymentId, processId, correlationKey, new HashMap<>());
}
@Override
public Long startProcess(String deploymentId, String processId, CorrelationKey correlationKey, Map<String, Object> params) {
DeployedUnit deployedUnit = deploymentService.getDeployedUnit(deploymentId);
if (deployedUnit == null) {
throw new DeploymentNotFoundException("No deployments available for " + deploymentId);
}
if (!deployedUnit.isActive()) {
throw new DeploymentNotFoundException("Deployments " + deploymentId + " is not active");
}
RuntimeManager manager = deployedUnit.getRuntimeManager();
params = process(params, ((InternalRuntimeManager) manager).getEnvironment().getClassLoader());
RuntimeEngine engine = manager.getRuntimeEngine(getContext(params));
KieSession ksession = engine.getKieSession();
ProcessInstance pi;
try {
pi = ((CorrelationAwareProcessRuntime)ksession).startProcess(processId, correlationKey, params);
return pi.getId();
} finally {
disposeRuntimeEngine(manager, engine);
}
}
protected Context<?> getContext(Map<String, Object> params) {
if (params == null) {
return ProcessInstanceIdContext.get();
}
String caseId = (String) params.get(EnvironmentName.CASE_ID);
if (caseId != null && !caseId.isEmpty()) {
return CaseContext.get(caseId);
}
return ProcessInstanceIdContext.get();
}
@Override
public void abortProcessInstance(Long processInstanceId) {
ProcessInstanceDesc piDesc = dataService.getProcessInstanceById(processInstanceId);
if (piDesc == null || piDesc.getState() != 1) {
throw new ProcessInstanceNotFoundException("Process instance with id " + processInstanceId + " was not found");
}
DeployedUnit deployedUnit = deploymentService.getDeployedUnit(piDesc.getDeploymentId());
if (deployedUnit == null) {
throw new DeploymentNotFoundException("No deployments available for " + piDesc.getDeploymentId());
}
RuntimeManager manager = deployedUnit.getRuntimeManager();
RuntimeEngine engine = manager.getRuntimeEngine(ProcessInstanceIdContext.get(processInstanceId));
try {
KieSession ksession = engine.getKieSession();
ksession.abortProcessInstance(processInstanceId);
} catch(SessionNotFoundException e) {
throw new ProcessInstanceNotFoundException("Process instance with id " + processInstanceId + " was not found", e);
} finally {
disposeRuntimeEngine(manager, engine);
}
}
@Override
public void abortProcessInstances(List<Long> processInstanceIds) {
for (long processInstanceId : processInstanceIds) {
abortProcessInstance(processInstanceId);
}
}
@Override
public void signalProcessInstance(Long processInstanceId, String signalName, Object event) {
ProcessInstanceDesc piDesc = dataService.getProcessInstanceById(processInstanceId);
if (piDesc == null || piDesc.getState() != 1) {
throw new ProcessInstanceNotFoundException("Process instance with id " + processInstanceId + " was not found");
}
DeployedUnit deployedUnit = deploymentService.getDeployedUnit(piDesc.getDeploymentId());
if (deployedUnit == null) {
throw new DeploymentNotFoundException("No deployments available for " + piDesc.getDeploymentId());
}
RuntimeManager manager = deployedUnit.getRuntimeManager();
event = process(event, ((InternalRuntimeManager) manager).getEnvironment().getClassLoader());
RuntimeEngine engine = manager.getRuntimeEngine(ProcessInstanceIdContext.get(processInstanceId));
try {
KieSession ksession = engine.getKieSession();
ksession.signalEvent(signalName, event, processInstanceId);
} catch(SessionNotFoundException e) {
throw new ProcessInstanceNotFoundException("Process instance with id " + processInstanceId + " was not found", e);
} finally {
disposeRuntimeEngine(manager, engine);
}
}
@Override
public void signalProcessInstances(List<Long> processInstanceIds, String signalName, Object event) {
for (Long processInstanceId : processInstanceIds) {
signalProcessInstance(processInstanceId, signalName, event);
}
}
@Override
public void signalEvent(String deployment, String signalName, Object event) {
DeployedUnit deployedUnit = deploymentService.getDeployedUnit(deployment);
if (deployedUnit == null) {
throw new DeploymentNotFoundException("No deployments available for " + deployment);
}
RuntimeManager manager = deployedUnit.getRuntimeManager();
event = process(event, ((InternalRuntimeManager) manager).getEnvironment().getClassLoader());
manager.signalEvent(signalName, event);
}
@Override
public ProcessInstance getProcessInstance(Long processInstanceId) {
ProcessInstanceDesc piDesc = dataService.getProcessInstanceById(processInstanceId);
if (piDesc == null) {
return null;
}
DeployedUnit deployedUnit = deploymentService.getDeployedUnit(piDesc.getDeploymentId());
if (deployedUnit == null) {
throw new DeploymentNotFoundException("No deployments available for " + piDesc.getDeploymentId());
}
RuntimeManager manager = deployedUnit.getRuntimeManager();
RuntimeEngine engine = manager.getRuntimeEngine(ProcessInstanceIdContext.get(processInstanceId));
try {
KieSession ksession = engine.getKieSession();
return ksession.getProcessInstance(processInstanceId);
} catch(SessionNotFoundException e) {
throw new ProcessInstanceNotFoundException("Process instance with id " + processInstanceId + " was not found", e);
} finally {
disposeRuntimeEngine(manager, engine);
}
}
@Override
public ProcessInstance getProcessInstance(CorrelationKey key) {
ProcessInstanceDesc piDesc = dataService.getProcessInstanceByCorrelationKey(key);
if (piDesc == null) {
return null;
}
DeployedUnit deployedUnit = deploymentService.getDeployedUnit(piDesc.getDeploymentId());
if (deployedUnit == null) {
throw new DeploymentNotFoundException("No deployments available for " + piDesc.getDeploymentId());
}
RuntimeManager manager = deployedUnit.getRuntimeManager();
RuntimeEngine engine = manager.getRuntimeEngine(CorrelationKeyContext.get(key));
KieSession ksession = engine.getKieSession();
try {
return ((CorrelationAwareProcessRuntime)ksession).getProcessInstance(key);
} finally {
disposeRuntimeEngine(manager, engine);
}
}
@Override
public void setProcessVariable(Long processInstanceId, String variableId, Object value) {
ProcessInstanceDesc piDesc = dataService.getProcessInstanceById(processInstanceId);
if (piDesc == null || piDesc.getState() != 1) {
throw new ProcessInstanceNotFoundException("Process instance with id " + processInstanceId + " was not found");
}
DeployedUnit deployedUnit = deploymentService.getDeployedUnit(piDesc.getDeploymentId());
if (deployedUnit == null) {
throw new DeploymentNotFoundException("No deployments available for " + piDesc.getDeploymentId());
}
RuntimeManager manager = deployedUnit.getRuntimeManager();
value = process(value, ((InternalRuntimeManager) manager).getEnvironment().getClassLoader());
RuntimeEngine engine = manager.getRuntimeEngine(ProcessInstanceIdContext.get(processInstanceId));
try {
KieSession ksession = engine.getKieSession();
ksession.execute(new SetProcessInstanceVariablesCommand(processInstanceId, Collections.singletonMap(variableId, value)));
} catch(SessionNotFoundException e) {
throw new ProcessInstanceNotFoundException("Process instance with id " + processInstanceId + " was not found", e);
} finally {
disposeRuntimeEngine(manager, engine);
}
}
@Override
public void setProcessVariables(Long processInstanceId, Map<String, Object> variables) {
ProcessInstanceDesc piDesc = dataService.getProcessInstanceById(processInstanceId);
if (piDesc == null || piDesc.getState() != 1) {
throw new ProcessInstanceNotFoundException("Process instance with id " + processInstanceId + " was not found");
}
DeployedUnit deployedUnit = deploymentService.getDeployedUnit(piDesc.getDeploymentId());
if (deployedUnit == null) {
throw new DeploymentNotFoundException("No deployments available for " + piDesc.getDeploymentId());
}
RuntimeManager manager = deployedUnit.getRuntimeManager();
variables = process(variables, ((InternalRuntimeManager) manager).getEnvironment().getClassLoader());
RuntimeEngine engine = manager.getRuntimeEngine(ProcessInstanceIdContext.get(processInstanceId));
try {
KieSession ksession = engine.getKieSession();
ksession.execute(new SetProcessInstanceVariablesCommand(processInstanceId, variables));
} catch(SessionNotFoundException e) {
throw new ProcessInstanceNotFoundException("Process instance with id " + processInstanceId + " was not found", e);
} finally {
disposeRuntimeEngine(manager, engine);
}
}
@Override
public Object getProcessInstanceVariable(Long processInstanceId, String variableName) {
ProcessInstanceDesc piDesc = dataService.getProcessInstanceById(processInstanceId);
if (piDesc == null || piDesc.getState() != 1) {
throw new ProcessInstanceNotFoundException("Process instance with id " + processInstanceId + " was not found");
}
DeployedUnit deployedUnit = deploymentService.getDeployedUnit(piDesc.getDeploymentId());
if (deployedUnit == null) {
throw new DeploymentNotFoundException("No deployments available for " + piDesc.getDeploymentId());
}
RuntimeManager manager = deployedUnit.getRuntimeManager();
RuntimeEngine engine = manager.getRuntimeEngine(ProcessInstanceIdContext.get(processInstanceId));
try {
KieSession ksession = engine.getKieSession();
return ksession.execute(new ExecutableCommand<Object>() {
private static final long serialVersionUID = -2693525229757876896L;
@Override
public Object execute(org.kie.api.runtime.Context context) {
KieSession ksession = ((RegistryContext) context).lookup( KieSession.class );
WorkflowProcessInstance pi = (WorkflowProcessInstance) ksession.getProcessInstance(processInstanceId, true);
if (pi == null) {
throw new ProcessInstanceNotFoundException("Process instance with id " + processInstanceId + " was not found");
}
return pi.getVariable(variableName);
}
});
} catch(SessionNotFoundException e) {
throw new ProcessInstanceNotFoundException("Process instance with id " + processInstanceId + " was not found", e);
} finally {
disposeRuntimeEngine(manager, engine);
}
}
@Override
public Map<String, Object> getProcessInstanceVariables(Long processInstanceId) {
ProcessInstanceDesc piDesc = dataService.getProcessInstanceById(processInstanceId);
if (piDesc == null || piDesc.getState() != 1) {
throw new ProcessInstanceNotFoundException("Process instance with id " + processInstanceId + " was not found");
}
DeployedUnit deployedUnit = deploymentService.getDeployedUnit(piDesc.getDeploymentId());
if (deployedUnit == null) {
throw new DeploymentNotFoundException("No deployments available for " + piDesc.getDeploymentId());
}
RuntimeManager manager = deployedUnit.getRuntimeManager();
RuntimeEngine engine = manager.getRuntimeEngine(ProcessInstanceIdContext.get(processInstanceId));
try {
KieSession ksession = engine.getKieSession();
WorkflowProcessInstanceImpl pi = (WorkflowProcessInstanceImpl) ksession.getProcessInstance(processInstanceId, true);
return pi.getVariables();
} catch(SessionNotFoundException e) {
throw new ProcessInstanceNotFoundException("Process instance with id " + processInstanceId + " was not found", e);
} finally {
disposeRuntimeEngine(manager, engine);
}
}
@Override
public Collection<String> getAvailableSignals(Long processInstanceId) {
ProcessInstanceDesc piDesc = dataService.getProcessInstanceById(processInstanceId);
if (piDesc == null) {
throw new ProcessInstanceNotFoundException("Process instance with id " + processInstanceId + " was not found");
}
DeployedUnit deployedUnit = deploymentService.getDeployedUnit(piDesc.getDeploymentId());
if (deployedUnit == null) {
throw new DeploymentNotFoundException("No deployments available for " + piDesc.getDeploymentId());
}
RuntimeManager manager = deployedUnit.getRuntimeManager();
RuntimeEngine engine = manager.getRuntimeEngine(ProcessInstanceIdContext.get(processInstanceId));
try {
KieSession ksession = engine.getKieSession();
ProcessInstance processInstance = ksession.getProcessInstance(processInstanceId);
Collection<String> activeSignals = new ArrayList<>();
if (processInstance != null) {
((ProcessInstanceImpl) processInstance)
.setProcess(ksession.getKieBase().getProcess(processInstance.getProcessId()));
Collection<NodeInstance> activeNodes = ((WorkflowProcessInstance) processInstance).getNodeInstances();
activeSignals.addAll(collectActiveSignals(activeNodes));
}
return activeSignals;
} catch(SessionNotFoundException e) {
throw new ProcessInstanceNotFoundException("Process instance with id " + processInstanceId + " was not found", e);
} finally {
disposeRuntimeEngine(manager, engine);
}
}
@Override
public void completeWorkItem(Long id, Map<String, Object> results) {
NodeInstanceDesc nodeDesc = dataService.getNodeInstanceForWorkItem(id);
if (nodeDesc == null) {
throw new WorkItemNotFoundException("Work item with id " + id + " was not found");
}
DeployedUnit deployedUnit = deploymentService.getDeployedUnit(nodeDesc.getDeploymentId());
if (deployedUnit == null) {
throw new DeploymentNotFoundException("No deployments available for " + nodeDesc.getDeploymentId());
}
Long processInstanceId = nodeDesc.getProcessInstanceId();
RuntimeManager manager = deployedUnit.getRuntimeManager();
results = process(results, ((InternalRuntimeManager) manager).getEnvironment().getClassLoader());
RuntimeEngine engine = manager.getRuntimeEngine(ProcessInstanceIdContext.get(processInstanceId));
try {
KieSession ksession = engine.getKieSession();
ksession.getWorkItemManager().completeWorkItem(id, results);
} catch(SessionNotFoundException e) {
throw new ProcessInstanceNotFoundException("Process instance with id " + processInstanceId + " was not found", e);
} finally {
disposeRuntimeEngine(manager, engine);
}
}
@Override
public void abortWorkItem(Long id) {
NodeInstanceDesc nodeDesc = dataService.getNodeInstanceForWorkItem(id);
if (nodeDesc == null) {
throw new WorkItemNotFoundException("Work item with id " + id + " was not found");
}
DeployedUnit deployedUnit = deploymentService.getDeployedUnit(nodeDesc.getDeploymentId());
if (deployedUnit == null) {
throw new DeploymentNotFoundException("No deployments available for " + nodeDesc.getDeploymentId());
}
Long processInstanceId = nodeDesc.getProcessInstanceId();
RuntimeManager manager = deployedUnit.getRuntimeManager();
RuntimeEngine engine = manager.getRuntimeEngine(ProcessInstanceIdContext.get(processInstanceId));
try {
KieSession ksession = engine.getKieSession();
ksession.getWorkItemManager().abortWorkItem(id);
} catch(SessionNotFoundException e) {
throw new ProcessInstanceNotFoundException("Process instance with id " + processInstanceId + " was not found", e);
} finally {
disposeRuntimeEngine(manager, engine);
}
}
@Override
public WorkItem getWorkItem(Long id) {
NodeInstanceDesc nodeDesc = dataService.getNodeInstanceForWorkItem(id);
if (nodeDesc == null) {
throw new WorkItemNotFoundException("Work item with id " + id + " was not found");
}
DeployedUnit deployedUnit = deploymentService.getDeployedUnit(nodeDesc.getDeploymentId());
if (deployedUnit == null) {
throw new DeploymentNotFoundException("No deployments available for " + nodeDesc.getDeploymentId());
}
Long processInstanceId = nodeDesc.getProcessInstanceId();
RuntimeManager manager = deployedUnit.getRuntimeManager();
RuntimeEngine engine = manager.getRuntimeEngine(ProcessInstanceIdContext.get(processInstanceId));
try {
KieSession ksession = engine.getKieSession();
return ((WorkItemManager)ksession.getWorkItemManager()).getWorkItem(id);
} catch(SessionNotFoundException e) {
throw new ProcessInstanceNotFoundException("Process instance with id " + processInstanceId + " was not found", e);
} finally {
disposeRuntimeEngine(manager, engine);
}
}
@Override
public List<WorkItem> getWorkItemByProcessInstance(Long processInstanceId) {
ProcessInstanceDesc piDesc = dataService.getProcessInstanceById(processInstanceId);
if (piDesc == null || piDesc.getState() != 1) {
throw new ProcessInstanceNotFoundException("Process instance with id " + processInstanceId + " was not found");
}
DeployedUnit deployedUnit = deploymentService.getDeployedUnit(piDesc.getDeploymentId());
if (deployedUnit == null) {
throw new DeploymentNotFoundException("No deployments available for " + piDesc.getDeploymentId());
}
RuntimeManager manager = deployedUnit.getRuntimeManager();
RuntimeEngine engine = manager.getRuntimeEngine(ProcessInstanceIdContext.get(processInstanceId));
try {
KieSession ksession = engine.getKieSession();
List<WorkItem> workItems = new ArrayList<>();
Collection<NodeInstanceDesc> nodes = dataService.getProcessInstanceHistoryActive(processInstanceId, null);
for (NodeInstanceDesc node : nodes) {
if (node.getWorkItemId() != null) {
workItems.add(((WorkItemManager)ksession.getWorkItemManager()).getWorkItem(node.getWorkItemId()));
}
}
return workItems;
} catch(SessionNotFoundException e) {
throw new ProcessInstanceNotFoundException("Process instance with id " + processInstanceId + " was not found", e);
} finally {
disposeRuntimeEngine(manager, engine);
}
}
@Override
public <T> T execute(String deploymentId, Command<T> command) {
Long processInstanceId = CommonUtils.getProcessInstanceId(command);
logger.debug("Executing command {} with process instance id {} as contextual data", command, processInstanceId);
DeployedUnit deployedUnit = deploymentService.getDeployedUnit(deploymentId);
if (deployedUnit == null) {
throw new DeploymentNotFoundException("No deployments available for " + deploymentId);
}
disallowWhenNotActive(deployedUnit, command);
RuntimeManager manager = deployedUnit.getRuntimeManager();
RuntimeEngine engine = manager.getRuntimeEngine(ProcessInstanceIdContext.get(processInstanceId));
try {
KieSession ksession = engine.getKieSession();
return ksession.execute(command);
} catch(SessionNotFoundException e) {
throw new ProcessInstanceNotFoundException("Process instance with id " + processInstanceId + " was not found", e);
} finally {
disposeRuntimeEngine(manager, engine);
}
}
@Override
public <T> T execute(String deploymentId, Context<?> context, Command<T> command) {
DeployedUnit deployedUnit = deploymentService.getDeployedUnit(deploymentId);
if (deployedUnit == null) {
throw new DeploymentNotFoundException("No deployments available for " + deploymentId);
}
disallowWhenNotActive(deployedUnit, command);
RuntimeManager manager = deployedUnit.getRuntimeManager();
RuntimeEngine engine = manager.getRuntimeEngine(context);
try {
KieSession ksession = engine.getKieSession();
return ksession.execute(command);
} catch(SessionNotFoundException e) {
throw new ProcessInstanceNotFoundException("Process instance with context id " + context.getContextId() + " was not found", e);
} finally {
disposeRuntimeEngine(manager, engine);
}
}
protected void disallowWhenNotActive(DeployedUnit deployedUnit, Command<?> cmd) {
if (!deployedUnit.isActive() &&
cmd instanceof StartProcessCommand) {
throw new DeploymentNotFoundException("Deployments " + deployedUnit.getDeploymentUnit().getIdentifier() + " is not active");
}
}
protected Collection<String> collectActiveSignals(
Collection<NodeInstance> activeNodes) {
Collection<String> activeNodesComposite = new ArrayList<>();
for (NodeInstance nodeInstance : activeNodes) {
if (nodeInstance instanceof EventNodeInstance) {
String type = ((EventNodeInstance) nodeInstance).getEventNode().getType();
if (type != null && !type.startsWith("Message-")) {
activeNodesComposite.add(VariableUtil.resolveVariable(type, nodeInstance));
}
}
if (nodeInstance instanceof CompositeNodeInstance) {
Collection<NodeInstance> currentNodeInstances = ((CompositeNodeInstance) nodeInstance).getNodeInstances();
// recursively check current nodes
activeNodesComposite
.addAll(collectActiveSignals(currentNodeInstances));
}
}
return activeNodesComposite;
}
@Override
public <T> T process(T variables, ClassLoader cl) {
// do nothing here as there is no need to process variables
return variables;
}
protected void disposeRuntimeEngine(RuntimeManager manager, RuntimeEngine engine) {
manager.disposeRuntimeEngine(engine);
}
}
| DuncanDoyle/jbpm | jbpm-services/jbpm-kie-services/src/main/java/org/jbpm/kie/services/impl/ProcessServiceImpl.java | Java | apache-2.0 | 26,916 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.flink.table.catalog;
import org.apache.flink.table.api.TableConfig;
import org.apache.flink.table.api.TableException;
import org.apache.flink.table.api.TableSchema;
import org.apache.flink.table.calcite.FlinkTypeFactory;
import org.apache.flink.table.catalog.CatalogManager.TableLookupResult;
import org.apache.flink.table.factories.TableFactory;
import org.apache.flink.table.factories.TableFactoryUtil;
import org.apache.flink.table.factories.TableSourceFactory;
import org.apache.flink.table.factories.TableSourceFactoryContextImpl;
import org.apache.flink.table.plan.schema.TableSinkTable;
import org.apache.flink.table.plan.schema.TableSourceTable;
import org.apache.flink.table.plan.stats.FlinkStatistic;
import org.apache.flink.table.sources.StreamTableSource;
import org.apache.flink.table.sources.TableSource;
import org.apache.calcite.linq4j.tree.Expression;
import org.apache.calcite.rel.type.RelProtoDataType;
import org.apache.calcite.schema.Function;
import org.apache.calcite.schema.Schema;
import org.apache.calcite.schema.SchemaPlus;
import org.apache.calcite.schema.SchemaVersion;
import org.apache.calcite.schema.Schemas;
import org.apache.calcite.schema.Table;
import org.apache.calcite.schema.impl.ViewTable;
import javax.annotation.Nullable;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
/**
* A mapping between Flink catalog's database and Calcite's schema. Tables are registered as tables
* in the schema.
*/
class DatabaseCalciteSchema implements Schema {
private final boolean isStreamingMode;
private final String catalogName;
private final String databaseName;
private final CatalogManager catalogManager;
private final TableConfig tableConfig;
public DatabaseCalciteSchema(
boolean isStreamingMode,
String databaseName,
String catalogName,
CatalogManager catalogManager,
TableConfig tableConfig) {
this.isStreamingMode = isStreamingMode;
this.databaseName = databaseName;
this.catalogName = catalogName;
this.catalogManager = catalogManager;
this.tableConfig = tableConfig;
}
@Override
public Table getTable(String tableName) {
ObjectIdentifier identifier = ObjectIdentifier.of(catalogName, databaseName, tableName);
return catalogManager
.getTable(identifier)
.map(
result -> {
final TableFactory tableFactory;
if (result.isTemporary()) {
tableFactory = null;
} else {
tableFactory =
catalogManager
.getCatalog(catalogName)
.flatMap(Catalog::getTableFactory)
.orElse(null);
}
return convertTable(identifier, result, tableFactory);
})
.orElse(null);
}
private Table convertTable(
ObjectIdentifier identifier,
TableLookupResult lookupResult,
@Nullable TableFactory tableFactory) {
CatalogBaseTable table = lookupResult.getTable();
TableSchema resolvedSchema =
TableSchema.fromResolvedSchema(lookupResult.getResolvedSchema());
if (table instanceof QueryOperationCatalogView) {
return QueryOperationCatalogViewTable.createCalciteTable(
((QueryOperationCatalogView) table), resolvedSchema);
} else if (table instanceof ConnectorCatalogTable) {
return convertConnectorTable((ConnectorCatalogTable<?, ?>) table, resolvedSchema);
} else {
if (table instanceof CatalogTable) {
return convertCatalogTable(
identifier,
(CatalogTable) table,
resolvedSchema,
tableFactory,
lookupResult.isTemporary());
} else if (table instanceof CatalogView) {
return convertCatalogView(
identifier.getObjectName(), (CatalogView) table, resolvedSchema);
} else {
throw new TableException("Unsupported table type: " + table);
}
}
}
private Table convertConnectorTable(
ConnectorCatalogTable<?, ?> table, TableSchema resolvedSchema) {
Optional<TableSourceTable<?>> tableSourceTable =
table.getTableSource()
.map(
tableSource ->
new TableSourceTable<>(
resolvedSchema,
tableSource,
!table.isBatch(),
FlinkStatistic.UNKNOWN()));
if (tableSourceTable.isPresent()) {
return tableSourceTable.get();
} else {
Optional<TableSinkTable<?>> tableSinkTable =
table.getTableSink()
.map(
tableSink ->
new TableSinkTable<>(
tableSink, FlinkStatistic.UNKNOWN()));
if (tableSinkTable.isPresent()) {
return tableSinkTable.get();
} else {
throw new TableException(
"Cannot convert a connector table " + "without either source or sink.");
}
}
}
private Table convertCatalogTable(
ObjectIdentifier identifier,
CatalogTable table,
TableSchema resolvedSchema,
@Nullable TableFactory tableFactory,
boolean isTemporary) {
final TableSource<?> tableSource;
final TableSourceFactory.Context context =
new TableSourceFactoryContextImpl(
identifier, table, tableConfig.getConfiguration(), isTemporary);
if (tableFactory != null) {
if (tableFactory instanceof TableSourceFactory) {
tableSource = ((TableSourceFactory<?>) tableFactory).createTableSource(context);
} else {
throw new TableException(
"Cannot query a sink-only table. TableFactory provided by catalog must implement TableSourceFactory");
}
} else {
tableSource = TableFactoryUtil.findAndCreateTableSource(context);
}
if (!(tableSource instanceof StreamTableSource)) {
throw new TableException(
"Catalog tables support only StreamTableSource and InputFormatTableSource");
}
return new TableSourceTable<>(
resolvedSchema,
tableSource,
// this means the TableSource extends from StreamTableSource, this is needed for the
// legacy Planner. Blink Planner should use the information that comes from the
// TableSource
// itself to determine if it is a streaming or batch source.
isStreamingMode,
FlinkStatistic.UNKNOWN());
}
private Table convertCatalogView(
String tableName, CatalogView table, TableSchema resolvedSchema) {
return new ViewTable(
null,
typeFactory -> ((FlinkTypeFactory) typeFactory).buildLogicalRowType(resolvedSchema),
table.getExpandedQuery(),
Arrays.asList(catalogName, databaseName),
Arrays.asList(catalogName, databaseName, tableName));
}
@Override
public Set<String> getTableNames() {
return catalogManager.listTables(catalogName, databaseName);
}
@Override
public RelProtoDataType getType(String name) {
return null;
}
@Override
public Set<String> getTypeNames() {
return new HashSet<>();
}
@Override
public Collection<Function> getFunctions(String s) {
return new HashSet<>();
}
@Override
public Set<String> getFunctionNames() {
return new HashSet<>();
}
@Override
public Schema getSubSchema(String s) {
return null;
}
@Override
public Set<String> getSubSchemaNames() {
return new HashSet<>();
}
@Override
public Expression getExpression(SchemaPlus parentSchema, String name) {
return Schemas.subSchemaExpression(parentSchema, name, getClass());
}
@Override
public boolean isMutable() {
return true;
}
@Override
public Schema snapshot(SchemaVersion schemaVersion) {
return this;
}
}
| clarkyzl/flink | flink-table/flink-table-planner/src/main/java/org/apache/flink/table/catalog/DatabaseCalciteSchema.java | Java | apache-2.0 | 9,901 |
/*
* Copyright 2014-2015 MarkLogic Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.marklogic.client.functionaltest;
import static org.custommonkey.xmlunit.XMLAssert.assertXpathEvaluatesTo;
import java.io.IOException;
import javax.xml.namespace.QName;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
import com.marklogic.client.DatabaseClient;
import com.marklogic.client.DatabaseClientFactory;
import com.marklogic.client.DatabaseClientFactory.Authentication;
import com.marklogic.client.admin.QueryOptionsManager;
import com.marklogic.client.admin.ServerConfigurationManager;
import com.marklogic.client.admin.config.QueryOptionsBuilder;
import com.marklogic.client.io.DOMHandle;
import com.marklogic.client.io.Format;
import com.marklogic.client.io.QueryOptionsHandle;
import com.marklogic.client.io.StringHandle;
import com.marklogic.client.query.QueryManager;
import com.marklogic.client.query.StructuredQueryBuilder;
import com.marklogic.client.query.StructuredQueryBuilder.Operator;
import com.marklogic.client.query.StructuredQueryDefinition;
import org.custommonkey.xmlunit.exceptions.XpathException;
import org.junit.*;
public class TestBug18801 extends BasicJavaClientREST {
private static String dbName = "Bug18801DB";
private static String [] fNames = {"Bug18801DB-1"};
private static String restServerName = "REST-Java-Client-API-Server";
@BeforeClass
public static void setUp() throws Exception
{
System.out.println("In setup");
setupJavaRESTServer(dbName, fNames[0], restServerName,8011);
setupAppServicesConstraint(dbName);
}
@SuppressWarnings("deprecation")
@Test
public void testDefaultFacetValue() throws IOException, ParserConfigurationException, SAXException, XpathException, TransformerException
{
System.out.println("Running testDefaultFacetValue");
String[] filenames = {"constraint1.xml", "constraint2.xml", "constraint3.xml", "constraint4.xml", "constraint5.xml"};
DatabaseClient client = DatabaseClientFactory.newClient("localhost", 8011, "rest-admin", "x", Authentication.DIGEST);
// set query option validation to true
ServerConfigurationManager srvMgr = client.newServerConfigManager();
srvMgr.readConfiguration();
srvMgr.setQueryOptionValidation(true);
srvMgr.writeConfiguration();
// write docs
for(String filename : filenames)
{
writeDocumentUsingInputStreamHandle(client, filename, "/def-facet/", "XML");
}
// create query options manager
QueryOptionsManager optionsMgr = client.newServerConfigManager().newQueryOptionsManager();
// create query options builder
QueryOptionsBuilder builder = new QueryOptionsBuilder();
// create query options handle
QueryOptionsHandle handle = new QueryOptionsHandle();
// build query options
handle.withConstraints(builder.constraint("pop",
builder.range(builder.elementRangeIndex(new QName("popularity"),
builder.rangeType("xs:int")))));
// write query options
optionsMgr.writeOptions("FacetValueOpt", handle);
// read query option
StringHandle readHandle = new StringHandle();
readHandle.setFormat(Format.XML);
optionsMgr.readOptions("FacetValueOpt", readHandle);
String output = readHandle.get();
System.out.println(output);
// create query manager
QueryManager queryMgr = client.newQueryManager();
// create query def
StructuredQueryBuilder qb = queryMgr.newStructuredQueryBuilder("FacetValueOpt");
StructuredQueryDefinition queryFinal = qb.rangeConstraint("pop", Operator.EQ, "5");
// create handle
DOMHandle resultsHandle = new DOMHandle();
queryMgr.search(queryFinal, resultsHandle);
// get the result
Document resultDoc = resultsHandle.get();
//System.out.println(convertXMLDocumentToString(resultDoc));
assertXpathEvaluatesTo("pop", "string(//*[local-name()='response']//*[local-name()='facet']//@*[local-name()='name'])", resultDoc);
assertXpathEvaluatesTo("3", "string(//*[local-name()='response']//*[local-name()='facet']/*[local-name()='facet-value']//@*[local-name()='count'])", resultDoc);
// release client
client.release();
}
@AfterClass
public static void tearDown() throws Exception
{
System.out.println("In tear down");
tearDownJavaRESTServer(dbName, fNames,restServerName);
}
}
| supriyantomaftuh/java-client-api | test-complete/src/test/java/com/marklogic/client/functionaltest/TestBug18801.java | Java | apache-2.0 | 5,062 |
/**
* Copyright 2010 Newcastle University
*
* http://research.ncl.ac.uk/smart/
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.amber.oauth2.common.domain.client;
/**
* @author Maciej Machulak ([email protected])
* @author Lukasz Moren ([email protected])
* @author Aad van Moorsel ([email protected])
*/
public class BasicClientInfo implements ClientInfo {
protected String name;
protected String clientId;
protected String clientSecret;
protected String redirectUri;
protected String clientUri;
protected String description;
protected String iconUri;
protected Long issuedAt;
protected Long expiresIn;
public BasicClientInfo() {
}
@Override
public String getClientId() {
return clientId;
}
@Override
public String getClientSecret() {
return clientSecret;
}
@Override
public String getRedirectUri() {
return redirectUri;
}
@Override
public String getName() {
return name;
}
@Override
public String getIconUri() {
return iconUri;
}
@Override
public String getClientUri() {
return clientUri;
}
@Override
public String getDescription() {
return description;
}
public void setClientUri(String clientUri) {
this.clientUri = clientUri;
}
public Long getIssuedAt() {
return issuedAt;
}
public void setIssuedAt(Long issuedAt) {
this.issuedAt = issuedAt;
}
public Long getExpiresIn() {
return expiresIn;
}
public void setExpiresIn(Long expiresIn) {
this.expiresIn = expiresIn;
}
public void setName(String name) {
this.name = name;
}
public void setClientId(String clientId) {
this.clientId = clientId;
}
public void setClientSecret(String clientSecret) {
this.clientSecret = clientSecret;
}
public void setRedirectUri(String redirectUri) {
this.redirectUri = redirectUri;
}
public void setIconUri(String iconUri) {
this.iconUri = iconUri;
}
public void setDescription(String description) {
this.description = description;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
BasicClientInfo that = (BasicClientInfo)o;
if (clientId != null ? !clientId.equals(that.clientId) : that.clientId != null) {
return false;
}
if (clientSecret != null ? !clientSecret.equals(that.clientSecret) : that.clientSecret != null) {
return false;
}
if (clientUri != null ? !clientUri.equals(that.clientUri) : that.clientUri != null) {
return false;
}
if (description != null ? !description.equals(that.description) : that.description != null) {
return false;
}
if (expiresIn != null ? !expiresIn.equals(that.expiresIn) : that.expiresIn != null) {
return false;
}
if (iconUri != null ? !iconUri.equals(that.iconUri) : that.iconUri != null) {
return false;
}
if (issuedAt != null ? !issuedAt.equals(that.issuedAt) : that.issuedAt != null) {
return false;
}
if (name != null ? !name.equals(that.name) : that.name != null) {
return false;
}
if (redirectUri != null ? !redirectUri.equals(that.redirectUri) : that.redirectUri != null) {
return false;
}
return true;
}
@Override
public int hashCode() {
int result = name != null ? name.hashCode() : 0;
result = 31 * result + (clientId != null ? clientId.hashCode() : 0);
result = 31 * result + (clientSecret != null ? clientSecret.hashCode() : 0);
result = 31 * result + (redirectUri != null ? redirectUri.hashCode() : 0);
result = 31 * result + (clientUri != null ? clientUri.hashCode() : 0);
result = 31 * result + (description != null ? description.hashCode() : 0);
result = 31 * result + (iconUri != null ? iconUri.hashCode() : 0);
result = 31 * result + (issuedAt != null ? issuedAt.hashCode() : 0);
result = 31 * result + (expiresIn != null ? expiresIn.hashCode() : 0);
return result;
}
}
| sebadiaz/oltu | oauth-2.0/oauth2-common/src/main/java/org/apache/amber/oauth2/common/domain/client/BasicClientInfo.java | Java | apache-2.0 | 5,403 |
package com.oozinoz.robotInterpreter2;
/*
* Copyright (c) 2001, 2005. Steven J. Metsker.
*
* Steve Metsker makes no representations or warranties about
* the fitness of this software for any particular purpose,
* including the implied warranty of merchantability.
*
* Please use this software as you wish with the sole
* restriction that you may not claim that you wrote it.
*/
/**
* This class represents a "while" statement that will execute
* its body so long as its term evaluates to a non-null value.
*/
public class WhileCommand extends Command {
protected Term term;
protected Command body;
/**
* Construct a "while" command that will execute its body
* as long as the supplied term evaulates to a non-null value.
* @param term the term to evaluate on each loop of the while
* @param body the body to execute
*/
public WhileCommand(Term term, Command body) {
this.term = term;
this.body = body;
}
/**
* Evaluate this object's term; if it's not null,
* execute the body. Repeat.
*/
public void execute() {
while (term.eval() != null)
body.execute();
}
} | sunshineboy/javacollection | DesignPattern/src/com/oozinoz/robotInterpreter2/WhileCommand.java | Java | apache-2.0 | 1,225 |
package org.projectbuendia.client.models;
import org.json.JSONException;
import org.json.JSONObject;
public class VoidObs {
public String Uuid;
public VoidObs(String uuid) {
this.Uuid = uuid;
}
public JSONObject toJson() throws JSONException {
JSONObject json = new JSONObject();
json.put("uuid", Uuid);
return json;
}
}
| llvasconcellos/client | app/src/main/java/org/projectbuendia/client/models/VoidObs.java | Java | apache-2.0 | 379 |
// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.geocities.com/kpdus/jad.html
// Decompiler options: braces fieldsfirst space lnc
package cn.com.smartdevices.bracelet.ui;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextPaint;
import android.widget.Button;
import android.widget.TextView;
// Referenced classes of package cn.com.smartdevices.bracelet.ui:
// SystemBarTintActivity, FwUpgradeFailedActivity, aj, ak
public class FwLowBatteryActivity extends SystemBarTintActivity
{
private TextView a;
private Button b;
public FwLowBatteryActivity()
{
a = null;
b = null;
}
private void a()
{
startActivity(new Intent(this, cn/com/smartdevices/bracelet/ui/FwUpgradeFailedActivity));
}
static void a(FwLowBatteryActivity fwlowbatteryactivity)
{
fwlowbatteryactivity.a();
}
protected void onCreate(Bundle bundle)
{
super.onCreate(bundle);
setContentView(0x7f030003);
a = (TextView)findViewById(0x7f0a0031);
a.getPaint().setFlags(8);
a.setOnClickListener(new aj(this));
b = (Button)findViewById(0x7f0a0032);
b.setOnClickListener(new ak(this));
}
}
| vishnudevk/MiBandDecompiled | Original Files/source/src/cn/com/smartdevices/bracelet/ui/FwLowBatteryActivity.java | Java | apache-2.0 | 1,282 |
package org.apache.lucene.analysis.ja;
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import org.apache.lucene.analysis.CharFilter;
import org.apache.lucene.analysis.util.RollingCharBuffer;
import java.io.IOException;
import java.io.Reader;
/**
* Normalizes Japanese horizontal iteration marks (odoriji) to their expanded form.
* <p>
* Sequences of iteration marks are supported. In case an illegal sequence of iteration
* marks is encountered, the implementation emits the illegal source character as-is
* without considering its script. For example, with input "?ゝ", we get
* "??" even though "?" isn't hiragana.
* </p>
* <p>
* Note that a full stop punctuation character "。" (U+3002) can not be iterated
* (see below). Iteration marks themselves can be emitted in case they are illegal,
* i.e. if they go back past the beginning of the character stream.
* </p>
* <p>
* The implementation buffers input until a full stop punctuation character (U+3002)
* or EOF is reached in order to not keep a copy of the character stream in memory.
* Vertical iteration marks, which are even rarer than horizontal iteration marks in
* contemporary Japanese, are unsupported.
* </p>
*/
public class JapaneseIterationMarkCharFilter extends CharFilter {
/** Normalize kanji iteration marks by default */
public static final boolean NORMALIZE_KANJI_DEFAULT = true;
/** Normalize kana iteration marks by default */
public static final boolean NORMALIZE_KANA_DEFAULT = true;
private static final char KANJI_ITERATION_MARK = '\u3005'; // 々
private static final char HIRAGANA_ITERATION_MARK = '\u309d'; // ゝ
private static final char HIRAGANA_VOICED_ITERATION_MARK = '\u309e'; // ゞ
private static final char KATAKANA_ITERATION_MARK = '\u30fd'; // ヽ
private static final char KATAKANA_VOICED_ITERATION_MARK = '\u30fe'; // ヾ
private static final char FULL_STOP_PUNCTUATION = '\u3002'; // 。
// Hiragana to dakuten map (lookup using code point - 0x30ab(か)*/
private static char[] h2d = new char[50];
// Katakana to dakuten map (lookup using code point - 0x30ab(カ
private static char[] k2d = new char[50];
private final RollingCharBuffer buffer = new RollingCharBuffer();
private int bufferPosition = 0;
private int iterationMarksSpanSize = 0;
private int iterationMarkSpanEndPosition = 0;
private boolean normalizeKanji;
private boolean normalizeKana;
static {
// Hiragana dakuten map
h2d[0] = '\u304c'; // か => が
h2d[1] = '\u304c'; // が => が
h2d[2] = '\u304e'; // き => ぎ
h2d[3] = '\u304e'; // ぎ => ぎ
h2d[4] = '\u3050'; // く => ぐ
h2d[5] = '\u3050'; // ぐ => ぐ
h2d[6] = '\u3052'; // け => げ
h2d[7] = '\u3052'; // げ => げ
h2d[8] = '\u3054'; // こ => ご
h2d[9] = '\u3054'; // ご => ご
h2d[10] = '\u3056'; // さ => ざ
h2d[11] = '\u3056'; // ざ => ざ
h2d[12] = '\u3058'; // し => じ
h2d[13] = '\u3058'; // じ => じ
h2d[14] = '\u305a'; // す => ず
h2d[15] = '\u305a'; // ず => ず
h2d[16] = '\u305c'; // せ => ぜ
h2d[17] = '\u305c'; // ぜ => ぜ
h2d[18] = '\u305e'; // そ => ぞ
h2d[19] = '\u305e'; // ぞ => ぞ
h2d[20] = '\u3060'; // た => だ
h2d[21] = '\u3060'; // だ => だ
h2d[22] = '\u3062'; // ち => ぢ
h2d[23] = '\u3062'; // ぢ => ぢ
h2d[24] = '\u3063';
h2d[25] = '\u3065'; // つ => づ
h2d[26] = '\u3065'; // づ => づ
h2d[27] = '\u3067'; // て => で
h2d[28] = '\u3067'; // で => で
h2d[29] = '\u3069'; // と => ど
h2d[30] = '\u3069'; // ど => ど
h2d[31] = '\u306a';
h2d[32] = '\u306b';
h2d[33] = '\u306c';
h2d[34] = '\u306d';
h2d[35] = '\u306e';
h2d[36] = '\u3070'; // は => ば
h2d[37] = '\u3070'; // ば => ば
h2d[38] = '\u3071';
h2d[39] = '\u3073'; // ひ => び
h2d[40] = '\u3073'; // び => び
h2d[41] = '\u3074';
h2d[42] = '\u3076'; // ふ => ぶ
h2d[43] = '\u3076'; // ぶ => ぶ
h2d[44] = '\u3077';
h2d[45] = '\u3079'; // へ => べ
h2d[46] = '\u3079'; // べ => べ
h2d[47] = '\u307a';
h2d[48] = '\u307c'; // ほ => ぼ
h2d[49] = '\u307c'; // ぼ => ぼ
// Make katakana dakuten map from hiragana map
char codePointDifference = '\u30ab' - '\u304b'; // カ - か
assert h2d.length == k2d.length;
for (int i = 0; i < k2d.length; i++) {
k2d[i] = (char) (h2d[i] + codePointDifference);
}
}
/**
* Constructor. Normalizes both kanji and kana iteration marks by default.
*
* @param input char stream
*/
public JapaneseIterationMarkCharFilter(Reader input) {
this(input, NORMALIZE_KANJI_DEFAULT, NORMALIZE_KANA_DEFAULT);
}
/**
* Constructor
*
* @param input char stream
* @param normalizeKanji indicates whether kanji iteration marks should be normalized
* @param normalizeKana indicates whether kana iteration marks should be normalized
*/
public JapaneseIterationMarkCharFilter(Reader input, boolean normalizeKanji, boolean normalizeKana) {
super(input);
this.normalizeKanji = normalizeKanji;
this.normalizeKana = normalizeKana;
buffer.reset(input);
}
/**
* {@inheritDoc}
*/
@Override
public int read(char[] buffer, int offset, int length) throws IOException {
int read = 0;
for (int i = offset; i < offset + length; i++) {
int c = read();
if (c == -1) {
break;
}
buffer[i] = (char) c;
read++;
}
return read == 0 ? -1 : read;
}
/**
* {@inheritDoc}
*/
@Override
public int read() throws IOException {
int ic = buffer.get(bufferPosition);
// End of input
if (ic == -1) {
buffer.freeBefore(bufferPosition);
return ic;
}
char c = (char) ic;
// Skip surrogate pair characters
if (Character.isHighSurrogate(c) || Character.isLowSurrogate(c)) {
iterationMarkSpanEndPosition = bufferPosition + 1;
}
// Free rolling buffer on full stop
if (c == FULL_STOP_PUNCTUATION) {
buffer.freeBefore(bufferPosition);
iterationMarkSpanEndPosition = bufferPosition + 1;
}
// Normalize iteration mark
if (isIterationMark(c)) {
c = normalizeIterationMark(c);
}
bufferPosition++;
return c;
}
/**
* Normalizes the iteration mark character c
*
* @param c iteration mark character to normalize
* @return normalized iteration mark
* @throws IOException If there is a low-level I/O error.
*/
private char normalizeIterationMark(char c) throws IOException {
// Case 1: Inside an iteration mark span
if (bufferPosition < iterationMarkSpanEndPosition) {
return normalize(sourceCharacter(bufferPosition, iterationMarksSpanSize), c);
}
// Case 2: New iteration mark spans starts where the previous one ended, which is illegal
if (bufferPosition == iterationMarkSpanEndPosition) {
// Emit the illegal iteration mark and increase end position to indicate that we can't
// start a new span on the next position either
iterationMarkSpanEndPosition++;
return c;
}
// Case 3: New iteration mark span
iterationMarksSpanSize = nextIterationMarkSpanSize();
iterationMarkSpanEndPosition = bufferPosition + iterationMarksSpanSize;
return normalize(sourceCharacter(bufferPosition, iterationMarksSpanSize), c);
}
/**
* Finds the number of subsequent next iteration marks
*
* @return number of iteration marks starting at the current buffer position
* @throws IOException If there is a low-level I/O error.
*/
private int nextIterationMarkSpanSize() throws IOException {
int spanSize = 0;
for (int i = bufferPosition; buffer.get(i) != -1 && isIterationMark((char) (buffer.get(i))); i++) {
spanSize++;
}
// Restrict span size so that we don't go past the previous end position
if (bufferPosition - spanSize < iterationMarkSpanEndPosition) {
spanSize = bufferPosition - iterationMarkSpanEndPosition;
}
return spanSize;
}
/**
* Returns the source character for a given position and iteration mark span size
*
* @param position buffer position (should not exceed bufferPosition)
* @param spanSize iteration mark span size
* @return source character
* @throws IOException If there is a low-level I/O error.
*/
private char sourceCharacter(int position, int spanSize) throws IOException {
return (char) buffer.get(position - spanSize);
}
/**
* Normalize a character
*
* @param c character to normalize
* @param m repetition mark referring to c
* @return normalized character - return c on illegal iteration marks
*/
private char normalize(char c, char m) {
if (isHiraganaIterationMark(m)) {
return normalizedHiragana(c, m);
}
if (isKatakanaIterationMark(m)) {
return normalizedKatakana(c, m);
}
return c; // If m is not kana and we are to normalize it, we assume it is kanji and simply return it
}
/**
* Normalize hiragana character
*
* @param c hiragana character
* @param m repetition mark referring to c
* @return normalized character - return c on illegal iteration marks
*/
private char normalizedHiragana(char c, char m) {
switch (m) {
case HIRAGANA_ITERATION_MARK:
return isHiraganaDakuten(c) ? (char) (c - 1) : c;
case HIRAGANA_VOICED_ITERATION_MARK:
return lookupHiraganaDakuten(c);
default:
return c;
}
}
/**
* Normalize katakana character
*
* @param c katakana character
* @param m repetition mark referring to c
* @return normalized character - return c on illegal iteration marks
*/
private char normalizedKatakana(char c, char m) {
switch (m) {
case KATAKANA_ITERATION_MARK:
return isKatakanaDakuten(c) ? (char) (c - 1) : c;
case KATAKANA_VOICED_ITERATION_MARK:
return lookupKatakanaDakuten(c);
default:
return c;
}
}
/**
* Iteration mark character predicate
*
* @param c character to test
* @return true if c is an iteration mark character. Otherwise false.
*/
private boolean isIterationMark(char c) {
return isKanjiIterationMark(c) || isHiraganaIterationMark(c) || isKatakanaIterationMark(c);
}
/**
* Hiragana iteration mark character predicate
*
* @param c character to test
* @return true if c is a hiragana iteration mark character. Otherwise false.
*/
private boolean isHiraganaIterationMark(char c) {
if (normalizeKana) {
return c == HIRAGANA_ITERATION_MARK || c == HIRAGANA_VOICED_ITERATION_MARK;
} else {
return false;
}
}
/**
* Katakana iteration mark character predicate
*
* @param c character to test
* @return true if c is a katakana iteration mark character. Otherwise false.
*/
private boolean isKatakanaIterationMark(char c) {
if (normalizeKana) {
return c == KATAKANA_ITERATION_MARK || c == KATAKANA_VOICED_ITERATION_MARK;
} else {
return false;
}
}
/**
* Kanji iteration mark character predicate
*
* @param c character to test
* @return true if c is a kanji iteration mark character. Otherwise false.
*/
private boolean isKanjiIterationMark(char c) {
if (normalizeKanji) {
return c == KANJI_ITERATION_MARK;
} else {
return false;
}
}
/**
* Look up hiragana dakuten
*
* @param c character to look up
* @return hiragana dakuten variant of c or c itself if no dakuten variant exists
*/
private char lookupHiraganaDakuten(char c) {
return lookup(c, h2d, '\u304b'); // Code point is for か
}
/**
* Look up katakana dakuten. Only full-width katakana are supported.
*
* @param c character to look up
* @return katakana dakuten variant of c or c itself if no dakuten variant exists
*/
private char lookupKatakanaDakuten(char c) {
return lookup(c, k2d, '\u30ab'); // Code point is for カ
}
/**
* Hiragana dakuten predicate
*
* @param c character to check
* @return true if c is a hiragana dakuten and otherwise false
*/
private boolean isHiraganaDakuten(char c) {
return inside(c, h2d, '\u304b') && c == lookupHiraganaDakuten(c);
}
/**
* Katakana dakuten predicate
*
* @param c character to check
* @return true if c is a hiragana dakuten and otherwise false
*/
private boolean isKatakanaDakuten(char c) {
return inside(c, k2d, '\u30ab') && c == lookupKatakanaDakuten(c);
}
/**
* Looks up a character in dakuten map and returns the dakuten variant if it exists.
* Otherwise return the character being looked up itself
*
* @param c character to look up
* @param map dakuten map
* @param offset code point offset from c
* @return mapped character or c if no mapping exists
*/
private char lookup(char c, char[] map, char offset) {
if (!inside(c, map, offset)) {
return c;
} else {
return map[c - offset];
}
}
/**
* Predicate indicating if the lookup character is within dakuten map range
*
* @param c character to look up
* @param map dakuten map
* @param offset code point offset from c
* @return true if c is mapped by map and otherwise false
*/
private boolean inside(char c, char[] map, char offset) {
return c >= offset && c < offset + map.length;
}
@Override
protected int correct(int currentOff) {
return currentOff; // this filter doesn't change the length of strings
}
}
| visouza/solr-5.0.0 | lucene/analysis/kuromoji/src/java/org/apache/lucene/analysis/ja/JapaneseIterationMarkCharFilter.java | Java | apache-2.0 | 14,447 |
package cn.hugo.android.mtd.exception;
public class MTDError extends Exception {
public MTDError(String message, Throwable tr) {
super(message, tr);
}
public MTDError(Exception e) {
super(e);
}
public MTDError(String message) {
super(message);
}
private static final long serialVersionUID = -2720998960647552784L;
}
| githubzoujiayun/mtd | mtd/src/cn/hugo/android/mtd/exception/MTDError.java | Java | apache-2.0 | 336 |
/*******************************************************************************
*
* Pentaho Data Integration
*
* Copyright (C) 2002-2012 by Pentaho : http://www.pentaho.com
*
*******************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
package org.pentaho.di.ui.trans.steps.scriptvalues_mod;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.util.Collections;
import java.util.Date;
import java.util.Hashtable;
import java.util.List;
import java.util.Vector;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.custom.CTabFolder2Adapter;
import org.eclipse.swt.custom.CTabFolderEvent;
import org.eclipse.swt.custom.CTabItem;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.custom.TreeEditor;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.DragSource;
import org.eclipse.swt.dnd.DragSourceAdapter;
import org.eclipse.swt.dnd.DragSourceEvent;
import org.eclipse.swt.dnd.TextTransfer;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.events.FocusAdapter;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.ShellAdapter;
import org.eclipse.swt.events.ShellEvent;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;
import org.mozilla.javascript.CompilerEnvirons;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.ContextFactory;
import org.mozilla.javascript.ErrorReporter;
import org.mozilla.javascript.EvaluatorException;
import org.mozilla.javascript.JavaScriptException;
import org.mozilla.javascript.NodeTransformer;
import org.mozilla.javascript.Parser;
import org.mozilla.javascript.Script;
import org.mozilla.javascript.ScriptOrFnNode;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.ScriptableObject;
import org.mozilla.javascript.tools.ToolErrorReporter;
import org.pentaho.di.compatibility.Row;
import org.pentaho.di.compatibility.Value;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.Props;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.plugins.PluginRegistry;
import org.pentaho.di.core.plugins.StepPluginType;
import org.pentaho.di.core.row.RowMeta;
import org.pentaho.di.core.row.RowMetaInterface;
import org.pentaho.di.core.row.ValueMeta;
import org.pentaho.di.core.row.ValueMetaInterface;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.di.trans.Trans;
import org.pentaho.di.trans.TransHopMeta;
import org.pentaho.di.trans.TransMeta;
import org.pentaho.di.trans.step.BaseStepMeta;
import org.pentaho.di.trans.step.StepDialogInterface;
import org.pentaho.di.trans.step.StepMeta;
import org.pentaho.di.trans.steps.rowgenerator.RowGeneratorMeta;
import org.pentaho.di.trans.steps.scriptvalues_mod.ScriptValuesAddedFunctions;
import org.pentaho.di.trans.steps.scriptvalues_mod.ScriptValuesMetaMod;
import org.pentaho.di.trans.steps.scriptvalues_mod.ScriptValuesModDummy;
import org.pentaho.di.trans.steps.scriptvalues_mod.ScriptValuesScript;
import org.pentaho.di.ui.core.dialog.EnterTextDialog;
import org.pentaho.di.ui.core.dialog.ErrorDialog;
import org.pentaho.di.ui.core.dialog.PreviewRowsDialog;
import org.pentaho.di.ui.core.gui.GUIResource;
import org.pentaho.di.ui.core.widget.ColumnInfo;
import org.pentaho.di.ui.core.widget.StyledTextComp;
import org.pentaho.di.ui.core.widget.TableView;
import org.pentaho.di.ui.core.widget.TextVar;
import org.pentaho.di.ui.spoon.Spoon;
import org.pentaho.di.ui.trans.dialog.TransPreviewProgressDialog;
import org.pentaho.di.ui.trans.step.BaseStepDialog;
public class ScriptValuesModDialog extends BaseStepDialog implements StepDialogInterface
{
private static Class<?> PKG = ScriptValuesMetaMod.class; // for i18n purposes, needed by Translator2!! $NON-NLS-1$
private static final String[] YES_NO_COMBO = new String[] { BaseMessages.getString(PKG, "System.Combo.No"), BaseMessages.getString(PKG, "System.Combo.Yes") };
private ModifyListener lsMod;
private SashForm wSash;
private FormData fdSash;
private Composite wTop, wBottom;
private FormData fdTop, fdBottom;
private Label wlScript;
private FormData fdlScript, fdScript;
private Label wSeparator;
private FormData fdSeparator;
private Label wlFields;
private TableView wFields;
private FormData fdlFields, fdFields;
private Label wlPosition;
private FormData fdlPosition;
private Text wlHelpLabel;
private Button wVars, wTest;
private Listener lsVars, lsTest;
// private Button wHelp;
private Label wlScriptFunctions;
private FormData fdlScriptFunctions;
private Tree wTree;
private TreeItem wTreeScriptsItem;
private TreeItem wTreeClassesitem;
private FormData fdlTree;
private Listener lsTree;
// private Listener lsHelp;
private FormData fdHelpLabel;
private Image imageActiveScript=null;
private Image imageInactiveScript=null;
private Image imageActiveStartScript=null;
private Image imageActiveEndScript=null;
private Image imageInputFields=null;
private Image imageOutputFields=null;
private Image imageArrowOrange=null;
private Image imageArrowGreen=null;
private Image imageUnderGreen=null;
private Image imageAddScript=null;
private Image imageDeleteScript=null;
private Image imageDuplicateScript=null;
private CTabFolder folder;
private Menu cMenu;
private Menu tMenu;
// Suport for Rename Tree
private TreeItem [] lastItem;
private TreeEditor editor;
private static final int DELETE_ITEM = 0;
private static final int ADD_ITEM = 1;
private static final int RENAME_ITEM = 2;
private static final int SET_ACTIVE_ITEM = 3;
private static final int ADD_COPY = 2;
private static final int ADD_BLANK = 1;
private static final int ADD_DEFAULT = 0;
private String strActiveScript;
private String strActiveStartScript;
private String strActiveEndScript;
private static String[] jsFunctionList = ScriptValuesAddedFunctions.jsFunctionList;
public final static int SKIP_TRANSFORMATION = 1;
private final static int ABORT_TRANSFORMATION = -1;
private final static int ERROR_TRANSFORMATION = -2;
private final static int CONTINUE_TRANSFORMATION = 0;
private ScriptValuesMetaMod input;
private ScriptValuesHelp scVHelp;
private ScriptValuesHighlight lineStyler = new ScriptValuesHighlight();
private Button wCompatible;
private TextVar wOptimizationLevel;
private TreeItem iteminput;
private TreeItem itemoutput;
private static GUIResource guiresource=GUIResource.getInstance();
private TreeItem itemWaitFieldsIn,itemWaitFieldsOut;
private RowMetaInterface rowPrevStepFields;;
private RowGeneratorMeta genMeta;
public ScriptValuesModDialog(Shell parent, Object in, TransMeta transMeta, String sname){
super(parent, (BaseStepMeta)in, transMeta, sname);
input=(ScriptValuesMetaMod)in;
genMeta = null;
try{
//ImageLoader xl = new ImageLoader();
imageUnderGreen = guiresource.getImage("ui/images/underGreen.png");
imageArrowGreen = guiresource.getImage("ui/images/arrowGreen.png");
imageArrowOrange = guiresource.getImage("ui/images/arrowOrange.png");
imageInputFields = guiresource.getImage("ui/images/inSmall.png");
imageOutputFields = guiresource.getImage("ui/images/outSmall.png");
imageActiveScript = guiresource.getImage("ui/images/faScript.png");
imageInactiveScript = guiresource.getImage("ui/images/hide-inactive.png");
imageActiveStartScript = guiresource.getImage("ui/images/SQLbutton.png");
imageActiveEndScript = guiresource.getImage("ui/images/edfScript.png");
imageDeleteScript = guiresource.getImage("ui/images/deleteSmall.png");
imageAddScript = guiresource.getImage("ui/images/addSmall.png");
imageDuplicateScript = guiresource.getImage("ui/images/copySmall.png");
}catch(Exception e){
imageActiveScript = guiresource.getImageEmpty16x16();
imageInactiveScript = guiresource.getImageEmpty16x16();
imageActiveStartScript = guiresource.getImageEmpty16x16();
imageActiveEndScript = guiresource.getImageEmpty16x16();
imageInputFields = guiresource.getImageEmpty16x16();
imageOutputFields = guiresource.getImageEmpty16x16();
imageArrowOrange = guiresource.getImageEmpty16x16();
imageArrowGreen= guiresource.getImageEmpty16x16();
imageUnderGreen= guiresource.getImageEmpty16x16();
imageDeleteScript= guiresource.getImageEmpty16x16();
imageAddScript= guiresource.getImageEmpty16x16();
imageDuplicateScript= guiresource.getImageEmpty16x16();
}
try
{
scVHelp = new ScriptValuesHelp("jsFunctionHelp.xml");
}
catch (Exception e)
{
new ErrorDialog(shell, "Unexpected error", "There was an unexpected error reading the javascript functions help", e);
}
}
public String open(){
Shell parent = getParent();
Display display = parent.getDisplay();
shell = new Shell(parent, SWT.DIALOG_TRIM | SWT.RESIZE | SWT.MAX | SWT.MIN);
props.setLook(shell);
setShellImage(shell, input);
lsMod = new ModifyListener()
{
public void modifyText(ModifyEvent e)
{
input.setChanged();
}
};
changed = input.hasChanged();
FormLayout formLayout = new FormLayout ();
formLayout.marginWidth = Const.FORM_MARGIN;
formLayout.marginHeight = Const.FORM_MARGIN;
shell.setLayout(formLayout);
shell.setText(BaseMessages.getString(PKG, "ScriptValuesDialogMod.Shell.Title")); //$NON-NLS-1$
int middle = props.getMiddlePct();
int margin = Const.MARGIN;
// Filename line
wlStepname=new Label(shell, SWT.RIGHT);
wlStepname.setText(BaseMessages.getString(PKG, "ScriptValuesDialogMod.Stepname.Label")); //$NON-NLS-1$
props.setLook(wlStepname);
fdlStepname=new FormData();
fdlStepname.left = new FormAttachment(0, 0);
fdlStepname.right= new FormAttachment(middle, -margin);
fdlStepname.top = new FormAttachment(0, margin);
wlStepname.setLayoutData(fdlStepname);
wStepname=new Text(shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
wStepname.setText(stepname);
props.setLook(wStepname);
wStepname.addModifyListener(lsMod);
fdStepname=new FormData();
fdStepname.left = new FormAttachment(middle, 0);
fdStepname.top = new FormAttachment(0, margin);
fdStepname.right= new FormAttachment(100, 0);
wStepname.setLayoutData(fdStepname);
wSash = new SashForm(shell, SWT.VERTICAL );
// Top sash form
//
wTop = new Composite(wSash, SWT.NONE);
props.setLook(wTop);
FormLayout topLayout = new FormLayout ();
topLayout.marginWidth = Const.FORM_MARGIN;
topLayout.marginHeight = Const.FORM_MARGIN;
wTop.setLayout(topLayout);
// Script line
wlScriptFunctions=new Label(wTop, SWT.NONE);
wlScriptFunctions.setText(BaseMessages.getString(PKG, "ScriptValuesDialogMod.JavascriptFunctions.Label")); //$NON-NLS-1$
props.setLook(wlScriptFunctions);
fdlScriptFunctions=new FormData();
fdlScriptFunctions.left = new FormAttachment(0, 0);
fdlScriptFunctions.top = new FormAttachment(0, 0);
wlScriptFunctions.setLayoutData(fdlScriptFunctions);
// Tree View Test
wTree = new Tree(wTop, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL);
props.setLook(wTree);
fdlTree=new FormData();
fdlTree.left = new FormAttachment(0, 0);
fdlTree.top = new FormAttachment(wlScriptFunctions, margin);
fdlTree.right = new FormAttachment(20, 0);
fdlTree.bottom = new FormAttachment(100, -margin);
wTree.setLayoutData(fdlTree);
// Script line
wlScript=new Label(wTop, SWT.NONE);
wlScript.setText(BaseMessages.getString(PKG, "ScriptValuesDialogMod.Javascript.Label")); //$NON-NLS-1$
props.setLook(wlScript);
fdlScript=new FormData();
fdlScript.left = new FormAttachment(wTree, margin);
fdlScript.top = new FormAttachment(0, 0);
wlScript.setLayoutData(fdlScript);
folder = new CTabFolder(wTop, SWT.BORDER | SWT.RESIZE);
folder.setSimple(false);
folder.setUnselectedImageVisible(true);
folder.setUnselectedCloseVisible(true);
fdScript=new FormData();
fdScript.left = new FormAttachment(wTree, margin);
fdScript.top = new FormAttachment(wlScript, margin);
fdScript.right = new FormAttachment(100, -5);
fdScript.bottom = new FormAttachment(100, -50);
folder.setLayoutData(fdScript);
wlPosition=new Label(wTop, SWT.NONE);
wlPosition.setText(BaseMessages.getString(PKG, "ScriptValuesDialogMod.Position.Label")); //$NON-NLS-1$
props.setLook(wlPosition);
fdlPosition=new FormData();
fdlPosition.left = new FormAttachment(wTree, margin);
fdlPosition.right = new FormAttachment(30, 0);
fdlPosition.top = new FormAttachment(folder, margin);
wlPosition.setLayoutData(fdlPosition);
Label wlCompatible = new Label(wTop, SWT.NONE);
wlCompatible.setText(BaseMessages.getString(PKG, "ScriptValuesDialogMod.Compatible.Label")); //$NON-NLS-1$
props.setLook(wlCompatible);
FormData fdlCompatible = new FormData();
fdlCompatible.left = new FormAttachment(wTree, margin);
fdlCompatible.right = new FormAttachment(middle, 0);
fdlCompatible.top = new FormAttachment(wlPosition, margin);
wlCompatible.setLayoutData(fdlCompatible);
wCompatible = new Button(wTop, SWT.CHECK);
wCompatible.setToolTipText(BaseMessages.getString(PKG, "ScriptValuesDialogMod.Compatible.Tooltip"));
props.setLook(wCompatible);
FormData fdCompatible = new FormData();
fdCompatible.left = new FormAttachment(wlCompatible, margin);
fdCompatible.top = new FormAttachment(wlPosition, margin);
wCompatible.setLayoutData(fdCompatible);
wCompatible.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { setInputOutputFields(); input.setChanged(true);} });
Label wlOptimizationLevel = new Label(wTop, SWT.NONE);
wlOptimizationLevel.setText(BaseMessages.getString(PKG, "ScriptValuesDialogMod.OptimizationLevel.Label")); //$NON-NLS-1$
props.setLook(wlOptimizationLevel);
FormData fdlOptimizationLevel = new FormData();
fdlOptimizationLevel.left = new FormAttachment(wCompatible, margin*2);
fdlOptimizationLevel.top = new FormAttachment(wlPosition, margin);
wlOptimizationLevel.setLayoutData(fdlOptimizationLevel);
wOptimizationLevel = new TextVar(transMeta, wTop, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
wOptimizationLevel.setToolTipText(BaseMessages.getString(PKG, "ScriptValuesDialogMod.OptimizationLevel.Tooltip"));
props.setLook(wOptimizationLevel);
FormData fdOptimizationLevel = new FormData();
fdOptimizationLevel.left = new FormAttachment(wlOptimizationLevel, margin);
fdOptimizationLevel.top = new FormAttachment(wlPosition, margin);
fdOptimizationLevel.right = new FormAttachment(100, margin);
wOptimizationLevel.setLayoutData(fdOptimizationLevel);
wOptimizationLevel.addModifyListener(lsMod);
wlHelpLabel = new Text(wTop, SWT.V_SCROLL | SWT.LEFT);
wlHelpLabel.setEditable(false);
wlHelpLabel.setText("Hallo");
props.setLook(wlHelpLabel);
fdHelpLabel = new FormData();
fdHelpLabel.left = new FormAttachment(wlPosition, margin);
fdHelpLabel.top = new FormAttachment(folder, margin);
fdHelpLabel.right = new FormAttachment(100, -5);
fdHelpLabel.bottom = new FormAttachment(100,0);
wlHelpLabel.setLayoutData(fdHelpLabel);
wlHelpLabel.setVisible(false);
fdTop=new FormData();
fdTop.left = new FormAttachment(0, 0);
fdTop.top = new FormAttachment(0, 0);
fdTop.right = new FormAttachment(100, 0);
fdTop.bottom= new FormAttachment(100, 0);
wTop.setLayoutData(fdTop);
wBottom = new Composite(wSash, SWT.NONE);
props.setLook(wBottom);
FormLayout bottomLayout = new FormLayout ();
bottomLayout.marginWidth = Const.FORM_MARGIN;
bottomLayout.marginHeight = Const.FORM_MARGIN;
wBottom.setLayout(bottomLayout);
wSeparator = new Label(wBottom, SWT.SEPARATOR | SWT.HORIZONTAL);
fdSeparator= new FormData();
fdSeparator.left = new FormAttachment(0, 0);
fdSeparator.right = new FormAttachment(100, 0);
fdSeparator.top = new FormAttachment(0, -margin+2);
wSeparator.setLayoutData(fdSeparator);
wlFields=new Label(wBottom, SWT.NONE);
wlFields.setText(BaseMessages.getString(PKG, "ScriptValuesDialogMod.Fields.Label")); //$NON-NLS-1$
props.setLook(wlFields);
fdlFields=new FormData();
fdlFields.left = new FormAttachment(0, 0);
fdlFields.top = new FormAttachment(wSeparator, 0);
wlFields.setLayoutData(fdlFields);
final int FieldsRows=input.getFieldname().length;
ColumnInfo[] colinf=new ColumnInfo[]
{
new ColumnInfo(BaseMessages.getString(PKG, "ScriptValuesDialogMod.ColumnInfo.Filename"), ColumnInfo.COLUMN_TYPE_TEXT, false), //$NON-NLS-1$
new ColumnInfo(BaseMessages.getString(PKG, "ScriptValuesDialogMod.ColumnInfo.RenameTo"), ColumnInfo.COLUMN_TYPE_TEXT, false ), //$NON-NLS-1$
new ColumnInfo(BaseMessages.getString(PKG, "ScriptValuesDialogMod.ColumnInfo.Type"), ColumnInfo.COLUMN_TYPE_CCOMBO, ValueMeta.getTypes() ), //$NON-NLS-1$
new ColumnInfo(BaseMessages.getString(PKG, "ScriptValuesDialogMod.ColumnInfo.Length"), ColumnInfo.COLUMN_TYPE_TEXT, false), //$NON-NLS-1$
new ColumnInfo(BaseMessages.getString(PKG, "ScriptValuesDialogMod.ColumnInfo.Precision"), ColumnInfo.COLUMN_TYPE_TEXT, false), //$NON-NLS-1$
new ColumnInfo(BaseMessages.getString(PKG, "ScriptValuesDialogMod.ColumnInfo.Replace"), ColumnInfo.COLUMN_TYPE_CCOMBO, YES_NO_COMBO ), //$NON-NLS-1$
};
wFields=new TableView(transMeta, wBottom,
SWT.BORDER | SWT.FULL_SELECTION | SWT.MULTI,
colinf,
FieldsRows,
lsMod,
props
);
fdFields=new FormData();
fdFields.left = new FormAttachment(0, 0);
fdFields.top = new FormAttachment(wlFields, margin);
fdFields.right = new FormAttachment(100, 0);
fdFields.bottom = new FormAttachment(100, 0);
wFields.setLayoutData(fdFields);
fdBottom=new FormData();
fdBottom.left = new FormAttachment(0, 0);
fdBottom.top = new FormAttachment(0, 0);
fdBottom.right = new FormAttachment(100, 0);
fdBottom.bottom= new FormAttachment(100, 0);
wBottom.setLayoutData(fdBottom);
fdSash = new FormData();
fdSash.left = new FormAttachment(0, 0);
fdSash.top = new FormAttachment(wStepname, 0);
fdSash.right = new FormAttachment(100, 0);
fdSash.bottom= new FormAttachment(100, -50);
wSash.setLayoutData(fdSash);
wSash.setWeights(new int[] {75,25});
wOK=new Button(shell, SWT.PUSH);
wOK.setText(BaseMessages.getString(PKG, "System.Button.OK")); //$NON-NLS-1$
wVars=new Button(shell, SWT.PUSH);
wVars.setText(BaseMessages.getString(PKG, "ScriptValuesDialogMod.GetVariables.Button")); //$NON-NLS-1$
wTest=new Button(shell, SWT.PUSH);
wTest.setText(BaseMessages.getString(PKG, "ScriptValuesDialogMod.TestScript.Button")); //$NON-NLS-1$
wCancel=new Button(shell, SWT.PUSH);
wCancel.setText(BaseMessages.getString(PKG, "System.Button.Cancel")); //$NON-NLS-1$
setButtonPositions(new Button[] { wOK, wCancel , wVars, wTest }, margin, null);
// Add listeners
lsCancel = new Listener() { public void handleEvent(Event e) { cancel(); } };
//lsGet = new Listener() { public void handleEvent(Event e) { get(); } };
lsTest = new Listener() { public void handleEvent(Event e) { newTest(); } };
lsVars = new Listener() { public void handleEvent(Event e) { test(true, true); } };
lsOK = new Listener() { public void handleEvent(Event e) { ok(); } };
lsTree = new Listener() { public void handleEvent(Event e) { treeDblClick(e); } };
// lsHelp = new Listener(){public void handleEvent(Event e){ wlHelpLabel.setVisible(true); }};
wCancel.addListener(SWT.Selection, lsCancel);
//wGet.addListener (SWT.Selection, lsGet );
wTest.addListener (SWT.Selection, lsTest );
wVars.addListener (SWT.Selection, lsVars );
wOK.addListener (SWT.Selection, lsOK );
wTree.addListener(SWT.MouseDoubleClick, lsTree);
lsDef=new SelectionAdapter() { public void widgetDefaultSelected(SelectionEvent e) { ok(); } };
wStepname.addSelectionListener( lsDef );
// Detect X or ALT-F4 or something that kills this window...
shell.addShellListener( new ShellAdapter() { public void shellClosed(ShellEvent e) { if (!cancel()) { e.doit=false; } } } );
folder.addCTabFolder2Listener(new CTabFolder2Adapter() {
public void close(CTabFolderEvent event) {
CTabItem cItem = (CTabItem)event.item;
event.doit=false;
if(cItem!=null && folder.getItemCount()>1){
MessageBox messageBox = new MessageBox(shell, SWT.ICON_QUESTION | SWT.NO | SWT.YES);
messageBox.setText(BaseMessages.getString(PKG, "ScriptValuesDialogMod.DeleteItem.Label"));
messageBox.setMessage(BaseMessages.getString(PKG, "ScriptValuesDialogMod.ConfirmDeleteItem.Label",cItem.getText()));
switch(messageBox.open()){
case SWT.YES:
modifyScriptTree(cItem,DELETE_ITEM);
event.doit=true;
break;
}
}
}
});
cMenu = new Menu(shell, SWT.POP_UP);
buildingFolderMenu();
tMenu = new Menu(shell, SWT.POP_UP);
buildingTreeMenu();
// Adding the Default Transform Scripts Item to the Tree
wTreeScriptsItem = new TreeItem(wTree, SWT.NULL);
wTreeScriptsItem.setImage(guiresource.getImageBol());
wTreeScriptsItem.setText(BaseMessages.getString(PKG, "ScriptValuesDialogMod.TransformScript.Label"));
// Set the shell size, based upon previous time...
setSize();
getData();
// Adding the Rest (Functions, InputItems, etc.) to the Tree
buildSpecialFunctionsTree();
// Input Fields
iteminput = new TreeItem(wTree, SWT.NULL);
iteminput.setImage(imageInputFields);
iteminput.setText(BaseMessages.getString(PKG, "ScriptValuesDialogMod.InputFields.Label"));
// Output Fields
itemoutput = new TreeItem(wTree, SWT.NULL);
itemoutput.setImage(imageOutputFields);
itemoutput.setText(BaseMessages.getString(PKG, "ScriptValuesDialogMod.OutputFields.Label"));
// Display waiting message for input
itemWaitFieldsIn = new TreeItem(iteminput, SWT.NULL);
itemWaitFieldsIn.setText(BaseMessages.getString(PKG, "ScriptValuesDialogMod.GettingFields.Label"));
itemWaitFieldsIn.setForeground(guiresource.getColorDirectory());
iteminput.setExpanded(true);
// Display waiting message for output
itemWaitFieldsOut = new TreeItem(itemoutput, SWT.NULL);
itemWaitFieldsOut.setText(BaseMessages.getString(PKG, "ScriptValuesDialogMod.GettingFields.Label"));
itemWaitFieldsOut.setForeground(guiresource.getColorDirectory());
itemoutput.setExpanded(true);
//
// Search the fields in the background
//
final Runnable runnable = new Runnable()
{
public void run()
{
StepMeta stepMeta = transMeta.findStep(stepname);
if (stepMeta!=null)
{
try
{
rowPrevStepFields = transMeta.getPrevStepFields(stepMeta);
if(rowPrevStepFields!=null) {
setInputOutputFields();
}else{
// Can not get fields...end of wait message
iteminput.removeAll();
itemoutput.removeAll();
}
}
catch(KettleException e)
{
logError(BaseMessages.getString(PKG, "System.Dialog.GetFieldsFailed.Message"));
}
}
}
};
new Thread(runnable).start();
//rebuildInputFieldsTree();
//buildOutputFieldsTree();
buildAddClassesListTree();
addRenameTowTreeScriptItems();
input.setChanged(changed);
// Create the drag source on the tree
DragSource ds = new DragSource(wTree, DND.DROP_MOVE);
ds.setTransfer(new Transfer[] { TextTransfer.getInstance() });
ds.addDragListener(new DragSourceAdapter() {
public void dragStart(DragSourceEvent event) {
TreeItem item = wTree.getSelection()[0];
// Qualifikation where the Drag Request Comes from
if(item !=null && item.getParentItem()!=null){
if(item.getParentItem().equals(wTreeScriptsItem)){
event.doit=false;
}else if(!item.getData().equals("Function")){
String strInsert =(String)item.getData();
if(strInsert.equals("jsFunction")) event.doit=true;
else event.doit=false;
}else{
event.doit=false;
}
}else{
event.doit=false;
}
}
public void dragSetData(DragSourceEvent event) {
// Set the data to be the first selected item's text
event.data = wTree.getSelection()[0].getText();
}
});
shell.open();
while (!shell.isDisposed()){
if (!display.readAndDispatch()) display.sleep();
}
return stepname;
}
private void setActiveCtab(String strName){
if(strName.length()==0){
folder.setSelection(0);
}
else folder.setSelection(getCTabPosition(strName));
}
private void addCtab(String cScriptName, String strScript, int iType){
CTabItem item = new CTabItem(folder, SWT.CLOSE);
switch(iType){
case ADD_DEFAULT: item.setText(cScriptName);
break;
default:
item.setText(getNextName(cScriptName));
break;
}
StyledTextComp wScript=new StyledTextComp(transMeta, item.getParent(), SWT.MULTI | SWT.LEFT | SWT.H_SCROLL | SWT.V_SCROLL, item.getText(), false);
if((strScript !=null) && strScript.length()>0) wScript.setText(strScript);
else wScript.setText(BaseMessages.getString(PKG, "ScriptValuesDialogMod.ScriptHere.Label")+Const.CR+Const.CR);
item.setImage(imageInactiveScript);
props.setLook(wScript, Props.WIDGET_STYLE_FIXED);
wScript.addKeyListener(new KeyAdapter(){
public void keyPressed(KeyEvent e) { setPosition(); }
public void keyReleased(KeyEvent e) { setPosition(); }
}
);
wScript.addFocusListener(new FocusAdapter(){
public void focusGained(FocusEvent e) { setPosition(); }
public void focusLost(FocusEvent e) { setPosition(); }
}
);
wScript.addMouseListener(new MouseAdapter(){
public void mouseDoubleClick(MouseEvent e) { setPosition(); }
public void mouseDown(MouseEvent e) { setPosition(); }
public void mouseUp(MouseEvent e) { setPosition(); }
}
);
wScript.addModifyListener(lsMod);
// Text Higlighting
lineStyler = new ScriptValuesHighlight(ScriptValuesAddedFunctions.jsFunctionList);
wScript.addLineStyleListener(lineStyler);
item.setControl(wScript);
// Adding new Item to Tree
modifyScriptTree(item, ADD_ITEM );
}
private void modifyScriptTree(CTabItem ctabitem, int iModType){
switch(iModType){
case DELETE_ITEM :
TreeItem dItem = getTreeItemByName(ctabitem.getText());
if(dItem!=null){
dItem.dispose();
input.setChanged();
}
break;
case ADD_ITEM :
TreeItem item = new TreeItem(wTreeScriptsItem, SWT.NULL);
item.setImage(imageActiveScript);
item.setText(ctabitem.getText());
input.setChanged();
break;
case RENAME_ITEM :
input.setChanged();
break;
case SET_ACTIVE_ITEM :
input.setChanged();
break;
}
}
private TreeItem getTreeItemByName(String strTabName){
TreeItem[] tItems = wTreeScriptsItem.getItems();
for(int i=0;i<tItems.length;i++){
if(tItems[i].getText().equals(strTabName)) return tItems[i];
}
return null;
}
private int getCTabPosition(String strTabName){
CTabItem[] cItems = folder.getItems();
for(int i=0;i<cItems.length;i++){
if(cItems[i].getText().equals(strTabName)) return i;
}
return -1;
}
private CTabItem getCTabItemByName(String strTabName){
CTabItem[] cItems = folder.getItems();
for(int i=0;i<cItems.length;i++){
if(cItems[i].getText().equals(strTabName)) return cItems[i];
}
return null;
}
private void modifyCTabItem(TreeItem tItem, int iModType, String strOption){
switch(iModType){
case DELETE_ITEM :
CTabItem dItem = folder.getItem(getCTabPosition(tItem.getText()));
if(dItem!=null){
dItem.dispose();
input.setChanged();
}
break;
case RENAME_ITEM :
CTabItem rItem = folder.getItem(getCTabPosition(tItem.getText()));
if(rItem!=null){
rItem.setText(strOption);
input.setChanged();
if(rItem.getImage().equals(imageActiveScript)) strActiveScript = strOption;
else if(rItem.getImage().equals(imageActiveStartScript)) strActiveStartScript = strOption;
else if(rItem.getImage().equals(imageActiveEndScript)) strActiveEndScript = strOption;
}
break;
case SET_ACTIVE_ITEM :
CTabItem aItem = folder.getItem(getCTabPosition(tItem.getText()));
if(aItem!=null){
input.setChanged();
strActiveScript = tItem.getText();
for(int i=0;i<folder.getItemCount();i++){
if(folder.getItem(i).equals(aItem))aItem.setImage(imageActiveScript);
else folder.getItem(i).setImage(imageInactiveScript);
}
}
break;
}
}
private StyledTextComp getStyledTextComp(){
CTabItem item = folder.getSelection();
if(item.getControl().isDisposed()) return null;
else return (StyledTextComp)item.getControl();
}
private StyledTextComp getStyledTextComp(CTabItem item){
return (StyledTextComp)item.getControl();
}
/*
private void setStyledTextComp(String strText){
CTabItem item = folder.getSelection();
((StyledTextComp)item.getControl()).setText(strText);
}
private void setStyledTextComp(String strText, CTabItem item){
((StyledTextComp)item.getControl()).setText(strText);
}
*/
private String getNextName(String strActualName){
String strRC = "";
if(strActualName.length()==0){
strActualName = "Item";
}
int i=0;
strRC = strActualName + "_" + i;
while(getCTabItemByName(strRC)!=null){
i++;
strRC = strActualName + "_" + i;
}
return strRC;
}
public void setPosition(){
StyledTextComp wScript = getStyledTextComp();
String scr = wScript.getText();
int linenr = wScript.getLineAtOffset(wScript.getCaretOffset())+1;
int posnr = wScript.getCaretOffset();
// Go back from position to last CR: how many positions?
int colnr=0;
while (posnr>0 && scr.charAt(posnr-1)!='\n' && scr.charAt(posnr-1)!='\r')
{
posnr--;
colnr++;
}
wlPosition.setText(BaseMessages.getString(PKG, "ScriptValuesDialogMod.Position.Label2")+linenr+", "+colnr); //$NON-NLS-1$ //$NON-NLS-2$
}
/**
* Copy information from the meta-data input to the dialog fields.
*/
public void getData()
{
wCompatible.setSelection(input.isCompatible());
if (!Const.isEmpty(Const.trim(input.getOptimizationLevel()))) {
wOptimizationLevel.setText(input.getOptimizationLevel().trim());
}
else {
wOptimizationLevel.setText(ScriptValuesMetaMod.OPTIMIZATION_LEVEL_DEFAULT);
}
for (int i=0;i<input.getFieldname().length;i++)
{
if (input.getFieldname()[i]!=null && input.getFieldname()[i].length()>0)
{
TableItem item = wFields.table.getItem(i);
item.setText(1, input.getFieldname()[i]);
if (input.getRename()[i]!=null && !input.getFieldname()[i].equals(input.getRename()[i]))
item.setText(2, input.getRename()[i]);
item.setText(3, ValueMeta.getTypeDesc(input.getType()[i]));
if (input.getLength()[i]>=0) item.setText(4, ""+input.getLength()[i]); //$NON-NLS-1$
if (input.getPrecision()[i]>=0) item.setText(5, ""+input.getPrecision()[i]); //$NON-NLS-1$
item.setText(6, input.getReplace()[i] ? YES_NO_COMBO[1] : YES_NO_COMBO[0]); //$NON-NLS-1$
}
}
ScriptValuesScript[] jsScripts = input.getJSScripts();
if(jsScripts.length>0){
for(int i=0;i<jsScripts.length;i++){
if(jsScripts[i].isTransformScript()) strActiveScript =jsScripts[i].getScriptName();
else if(jsScripts[i].isStartScript()) strActiveStartScript =jsScripts[i].getScriptName();
else if(jsScripts[i].isEndScript()) strActiveEndScript =jsScripts[i].getScriptName();
addCtab(jsScripts[i].getScriptName(), jsScripts[i].getScript(), ADD_DEFAULT);
}
}else{
addCtab("", "", ADD_DEFAULT);
}
setActiveCtab(strActiveScript);
refresh();
wFields.setRowNums();
wFields.optWidth(true);
wStepname.selectAll();
}
// Setting default active Script
private void refresh(){
//CTabItem item = getCTabItemByName(strActiveScript);
for(int i=0;i<folder.getItemCount();i++){
CTabItem item = folder.getItem(i);
if(item.getText().equals(strActiveScript))item.setImage(imageActiveScript);
else if(item.getText().equals(strActiveStartScript))item.setImage(imageActiveStartScript);
else if(item.getText().equals(strActiveEndScript))item.setImage(imageActiveEndScript);
else item.setImage(imageInactiveScript);
}
//modifyScriptTree(null, SET_ACTIVE_ITEM);
}
private void refreshScripts(){
CTabItem[] cTabs = folder.getItems();
for(int i =0;i<cTabs.length;i++){
if(cTabs[i].getImage().equals(imageActiveStartScript)) strActiveStartScript = cTabs[i].getText();
else if(cTabs[i].getImage().equals(imageActiveEndScript)) strActiveEndScript = cTabs[i].getText();
}
}
private boolean cancel()
{
if (input.hasChanged()) {
MessageBox box = new MessageBox(shell, SWT.YES | SWT.NO | SWT.APPLICATION_MODAL);
box.setText(BaseMessages.getString(PKG, "ScriptValuesModDialog.WarningDialogChanged.Title"));
box.setMessage(BaseMessages.getString(PKG, "ScriptValuesModDialog.WarningDialogChanged.Message", Const.CR));
int answer = box.open();
if (answer==SWT.NO) {
return false;
}
}
stepname = null;
input.setChanged(changed);
dispose();
return true;
}
private void getInfo(ScriptValuesMetaMod meta) {
meta.setCompatible( wCompatible.getSelection() );
meta.setOptimizationLevel(wOptimizationLevel.getText());
int nrfields = wFields.nrNonEmpty();
meta.allocate(nrfields);
for (int i=0;i<nrfields;i++){
TableItem item = wFields.getNonEmpty(i);
meta.getFieldname()[i] = item.getText(1);
meta.getRename()[i] = item.getText(2);
if (meta.getRename()[i]==null ||
meta.getRename()[i].length()==0 ||
meta.getRename()[i].equalsIgnoreCase(meta.getFieldname()[i])
)
{
meta.getRename()[i] = meta.getFieldname()[i];
}
meta.getType() [i] = ValueMeta.getType(item.getText(3));
String slen = item.getText(4);
String sprc = item.getText(5);
meta.getLength() [i]=Const.toInt(slen, -1);
meta.getPrecision()[i]=Const.toInt(sprc, -1);
meta.getReplace() [i]=YES_NO_COMBO[1].equalsIgnoreCase(item.getText(6));
}
//input.setActiveJSScript(strActiveScript);
CTabItem[] cTabs = folder.getItems();
if(cTabs.length>0){
ScriptValuesScript[] jsScripts = new ScriptValuesScript[cTabs.length];
for(int i=0;i<cTabs.length;i++){
ScriptValuesScript jsScript = new ScriptValuesScript(
ScriptValuesScript.NORMAL_SCRIPT,
cTabs[i].getText(),
getStyledTextComp(cTabs[i]).getText()
);
if(cTabs[i].getImage().equals(imageActiveScript)) jsScript.setScriptType(ScriptValuesScript.TRANSFORM_SCRIPT);
else if(cTabs[i].getImage().equals(imageActiveStartScript)) jsScript.setScriptType(ScriptValuesScript.START_SCRIPT);
else if(cTabs[i].getImage().equals(imageActiveEndScript)) jsScript.setScriptType(ScriptValuesScript.END_SCRIPT);
jsScripts[i] = jsScript;
}
meta.setJSScripts(jsScripts);
}
}
private void ok()
{
if (Const.isEmpty(wStepname.getText())) return;
stepname = wStepname.getText(); // return value
boolean bInputOK = false;
// Check if Active Script has set, otherwise Ask
if(getCTabItemByName(strActiveScript)==null){
MessageBox mb = new MessageBox(shell, SWT.OK | SWT.CANCEL | SWT.ICON_ERROR );
mb.setMessage(BaseMessages.getString(PKG, "ScriptValuesDialogMod.NoActiveScriptSet"));
mb.setText(BaseMessages.getString(PKG, "ScriptValuesDialogMod.ERROR.Label")); //$NON-NLS-1$
switch(mb.open()){
case SWT.OK:
strActiveScript = folder.getItem(0).getText();
refresh();
bInputOK = true;
break;
case SWT.CANCEL: bInputOK = false;
break;
}
}else{
bInputOK = true;
}
if (bInputOK && wCompatible.getSelection()) {
// If in compatibility mode the "replace" column must not be "Yes"
int nrfields = wFields.nrNonEmpty();
for (int i=0;i<nrfields;i++){
TableItem item = wFields.getNonEmpty(i);
if (YES_NO_COMBO[1].equalsIgnoreCase(item.getText(6))) {
bInputOK = false;
}
}
if (!bInputOK) {
MessageBox mb = new MessageBox(shell, SWT.OK | SWT.CANCEL | SWT.ICON_ERROR );
mb.setMessage(BaseMessages.getString(PKG, "ScriptValuesDialogMod.ReplaceNotAllowedInCompatibilityMode")); //$NON-NLS-1$
mb.setText(BaseMessages.getString(PKG, "ScriptValuesDialogMod.ERROR.Label")); //$NON-NLS-1$
mb.open();
}
}
if(bInputOK){
getInfo(input);
dispose();
}
}
public boolean test()
{
return test(false, false);
}
private boolean newTest() {
PluginRegistry registry = PluginRegistry.getInstance();
String scriptStepName = wStepname.getText();
try{
// What fields are coming into the step?
//
RowMetaInterface rowMeta = transMeta.getPrevStepFields(stepname).clone();
if (rowMeta!=null){
// Create a new RowGenerator step to generate rows for the test data...
// Only create a new instance the first time to help the user.
// Otherwise he/she has to key in the same test data all the time
//
if (genMeta==null) {
genMeta = new RowGeneratorMeta();
genMeta.setRowLimit("10");
genMeta.allocate(rowMeta.size());
for (int i=0;i<rowMeta.size();i++)
{
ValueMetaInterface valueMeta = rowMeta.getValueMeta(i);
if (valueMeta.isStorageBinaryString()) {
valueMeta.setStorageType(ValueMetaInterface.STORAGE_TYPE_NORMAL);
}
genMeta.getFieldName()[i] = valueMeta.getName();
genMeta.getFieldType()[i] = valueMeta.getTypeDesc();
genMeta.getFieldLength()[i] = valueMeta.getLength();
genMeta.getFieldPrecision()[i] = valueMeta.getPrecision();
genMeta.getCurrency()[i] = valueMeta.getCurrencySymbol();
genMeta.getDecimal()[i] = valueMeta.getDecimalSymbol();
genMeta.getGroup()[i] = valueMeta.getGroupingSymbol();
String string=null;
switch(valueMeta.getType()) {
case ValueMetaInterface.TYPE_DATE :
genMeta.getFieldFormat()[i] = "yyyy/MM/dd HH:mm:ss";
valueMeta.setConversionMask(genMeta.getFieldFormat()[i]);
string = valueMeta.getString(new Date());
break;
case ValueMetaInterface.TYPE_STRING :
string = "test value test value"; //$NON-NLS-1$
break;
case ValueMetaInterface.TYPE_INTEGER :
genMeta.getFieldFormat()[i] = "#";
valueMeta.setConversionMask(genMeta.getFieldFormat()[i]);
string = valueMeta.getString(Long.valueOf(0L));
break;
case ValueMetaInterface.TYPE_NUMBER :
genMeta.getFieldFormat()[i] = "#.#";
valueMeta.setConversionMask(genMeta.getFieldFormat()[i]);
string = valueMeta.getString(Double.valueOf(0.0D));
break;
case ValueMetaInterface.TYPE_BIGNUMBER :
genMeta.getFieldFormat()[i] = "#.#";
valueMeta.setConversionMask(genMeta.getFieldFormat()[i]);
string = valueMeta.getString(BigDecimal.ZERO);
break;
case ValueMetaInterface.TYPE_BOOLEAN :
string = valueMeta.getString(Boolean.TRUE);
break;
case ValueMetaInterface.TYPE_BINARY :
string = valueMeta.getString(new byte[] { 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, });
break;
default:
break;
}
genMeta.getValue()[i] = string;
}
}
StepMeta genStep = new StepMeta(registry.getPluginId(StepPluginType.class, genMeta), "## TEST DATA ##", genMeta);
genStep.setLocation(50, 50);
// Now create a JavaScript step with the information in this dialog
//
ScriptValuesMetaMod scriptMeta = new ScriptValuesMetaMod();
getInfo(scriptMeta);
StepMeta scriptStep = new StepMeta(registry.getPluginId(StepPluginType.class, scriptMeta), Const.NVL(scriptStepName, "## SCRIPT ##"), scriptMeta);
scriptStepName = scriptStep.getName();
scriptStep.setLocation(150, 50);
// Create a hop between both steps...
//
TransHopMeta hop = new TransHopMeta(genStep, scriptStep);
// Generate a new test transformation...
//
TransMeta transMeta = new TransMeta();
transMeta.setName(wStepname.getText()+" - PREVIEW"); // $NON-NLS-1$
transMeta.addStep(genStep);
transMeta.addStep(scriptStep);
transMeta.addTransHop(hop);
// OK, now we ask the user to edit this dialog...
//
if (Spoon.getInstance().editStep(transMeta, genStep)!=null) {
// Now run this transformation and grab the results...
//
TransPreviewProgressDialog progressDialog = new TransPreviewProgressDialog(
shell,
transMeta,
new String[] { scriptStepName, },
new int[] { Const.toInt(genMeta.getRowLimit(), 10), }
);
progressDialog.open();
Trans trans = progressDialog.getTrans();
String loggingText = progressDialog.getLoggingText();
if (!progressDialog.isCancelled())
{
if (trans.getResult()!=null && trans.getResult().getNrErrors()>0)
{
EnterTextDialog etd = new EnterTextDialog(shell, BaseMessages.getString(PKG, "System.Dialog.PreviewError.Title"),
BaseMessages.getString(PKG, "System.Dialog.PreviewError.Message"), loggingText, true );
etd.setReadOnly();
etd.open();
}
}
RowMetaInterface previewRowsMeta = progressDialog.getPreviewRowsMeta(wStepname.getText());
List<Object[]> previewRows = progressDialog.getPreviewRows(wStepname.getText());
if (previewRowsMeta!=null && previewRows!=null && previewRows.size()>0) {
PreviewRowsDialog prd = new PreviewRowsDialog(shell,
transMeta, SWT.NONE, wStepname.getText(),
previewRowsMeta,
previewRows,
loggingText);
prd.open();
}
}
return true;
} else {
throw new KettleException(BaseMessages.getString(PKG, "ScriptValuesDialogMod.Exception.CouldNotGetFields")); //$NON-NLS-1$
}
}
catch(Exception e) {
new ErrorDialog(shell, BaseMessages.getString(PKG, "ScriptValuesDialogMod.TestFailed.DialogTitle"), BaseMessages.getString(PKG, "ScriptValuesDialogMod.TestFailed.DialogMessage"), e); //$NON-NLS-1$ //$NON-NLS-2$
return false;
}
}
private boolean test(boolean getvars, boolean popup)
{
boolean retval=true;
StyledTextComp wScript = getStyledTextComp();
String scr = wScript.getText();
KettleException testException = null;
Context jscx;
Scriptable jsscope;
// Script jsscript;
// Making Refresh to get Active Script State
refreshScripts();
jscx = ContextFactory.getGlobal().enterContext();
jscx.setOptimizationLevel(-1);
jsscope = jscx.initStandardObjects(null, false);
// Adding the existing Scripts to the Context
for(int i=0;i<folder.getItemCount();i++){
StyledTextComp sItem = getStyledTextComp(folder.getItem(i));
Scriptable jsR = Context.toObject(sItem.getText(), jsscope);
jsscope.put(folder.getItem(i).getText(), jsscope, jsR); //$NON-NLS-1$
}
// Adding the Name of the Transformation to the Context
jsscope.put("_TransformationName_", jsscope, this.stepname);
try{
RowMetaInterface rowMeta = transMeta.getPrevStepFields(stepname);
if (rowMeta!=null){
ScriptValuesModDummy dummyStep = new ScriptValuesModDummy(rowMeta, transMeta.getStepFields(stepname));
Scriptable jsvalue = Context.toObject(dummyStep, jsscope);
jsscope.put("_step_", jsscope, jsvalue); //$NON-NLS-1$
// Modification for Additional Script parsing
try{
if (input.getAddClasses()!=null)
{
for(int i=0;i<input.getAddClasses().length;i++){
Object jsOut = Context.javaToJS(input.getAddClasses()[i].getAddObject(), jsscope);
ScriptableObject.putProperty(jsscope, input.getAddClasses()[i].getJSName(), jsOut);
}
}
}catch(Exception e){
testException = new KettleException(BaseMessages.getString(PKG, "ScriptValuesDialogMod.CouldNotAddToContext",e.toString())); //$NON-NLS-1$
retval = false;
}
// Adding some default JavaScriptFunctions to the System
try {
Context.javaToJS(ScriptValuesAddedFunctions.class, jsscope);
((ScriptableObject)jsscope).defineFunctionProperties(jsFunctionList, ScriptValuesAddedFunctions.class, ScriptableObject.DONTENUM);
} catch (Exception ex) {
testException = new KettleException(BaseMessages.getString(PKG, "ScriptValuesDialogMod.CouldNotAddDefaultFunctions", ex.toString())); //$NON-NLS-1$
retval = false;
};
// Adding some Constants to the JavaScript
try {
jsscope.put("SKIP_TRANSFORMATION", jsscope, Integer.valueOf(SKIP_TRANSFORMATION));
jsscope.put("ABORT_TRANSFORMATION", jsscope, Integer.valueOf(ABORT_TRANSFORMATION));
jsscope.put("ERROR_TRANSFORMATION", jsscope, Integer.valueOf(ERROR_TRANSFORMATION));
jsscope.put("CONTINUE_TRANSFORMATION", jsscope, Integer.valueOf(CONTINUE_TRANSFORMATION));
} catch (Exception ex) {
testException = new KettleException(BaseMessages.getString(PKG, "ScriptValuesDialogMod.CouldNotAddTransformationConstants",ex.toString())); //$NON-NLS-1$
retval = false;
};
try{
Object[] row=new Object[rowMeta.size()];
Scriptable jsRowMeta = Context.toObject(rowMeta, jsscope);
jsscope.put("rowMeta", jsscope, jsRowMeta); //$NON-NLS-1$
for (int i=0;i<rowMeta.size();i++)
{
ValueMetaInterface valueMeta = rowMeta.getValueMeta(i);
Object valueData = null;
// Set date and string values to something to simulate real thing
//
if (valueMeta.isDate()) valueData = new Date();
if (valueMeta.isString()) valueData = "test value test value test value test value test value test value test value test value test value test value"; //$NON-NLS-1$
if (valueMeta.isInteger()) valueData = Long.valueOf(0L);
if (valueMeta.isNumber()) valueData = new Double(0.0);
if (valueMeta.isBigNumber()) valueData = BigDecimal.ZERO;
if (valueMeta.isBoolean()) valueData = Boolean.TRUE;
if (valueMeta.isBinary()) valueData = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, };
if (valueMeta.isStorageBinaryString()) {
valueMeta.setStorageType(ValueMetaInterface.STORAGE_TYPE_NORMAL);
}
row[i]=valueData;
if (wCompatible.getSelection()) {
Value value = valueMeta.createOriginalValue(valueData);
Scriptable jsarg = Context.toObject(value, jsscope);
jsscope.put(valueMeta.getName(), jsscope, jsarg);
}
else {
Scriptable jsarg = Context.toObject(valueData, jsscope);
jsscope.put(valueMeta.getName(), jsscope, jsarg);
}
}
// OK, for these input values, we're going to allow the user to edit the default values...
// We are displaying a
// 2)
// Add support for Value class (new Value())
Scriptable jsval = Context.toObject(Value.class, jsscope);
jsscope.put("Value", jsscope, jsval); //$NON-NLS-1$
// Add the old style row object for compatibility reasons...
//
if (wCompatible.getSelection()) {
Row v2Row = RowMeta.createOriginalRow(rowMeta, row);
Scriptable jsV2Row = Context.toObject(v2Row, jsscope);
jsscope.put("row", jsscope, jsV2Row); //$NON-NLS-1$
}
else {
Scriptable jsRow = Context.toObject(row, jsscope);
jsscope.put("row", jsscope, jsRow); //$NON-NLS-1$
}
}catch(Exception ev){
testException = new KettleException(BaseMessages.getString(PKG, "ScriptValuesDialogMod.CouldNotAddInputFields", ev.toString())); //$NON-NLS-1$
retval = false;
}
try{
// Checking for StartScript
if(strActiveStartScript != null && !folder.getSelection().getText().equals(strActiveStartScript) && strActiveStartScript.length()>0){
String strStartScript = getStyledTextComp(folder.getItem(getCTabPosition(strActiveStartScript))).getText();
/* Object startScript = */ jscx.evaluateString(jsscope, strStartScript, "trans_Start", 1, null);
}
}catch(Exception e){
testException = new KettleException(BaseMessages.getString(PKG, "ScriptValuesDialogMod.CouldProcessStartScript",e.toString())); //$NON-NLS-1$
retval = false;
};
try {
Script evalScript = jscx.compileString(scr, "script", 1, null);
evalScript.exec(jscx, jsscope);
//Object tranScript = jscx.evaluateString(jsscope, scr, "script", 1, null);
if (getvars){
ScriptOrFnNode tree = parseVariables(jscx, jsscope, scr, "script", 1, null);
for (int i=0;i<tree.getParamAndVarCount();i++){
String varname = tree.getParamOrVarName(i);
if (!varname.equalsIgnoreCase("row") && !varname.equalsIgnoreCase("trans_Status")){
int type=ValueMetaInterface.TYPE_STRING;
int length=-1, precision=-1;
Object result = jsscope.get(varname, jsscope);
if (result!=null){
String classname = result.getClass().getName();
if (classname.equalsIgnoreCase("java.lang.Byte")){
// MAX = 127
type=ValueMetaInterface.TYPE_INTEGER;
length=3;
precision=0;
}else if (classname.equalsIgnoreCase("java.lang.Integer")){
// MAX = 2147483647
type=ValueMetaInterface.TYPE_INTEGER;
length=9;
precision=0;
}else if (classname.equalsIgnoreCase("java.lang.Long")){
// MAX = 9223372036854775807
type=ValueMetaInterface.TYPE_INTEGER;
length=18;
precision=0;
}else if (classname.equalsIgnoreCase("java.lang.Double")){
type=ValueMetaInterface.TYPE_NUMBER;
length=16;
precision=2;
}else if (classname.equalsIgnoreCase("org.mozilla.javascript.NativeDate") || classname.equalsIgnoreCase("java.util.Date")){
type=ValueMetaInterface.TYPE_DATE;
}else if (classname.equalsIgnoreCase("java.lang.Boolean")){
type=ValueMetaInterface.TYPE_BOOLEAN;
}
}
TableItem ti = new TableItem(wFields.table, SWT.NONE);
ti.setText(1, varname);
ti.setText(2, "");
ti.setText(3, ValueMeta.getTypeDesc(type));
ti.setText(4, length>=0 ? ( ""+length) : "" ); //$NON-NLS-1$
ti.setText(5, precision>=0 ? (""+precision ) : ""); //$NON-NLS-1$
// If the variable name exists in the input, suggest to replace the value
//
ti.setText(6, (rowMeta.indexOfValue(varname)>=0) ? YES_NO_COMBO[1] : YES_NO_COMBO[0]);
}
}
wFields.removeEmptyRows();
wFields.setRowNums();
wFields.optWidth(true);
}
// End Script!
}
catch(EvaluatorException e){
String position = "("+e.lineNumber()+":"+e.columnNumber()+")"; // $NON-NLS-1$ $NON-NLS-2$ $NON-NLS-3$
String message = BaseMessages.getString(PKG, "ScriptValuesDialogMod.Exception.CouldNotExecuteScript", position); //$NON-NLS-1$
testException = new KettleException(message, e);
retval=false;
}
catch(JavaScriptException e){
String position = "("+e.lineNumber()+":"+e.columnNumber()+")"; // $NON-NLS-1$ $NON-NLS-2$ $NON-NLS-3$
String message = BaseMessages.getString(PKG, "ScriptValuesDialogMod.Exception.CouldNotExecuteScript", position); //$NON-NLS-1$
testException = new KettleException(message, e);
retval=false;
}
catch(Exception e){
testException = new KettleException(BaseMessages.getString(PKG, "ScriptValuesDialogMod.Exception.CouldNotExecuteScript2"), e); //$NON-NLS-1$
retval=false;
}
}else{
testException = new KettleException(BaseMessages.getString(PKG, "ScriptValuesDialogMod.Exception.CouldNotGetFields")); //$NON-NLS-1$
retval=false;
}
if (popup){
if (retval){
if (!getvars){
MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_INFORMATION );
mb.setMessage(BaseMessages.getString(PKG, "ScriptValuesDialogMod.ScriptCompilationOK")+Const.CR); //$NON-NLS-1$
mb.setText("OK"); //$NON-NLS-1$
mb.open();
}
}else{
new ErrorDialog(shell, BaseMessages.getString(PKG, "ScriptValuesDialogMod.TestFailed.DialogTitle"), BaseMessages.getString(PKG, "ScriptValuesDialogMod.TestFailed.DialogMessage"), testException); //$NON-NLS-1$ //$NON-NLS-2$
}
}
}catch(KettleException ke){
retval=false;
new ErrorDialog(shell, BaseMessages.getString(PKG, "ScriptValuesDialogMod.TestFailed.DialogTitle"), BaseMessages.getString(PKG, "ScriptValuesDialogMod.TestFailed.DialogMessage"), ke); //$NON-NLS-1$ //$NON-NLS-2$
}finally{
if (jscx!=null) Context.exit();
}
return retval;
}
private void buildSpecialFunctionsTree(){
TreeItem item = new TreeItem(wTree, SWT.NULL);
item.setImage(guiresource.getImageBol());
item.setText(BaseMessages.getString(PKG, "ScriptValuesDialogMod.TansformConstant.Label"));
TreeItem itemT = new TreeItem(item, SWT.NULL);
itemT.setImage(imageArrowGreen);
itemT.setText("SKIP_TRANSFORMATION");
itemT.setData("SKIP_TRANSFORMATION");
//itemT = new TreeItem(item, SWT.NULL);
//itemT.setText("ABORT_TRANSFORMATION");
//itemT.setData("ABORT_TRANSFORMATION");
itemT = new TreeItem(item, SWT.NULL);
itemT.setImage(imageArrowGreen);
itemT.setText("ERROR_TRANSFORMATION");
itemT.setData("ERROR_TRANSFORMATION");
itemT = new TreeItem(item, SWT.NULL);
itemT.setImage(imageArrowGreen);
itemT.setText("CONTINUE_TRANSFORMATION");
itemT.setData("CONTINUE_TRANSFORMATION");
item = new TreeItem(wTree, SWT.NULL);
item.setImage(guiresource.getImageBol());
item.setText(BaseMessages.getString(PKG, "ScriptValuesDialogMod.TransformFunctions.Label"));
String strData = "";
// Adding the Grouping Items to the Tree
TreeItem itemStringFunctionsGroup = new TreeItem(item, SWT.NULL);
itemStringFunctionsGroup.setImage(imageUnderGreen);
itemStringFunctionsGroup.setText(BaseMessages.getString(PKG, "ScriptValuesDialogMod.StringFunctions.Label"));
itemStringFunctionsGroup.setData("Function");
TreeItem itemNumericFunctionsGroup = new TreeItem(item, SWT.NULL);
itemNumericFunctionsGroup.setImage(imageUnderGreen);
itemNumericFunctionsGroup.setText(BaseMessages.getString(PKG, "ScriptValuesDialogMod.NumericFunctions.Label"));
itemNumericFunctionsGroup.setData("Function");
TreeItem itemDateFunctionsGroup = new TreeItem(item, SWT.NULL);
itemDateFunctionsGroup.setImage(imageUnderGreen);
itemDateFunctionsGroup.setText(BaseMessages.getString(PKG, "ScriptValuesDialogMod.DateFunctions.Label"));
itemDateFunctionsGroup.setData("Function");
TreeItem itemLogicFunctionsGroup = new TreeItem(item, SWT.NULL);
itemLogicFunctionsGroup.setImage(imageUnderGreen);
itemLogicFunctionsGroup.setText(BaseMessages.getString(PKG, "ScriptValuesDialogMod.LogicFunctions.Label"));
itemLogicFunctionsGroup.setData("Function");
TreeItem itemSpecialFunctionsGroup = new TreeItem(item, SWT.NULL);
itemSpecialFunctionsGroup.setImage(imageUnderGreen);
itemSpecialFunctionsGroup.setText(BaseMessages.getString(PKG, "ScriptValuesDialogMod.SpecialFunctions.Label"));
itemSpecialFunctionsGroup.setData("Function");
TreeItem itemFileFunctionsGroup = new TreeItem(item, SWT.NULL);
itemFileFunctionsGroup.setImage(imageUnderGreen);
itemFileFunctionsGroup.setText(BaseMessages.getString(PKG, "ScriptValuesDialogMod.FileFunctions.Label"));
itemFileFunctionsGroup.setData("Function");
// Loading the Default delivered JScript Functions
//Method[] methods = ScriptValuesAddedFunctions.class.getMethods();
//String strClassType = ScriptValuesAddedFunctions.class.toString();
Hashtable<String, String> hatFunctions =scVHelp.getFunctionList();
Vector<String> v = new Vector<String>(hatFunctions.keySet());
Collections.sort(v);
for (String strFunction : v) {
String strFunctionType =(String)hatFunctions.get(strFunction);
int iFunctionType = Integer.valueOf(strFunctionType).intValue();
TreeItem itemFunction=null;
switch(iFunctionType){
case ScriptValuesAddedFunctions.STRING_FUNCTION: itemFunction = new TreeItem(itemStringFunctionsGroup,SWT.NULL); break;
case ScriptValuesAddedFunctions.NUMERIC_FUNCTION:itemFunction = new TreeItem(itemNumericFunctionsGroup,SWT.NULL); break;
case ScriptValuesAddedFunctions.DATE_FUNCTION:itemFunction = new TreeItem(itemDateFunctionsGroup,SWT.NULL); break;
case ScriptValuesAddedFunctions.LOGIC_FUNCTION:itemFunction = new TreeItem(itemLogicFunctionsGroup,SWT.NULL); break;
case ScriptValuesAddedFunctions.SPECIAL_FUNCTION:itemFunction = new TreeItem(itemSpecialFunctionsGroup,SWT.NULL); break;
case ScriptValuesAddedFunctions.FILE_FUNCTION:itemFunction = new TreeItem(itemFileFunctionsGroup,SWT.NULL); break;
}
if(itemFunction !=null){
itemFunction.setText(strFunction);
itemFunction.setImage(imageArrowGreen);
strData = "jsFunction";
itemFunction.setData(strData);
}
}
}
public boolean TreeItemExist(TreeItem itemToCheck, String strItemName){
boolean bRC=false;
if(itemToCheck.getItemCount()>0){
TreeItem[] items = itemToCheck.getItems();
for(int i=0;i<items.length;i++){
if(items[i].getText().equals(strItemName)) return true;
}
}
return bRC;
}
private void setInputOutputFields(){
shell.getDisplay().syncExec(new Runnable()
{
public void run()
{
// fields are got...end of wait message
iteminput.removeAll();
itemoutput.removeAll();
String strItemInToAdd="";
String strItemToAddOut="";
//try{
//RowMetaInterface r = transMeta.getPrevStepFields(stepname);
if (rowPrevStepFields!=null){
//TreeItem item = new TreeItem(wTree, SWT.NULL);
//item.setText(BaseMessages.getString(PKG, "ScriptValuesDialogMod.OutputFields.Label"));
//String strItemToAdd="";
for (int i=0;i<rowPrevStepFields.size();i++){
ValueMetaInterface v = rowPrevStepFields.getValueMeta(i);
strItemToAddOut=v.getName()+".setValue(var)";
if (wCompatible.getSelection()) {
switch(v.getType()){
case ValueMetaInterface.TYPE_STRING : strItemInToAdd=v.getName()+".getString()"; break; //$NON-NLS-1$
case ValueMetaInterface.TYPE_NUMBER : strItemInToAdd=v.getName()+".getNumber()"; break; //$NON-NLS-1$
case ValueMetaInterface.TYPE_INTEGER: strItemInToAdd=v.getName()+".getInteger()"; break; //$NON-NLS-1$
case ValueMetaInterface.TYPE_DATE : strItemInToAdd=v.getName()+".getDate()"; break; //$NON-NLS-1$
case ValueMetaInterface.TYPE_BOOLEAN:
strItemInToAdd=v.getName()+".getBoolean()";
strItemToAddOut=v.getName()+".setValue(var)";
break; //$NON-NLS-1$
case ValueMetaInterface.TYPE_BIGNUMBER: strItemInToAdd=v.getName()+".getBigNumber()"; break; //$NON-NLS-1$
case ValueMetaInterface.TYPE_BINARY: strItemInToAdd=v.getName()+".getBytes()"; break; //$NON-NLS-1$
case ValueMetaInterface.TYPE_SERIALIZABLE: strItemInToAdd=v.getName()+".getSerializable()"; break; //$NON-NLS-1$
default:
strItemInToAdd=v.getName();
strItemToAddOut=v.getName();
break;
}
}
else {
strItemInToAdd=v.getName();
}
TreeItem itemFields = new TreeItem(iteminput, SWT.NULL);
itemFields.setImage(imageArrowOrange);
itemFields.setText(strItemInToAdd);
itemFields.setData(strItemInToAdd);
/*
switch(v.getType()){
case ValueMetaInterface.TYPE_STRING :
case ValueMetaInterface.TYPE_NUMBER :
case ValueMetaInterface.TYPE_INTEGER:
case ValueMetaInterface.TYPE_DATE :
case ValueMetaInterface.TYPE_BOOLEAN:
strItemToAdd=v.getName()+".setValue(var)"; break; //$NON-NLS-1$
default: strItemToAdd=v.getName(); break;
}*/
itemFields = new TreeItem(itemoutput, SWT.NULL);
itemFields.setImage(imageArrowOrange);
itemFields.setText(strItemToAddOut);
itemFields.setData(strItemToAddOut);
}
}
/*}catch(KettleException ke){
new ErrorDialog(shell, BaseMessages.getString(PKG, "ScriptValuesDialogMod.FailedToGetFields.DialogTitle"), BaseMessages.getString(PKG, "ScriptValuesDialogMod.FailedToGetFields.DialogMessage"), ke); //$NON-NLS-1$ //$NON-NLS-2$
}*/
}
}
);
}
/*
private void rebuildInputFieldsTree(){
try{
String itemName = BaseMessages.getString(PKG, "ScriptValuesDialogMod.InputFields.Label");
RowMetaInterface r = transMeta.getPrevStepFields(stepname);
if (r!=null){
TreeItem item = null;
for (TreeItem look : wTree.getItems()) {
if (look.getText().equals(itemName)) {
// This is the rebuild part!
for (TreeItem child : look.getItems()) child.dispose(); // clear the children.
item=look;
break;
}
}
if (item==null) item = new TreeItem(wTree, SWT.NULL);
item.setText(itemName);
String strItemToAdd="";
for (int i=0;i<r.size();i++){
ValueMetaInterface v = r.getValueMeta(i);
if (wCompatible.getSelection()) {
switch(v.getType()){
case ValueMetaInterface.TYPE_STRING : strItemToAdd=v.getName()+".getString()"; break; //$NON-NLS-1$
case ValueMetaInterface.TYPE_NUMBER : strItemToAdd=v.getName()+".getNumber()"; break; //$NON-NLS-1$
case ValueMetaInterface.TYPE_INTEGER: strItemToAdd=v.getName()+".getInteger()"; break; //$NON-NLS-1$
case ValueMetaInterface.TYPE_DATE : strItemToAdd=v.getName()+".getDate()"; break; //$NON-NLS-1$
case ValueMetaInterface.TYPE_BOOLEAN: strItemToAdd=v.getName()+".getBoolean()"; break; //$NON-NLS-1$
case ValueMetaInterface.TYPE_BIGNUMBER: strItemToAdd=v.getName()+".getBigNumber()"; break; //$NON-NLS-1$
case ValueMetaInterface.TYPE_BINARY: strItemToAdd=v.getName()+".getBytes()"; break; //$NON-NLS-1$
case ValueMetaInterface.TYPE_SERIALIZABLE: strItemToAdd=v.getName()+".getSerializable()"; break; //$NON-NLS-1$
default: strItemToAdd=v.getName(); break;
}
}
else {
strItemToAdd=v.getName();
}
TreeItem itemInputFields = new TreeItem(item, SWT.NULL);
itemInputFields.setText(strItemToAdd);
itemInputFields.setData(strItemToAdd);
}
}
}catch(KettleException ke){
new ErrorDialog(shell, BaseMessages.getString(PKG, "ScriptValuesDialogMod.FailedToGetFields.DialogTitle"), BaseMessages.getString(PKG, "ScriptValuesDialogMod.FailedToGetFields.DialogMessage"), ke); //$NON-NLS-1$ //$NON-NLS-2$
}
}*/
// Adds the Current item to the current Position
private void treeDblClick(Event event){
StyledTextComp wScript = getStyledTextComp();
Point point = new Point(event.x, event.y);
TreeItem item = wTree.getItem(point);
// Qualifikation where the Click comes from
if(item !=null && item.getParentItem()!=null){
if(item.getParentItem().equals(wTreeScriptsItem)){
setActiveCtab(item.getText());
}else if(!item.getData().equals("Function")){
int iStart = wScript.getCaretOffset();
int selCount = wScript.getSelectionCount(); // this selection will be replaced by wScript.insert
iStart=iStart-selCount; //when a selection is already there we need to subtract the position
if (iStart<0) iStart=0; // just safety
String strInsert =(String)item.getData();
if(strInsert.equals("jsFunction")) strInsert = (String)item.getText();
wScript.insert(strInsert);
wScript.setSelection(iStart,iStart+strInsert.length());
}
}
/*
if (item != null && item.getParentItem()!=null && !item.getData().equals("Function")) {
int iStart = wScript.getCaretOffset();
String strInsert =(String)item.getData();
if(strInsert.equals("jsFunction")) strInsert = (String)item.getText();
wScript.insert(strInsert);
wScript.setSelection(iStart,iStart+strInsert.length());
}*/
}
// Building the Tree for Additional Classes
private void buildAddClassesListTree(){
if(wTreeClassesitem!=null){
wTreeClassesitem.dispose();
}
if (input.getAddClasses()!=null)
{
for(int i=0;i<input.getAddClasses().length;i++){
//System.out.println(input.getAddClasses().length);
try{
Method[] methods = input.getAddClasses()[i].getAddClass().getMethods();
String strClassType = input.getAddClasses()[i].getAddClass().toString();
String strParams;
wTreeClassesitem = new TreeItem(wTree, SWT.NULL);
wTreeClassesitem.setText(input.getAddClasses()[i].getJSName());
for (int j=0; j<methods.length; j++){
String strDeclaringClass = methods[j].getDeclaringClass().toString();
if(strClassType.equals(strDeclaringClass)){
TreeItem item2 = new TreeItem(wTreeClassesitem, SWT.NULL);
strParams = buildAddClassFunctionName(methods[j]);
item2.setText(methods[j].getName() + "("+ strParams +")");
String strData = input.getAddClasses()[i].getJSName() + "." +methods[j].getName() + "("+strParams+")";
item2.setData(strData);
}
}
}
catch(Exception e){
}
}
}
}
private String buildAddClassFunctionName(Method metForParams){
StringBuffer sbRC = new StringBuffer();
String strRC = "";
Class<?>[] clsParamType = metForParams.getParameterTypes();
String strParam;
for(int x=0;x<clsParamType.length;x++){
strParam = clsParamType[x].getName();
if(strParam.toLowerCase().indexOf("javascript")>0){
}else if(strParam.toLowerCase().indexOf("object")>0){
sbRC.append("var");
sbRC.append(", ");
}else if(strParam.equals("java.lang.String")){
sbRC.append("String");
sbRC.append(", ");
}else{
sbRC.append(strParam);
sbRC.append(", ");
}
}
strRC = sbRC.toString();
if(strRC.length()>0) strRC = strRC.substring(0,sbRC.length()-2);
return strRC;
}
private void buildingFolderMenu(){
//styledTextPopupmenu = new Menu(, SWT.POP_UP);
MenuItem addNewItem = new MenuItem(cMenu, SWT.PUSH);
addNewItem.setText(BaseMessages.getString(PKG, "ScriptValuesDialogMod.AddNewTab"));
addNewItem.setImage(imageAddScript);
addNewItem.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event e) {
addCtab("","", ADD_BLANK);
}
});
MenuItem copyItem = new MenuItem(cMenu, SWT.PUSH);
copyItem.setText(BaseMessages.getString(PKG, "ScriptValuesDialogMod.AddCopy"));
copyItem.setImage(imageDuplicateScript);
copyItem.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event e) {
CTabItem item = folder.getSelection();
StyledTextComp st = (StyledTextComp)item.getControl();
addCtab(item.getText(),st.getText(), ADD_COPY);
}
});
new MenuItem(cMenu, SWT.SEPARATOR);
MenuItem setActiveScriptItem = new MenuItem(cMenu, SWT.PUSH);
setActiveScriptItem.setText(BaseMessages.getString(PKG, "ScriptValuesDialogMod.SetTransformScript"));
setActiveScriptItem.setImage(imageActiveScript);
setActiveScriptItem.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event e) {
CTabItem item = folder.getSelection();
for(int i=0;i<folder.getItemCount();i++){
if(folder.getItem(i).equals(item)){
if(item.getImage().equals(imageActiveScript)) strActiveScript="";
else if(item.getImage().equals(imageActiveStartScript)) strActiveStartScript="";
else if(item.getImage().equals(imageActiveEndScript)) strActiveEndScript="";
item.setImage(imageActiveScript);
strActiveScript = item.getText();
}
else if(folder.getItem(i).getImage().equals(imageActiveScript)){
folder.getItem(i).setImage(imageInactiveScript);
}
}
modifyScriptTree(item, SET_ACTIVE_ITEM);
}
});
MenuItem setStartScriptItem = new MenuItem(cMenu, SWT.PUSH);
setStartScriptItem.setText(BaseMessages.getString(PKG, "ScriptValuesDialogMod.SetStartScript"));
setStartScriptItem.setImage(imageActiveStartScript);
setStartScriptItem.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event e) {
CTabItem item = folder.getSelection();
for(int i=0;i<folder.getItemCount();i++){
if(folder.getItem(i).equals(item)){
if(item.getImage().equals(imageActiveScript)) strActiveScript="";
else if(item.getImage().equals(imageActiveStartScript)) strActiveStartScript="";
else if(item.getImage().equals(imageActiveEndScript)) strActiveEndScript="";
item.setImage(imageActiveStartScript);
strActiveStartScript = item.getText();
}
else if(folder.getItem(i).getImage().equals(imageActiveStartScript)){
folder.getItem(i).setImage(imageInactiveScript);
}
}
modifyScriptTree(item, SET_ACTIVE_ITEM);
}
});
MenuItem setEndScriptItem = new MenuItem(cMenu, SWT.PUSH);
setEndScriptItem.setText(BaseMessages.getString(PKG, "ScriptValuesDialogMod.SetEndScript"));
setEndScriptItem.setImage(imageActiveEndScript);
setEndScriptItem.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event e) {
CTabItem item = folder.getSelection();
for(int i=0;i<folder.getItemCount();i++){
if(folder.getItem(i).equals(item)){
if(item.getImage().equals(imageActiveScript)) strActiveScript="";
else if(item.getImage().equals(imageActiveStartScript)) strActiveStartScript="";
else if(item.getImage().equals(imageActiveEndScript)) strActiveEndScript="";
item.setImage(imageActiveEndScript);
strActiveEndScript = item.getText();
}
else if(folder.getItem(i).getImage().equals(imageActiveEndScript)){
folder.getItem(i).setImage(imageInactiveScript);
}
}
modifyScriptTree(item, SET_ACTIVE_ITEM);
}
});
new MenuItem(cMenu, SWT.SEPARATOR);
MenuItem setRemoveScriptItem = new MenuItem(cMenu, SWT.PUSH);
setRemoveScriptItem.setText(BaseMessages.getString(PKG, "ScriptValuesDialogMod.RemoveScriptType"));
setRemoveScriptItem.setImage(imageInactiveScript);
setRemoveScriptItem.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event e) {
CTabItem item = folder.getSelection();
input.setChanged(true);
if(item.getImage().equals(imageActiveScript)) strActiveScript="";
else if(item.getImage().equals(imageActiveStartScript)) strActiveStartScript="";
else if(item.getImage().equals(imageActiveEndScript)) strActiveEndScript="";
item.setImage(imageInactiveScript);
}
});
folder.setMenu(cMenu);
}
private void buildingTreeMenu(){
//styledTextPopupmenu = new Menu(, SWT.POP_UP);
MenuItem addDeleteItem = new MenuItem(tMenu, SWT.PUSH);
addDeleteItem.setText(BaseMessages.getString(PKG, "ScriptValuesDialogMod.Delete.Label"));
addDeleteItem.setImage(imageDeleteScript);
addDeleteItem.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event e) {
if (wTree.getSelectionCount()<=0) return;
TreeItem tItem = wTree.getSelection()[0];
if(tItem!=null){
MessageBox messageBox = new MessageBox(shell, SWT.ICON_QUESTION | SWT.NO | SWT.YES);
messageBox.setText(BaseMessages.getString(PKG, "ScriptValuesDialogMod.DeleteItem.Label"));
messageBox.setMessage(BaseMessages.getString(PKG, "ScriptValuesDialogMod.ConfirmDeleteItem.Label",tItem.getText()));
switch(messageBox.open()){
case SWT.YES:
modifyCTabItem(tItem,DELETE_ITEM,"");
tItem.dispose();
input.setChanged();
break;
}
}
}
});
MenuItem renItem = new MenuItem(tMenu, SWT.PUSH);
renItem.setText(BaseMessages.getString(PKG, "ScriptValuesDialogMod.Rename.Label"));
renItem.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event e) {
renameFunction(wTree.getSelection()[0]);
}
});
new MenuItem(tMenu, SWT.SEPARATOR);
MenuItem helpItem = new MenuItem(tMenu, SWT.PUSH);
helpItem.setText(BaseMessages.getString(PKG, "ScriptValuesDialogMod.Sample.Label"));
helpItem.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event e) {
String strFunctionName = wTree.getSelection()[0].getText();
String strFunctionNameWithArgs = strFunctionName;
strFunctionName = strFunctionName.substring(0,strFunctionName.indexOf('('));
String strHelpTabName = strFunctionName + "_Sample";
if(getCTabPosition(strHelpTabName)==-1)
addCtab(strHelpTabName, scVHelp.getSample(strFunctionName,strFunctionNameWithArgs), 0);
if(getCTabPosition(strHelpTabName)!=-1)
setActiveCtab(strHelpTabName);
}
});
wTree.addListener(SWT.MouseDown, new Listener(){
public void handleEvent(Event e) {
if (wTree.getSelectionCount()<=0) return;
TreeItem tItem = wTree.getSelection()[0];
if(tItem != null){
TreeItem pItem = tItem.getParentItem();
if(pItem !=null && pItem.equals(wTreeScriptsItem)){
if(folder.getItemCount()>1) tMenu.getItem(0).setEnabled(true);
else tMenu.getItem(0).setEnabled(false);
tMenu.getItem(1).setEnabled(true);
tMenu.getItem(3).setEnabled(false);
}else if(tItem.equals(wTreeClassesitem)){
tMenu.getItem(0).setEnabled(false);
tMenu.getItem(1).setEnabled(false);
tMenu.getItem(3).setEnabled(false);
}else if(tItem.getData() != null && tItem.getData().equals("jsFunction")){
tMenu.getItem(0).setEnabled(false);
tMenu.getItem(1).setEnabled(false);
tMenu.getItem(3).setEnabled(true);
}else{
tMenu.getItem(0).setEnabled(false);
tMenu.getItem(1).setEnabled(false);
tMenu.getItem(3).setEnabled(false);
}
}
}
});
wTree.setMenu(tMenu);
}
private void addRenameTowTreeScriptItems(){
lastItem = new TreeItem [1];
editor = new TreeEditor (wTree);
wTree.addListener (SWT.Selection, new Listener () {
public void handleEvent (Event event) {
final TreeItem item = (TreeItem)event.item;
renameFunction(item);
}
});
}
// This function is for a Windows Like renaming inside the tree
private void renameFunction(TreeItem tItem){
final TreeItem item = tItem;
if(item.getParentItem()!=null && item.getParentItem().equals(wTreeScriptsItem)){
if (item != null && item == lastItem [0]) {
boolean isCarbon = SWT.getPlatform ().equals ("carbon");
final Composite composite = new Composite (wTree, SWT.NONE);
if (!isCarbon) composite.setBackground(shell.getDisplay().getSystemColor (SWT.COLOR_BLACK));
final Text text = new Text (composite, SWT.NONE);
final int inset = isCarbon ? 0 : 1;
composite.addListener (SWT.Resize, new Listener () {
public void handleEvent (Event e) {
Rectangle rect = composite.getClientArea ();
text.setBounds (rect.x + inset, rect.y + inset, rect.width - inset * 2, rect.height - inset * 2);
}
});
Listener textListener = new Listener () {
public void handleEvent (final Event e) {
switch (e.type) {
case SWT.FocusOut:
if(text.getText().length()>0){
// Check if the name Exists
if(getCTabItemByName(text.getText())==null){
modifyCTabItem(item,RENAME_ITEM, text.getText());
item.setText (text.getText ());
}
}
composite.dispose ();
break;
case SWT.Verify:
String newText = text.getText ();
String leftText = newText.substring (0, e.start);
String rightText = newText.substring (e.end, newText.length ());
GC gc = new GC (text);
Point size = gc.textExtent (leftText + e.text + rightText);
gc.dispose ();
size = text.computeSize (size.x, SWT.DEFAULT);
editor.horizontalAlignment = SWT.LEFT;
Rectangle itemRect = item.getBounds (), rect = wTree.getClientArea ();
editor.minimumWidth = Math.max (size.x, itemRect.width) + inset * 2;
int left = itemRect.x, right = rect.x + rect.width;
editor.minimumWidth = Math.min (editor.minimumWidth, right - left);
editor.minimumHeight = size.y + inset * 2;
editor.layout ();
break;
case SWT.Traverse:
switch (e.detail) {
case SWT.TRAVERSE_RETURN:
if(text.getText().length()>0){
// Check if the name Exists
if(getCTabItemByName(text.getText())==null){
modifyCTabItem(item,RENAME_ITEM, text.getText());
item.setText (text.getText ());
}
}
case SWT.TRAVERSE_ESCAPE:
composite.dispose ();
e.doit = false;
}
break;
}
}
};
text.addListener (SWT.FocusOut, textListener);
text.addListener (SWT.Traverse, textListener);
text.addListener (SWT.Verify, textListener);
editor.setEditor (composite, item);
text.setText (item.getText ());
text.selectAll ();
text.setFocus ();
}
}
lastItem [0] = item;
}
// This could be useful for further improvements
public static ScriptOrFnNode parseVariables(Context cx, Scriptable scope, String source, String sourceName, int lineno, Object securityDomain){
// Interpreter compiler = new Interpreter();
CompilerEnvirons evn = new CompilerEnvirons();
//evn.setLanguageVersion(Context.VERSION_1_5);
evn.setOptimizationLevel(-1);
evn.setGeneratingSource(true);
evn.setGenerateDebugInfo(true);
ErrorReporter errorReporter = new ToolErrorReporter(false);
Parser p = new Parser(evn, errorReporter);
ScriptOrFnNode tree = p.parse(source, "",0); // IOException
new NodeTransformer().transform(tree);
//Script result = (Script)compiler.compile(scope, evn, tree, p.getEncodedSource(),false, null);
return tree;
}
} | soluvas/pdi-ce | src-ui/org/pentaho/di/ui/trans/steps/scriptvalues_mod/ScriptValuesModDialog.java | Java | apache-2.0 | 81,863 |
/**
* OLAT - Online Learning and Training<br>
* http://www.olat.org
* <p>
* Licensed under the Apache License, Version 2.0 (the "License"); <br>
* you may not use this file except in compliance with the License.<br>
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing,<br>
* software distributed under the License is distributed on an "AS IS" BASIS, <br>
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <br>
* See the License for the specific language governing permissions and <br>
* limitations under the License.
* <p>
* Copyright (c) 1999-2006 at Multimedia- & E-Learning Services (MELS),<br>
* University of Zurich, Switzerland.
* <p>
*/
package org.olat.data.commons.database;
import java.util.List;
import org.hibernate.stat.Statistics;
import org.hibernate.type.Type;
/**
* @deprecated
*/
public interface DB {
/**
* Add an ITransactionListener to this DB instance.
* <p>
* The ITransactionListener will be informed about commit and rollbacks.
* <p>
* Adding the same listener twice has no effect.
* <p>
*
* @param listener
* the listener to be added
*/
public void addTransactionListener(ITransactionListener listener);
/**
* Removes an ITransactionListener from this DB instance.
* <p>
* If the ITransactionListener is currently not registered, this call has no effect.
*
* @param listener
*/
public void removeTransactionListener(ITransactionListener listener);
/**
* Close the database session.
*/
public void closeSession();
/**
* Close the database session, clean threadlocal but only if necessary
*/
public void cleanUpSession();
/**
* Create a DBQuery
*
* @param query
* @return DBQuery
*/
public DBQuery createQuery(String query);
/**
* Delete an object.
*
* @param object
*/
public void deleteObject(Object object);
/**
* Find objects based on query
*
* @param query
* @param value
* @param type
* @return List of results.
*/
public List find(String query, Object value, Type type);
/**
* Find objects based on query
*
* @param query
* @param values
* @param types
* @return List of results.
*/
public List find(String query, Object[] values, Type[] types);
/**
* Find an object.
*
* @param theClass
* @param key
* @return Object, if any found. or null otherwise
*/
public Object findObject(Class theClass, Long key);
/**
* Find objects based on query
*
* @param query
* @return List of results.
*/
public List find(String query);
/**
* Load an object.
*
* @param theClass
* @param key
* @return Object.
*/
public Object loadObject(Class theClass, Long key);
/**
* Save an object.
*
* @param object
*/
public void saveObject(Object object);
/**
* Update an object.
*
* @param object
*/
public void updateObject(Object object);
/**
* Deletion query.
*
* @param query
* @param value
* @param type
* @return nr of values deleted
*/
public abstract int delete(String query, Object value, Type type);
/**
* Deletion query.
*
* @param query
* @param values
* @param types
* @return nr of deleted rows
*/
public int delete(String query, Object[] values, Type[] types);
/**
* see DB.loadObject(Persistable persistable, boolean forceReloadFromDB)
*
* @param persistable
* @return the loaded object, never null
*/
public Persistable loadObject(Persistable persistable);
/**
* loads an object if needed. this makes sense if you have an object which had been generated in a previous hibernate session AND you need to access a Set or a
* attribute which was defined as a proxy.
*
* @param persistable
* the object which needs to be reloaded
* @param forceReloadFromDB
* if true, force a reload from the db (e.g. to catch up to an object commited by another thread which is still in this thread's session cache
* @return the loaded Object, never null
*/
public Persistable loadObject(Persistable persistable, boolean forceReloadFromDB);
/**
* Checks if the transaction needs to be committed and does so if this is the case, plus closes the connection in any case guaranteed.
* <p>
* Use this rather than commit() directly wherever possible!
*/
public void commitAndCloseSession();
/**
* Call this to commit current changes.
*/
public void commit();
/**
* Calls rollback and closes the connection guaranteed.
* <p>
* Note that this method checks whether the connection and the transaction are open and if they're not, then this method doesn't do anything.
*/
public void rollbackAndCloseSession();
/**
* Call this to rollback current changes.
*/
public void rollback();
/**
* Statistics must be enabled first, when you want to use it.
*
* @return Return Hibernates statistics object.
*/
public Statistics getStatistics();
/**
* Call this to intermediate commit current changes. Use this method in startup process and bulk changes.
*/
public void intermediateCommit();
/**
* @return True if any errors occured in the previous DB call.
*/
public boolean isError();
}
| huihoo/olat | olat7.8/src/main/java/org/olat/data/commons/database/DB.java | Java | apache-2.0 | 5,772 |
package org.jboss.resteasy.util;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import org.jboss.resteasy.resteasy_jaxrs.i18n.Messages;
/**
* This class is a trick used to extract GenericType information at runtime. Java does not allow you get generic
* type information easily, so this class does the trick. For example:
* <p/>
* <pre>
* Type genericType = (new GenericType<List<String>>() {}).getGenericType();
* </pre>
* <p/>
* The above code will get you the genericType for List<String>
*
* N.B. This class is replaced by javax.ws.rs.core.GenericType.
*
* @author <a href="mailto:[email protected]">Bill Burke</a>
* @version $Revision: 1 $
*
* @deprecated Replaced by javax.ws.rs.core.GenericType
*
* @see javax.ws.rs.core.GenericType
*/
@Deprecated
public class GenericType<T>
{
final Class<T> type;
final Type genericType;
/**
* Constructs a new generic entity. Derives represented class from type
* parameter. Note that this constructor is protected, users should create
* a (usually anonymous) subclass as shown above.
*
* @param entity the entity instance, must not be null
* @throws IllegalArgumentException if entity is null
*/
protected GenericType()
{
Type superclass = getClass().getGenericSuperclass();
if (!(superclass instanceof ParameterizedType))
{
throw new RuntimeException(Messages.MESSAGES.missingTypeParameter());
}
ParameterizedType parameterized = (ParameterizedType) superclass;
this.genericType = parameterized.getActualTypeArguments()[0];
this.type = (Class<T>) Types.getRawType(genericType);
}
/**
* Gets the raw type of the enclosed entity. Note that this is the raw type of
* the instance, not the raw type of the type parameter. I.e. in the example
* in the introduction, the raw type is {@code ArrayList} not {@code List}.
*
* @return the raw type
*/
public final Class<T> getType()
{
return type;
}
/**
* Gets underlying {@code Type} instance. Note that this is derived from the
* type parameter, not the enclosed instance. I.e. in the example
* in the introduction, the type is {@code List<String>} not
* {@code ArrayList<String>}.
*
* @return the type
*/
public final Type getGenericType()
{
return genericType;
}
} | psakar/Resteasy | resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/GenericType.java | Java | apache-2.0 | 2,400 |
/*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hbase.util;
import static org.junit.Assert.fail;
import java.security.Key;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.io.crypto.Cipher;
import org.apache.hadoop.hbase.io.crypto.CipherProvider;
import org.apache.hadoop.hbase.io.crypto.DefaultCipherProvider;
import org.apache.hadoop.hbase.io.crypto.KeyProvider;
import org.apache.hadoop.hbase.io.crypto.KeyProviderForTesting;
import org.apache.hadoop.hbase.testclassification.SmallTests;
import org.junit.Test;
import org.junit.experimental.categories.Category;
@Category(SmallTests.class)
public class TestEncryptionTest {
@Test
public void testTestKeyProvider() {
Configuration conf = HBaseConfiguration.create();
try {
conf.set(HConstants.CRYPTO_KEYPROVIDER_CONF_KEY, KeyProviderForTesting.class.getName());
EncryptionTest.testKeyProvider(conf);
} catch (Exception e) {
fail("Instantiation of test key provider should have passed");
}
try {
conf.set(HConstants.CRYPTO_KEYPROVIDER_CONF_KEY, FailingKeyProvider.class.getName());
EncryptionTest.testKeyProvider(conf);
fail("Instantiation of bad test key provider should have failed check");
} catch (Exception e) { }
}
@Test
public void testTestCipherProvider() {
Configuration conf = HBaseConfiguration.create();
try {
conf.set(HConstants.CRYPTO_CIPHERPROVIDER_CONF_KEY, DefaultCipherProvider.class.getName());
EncryptionTest.testCipherProvider(conf);
} catch (Exception e) {
fail("Instantiation of test cipher provider should have passed");
}
try {
conf.set(HConstants.CRYPTO_CIPHERPROVIDER_CONF_KEY, FailingCipherProvider.class.getName());
EncryptionTest.testCipherProvider(conf);
fail("Instantiation of bad test cipher provider should have failed check");
} catch (Exception e) { }
}
@Test
public void testTestCipher() {
Configuration conf = HBaseConfiguration.create();
conf.set(HConstants.CRYPTO_KEYPROVIDER_CONF_KEY, KeyProviderForTesting.class.getName());
String algorithm =
conf.get(HConstants.CRYPTO_KEY_ALGORITHM_CONF_KEY, HConstants.CIPHER_AES);
try {
EncryptionTest.testEncryption(conf, algorithm, null);
} catch (Exception e) {
fail("Test for cipher " + algorithm + " should have succeeded");
}
try {
EncryptionTest.testEncryption(conf, "foobar", null);
fail("Test for bogus cipher should have failed");
} catch (Exception e) { }
}
public static class FailingKeyProvider implements KeyProvider {
@Override
public void init(String params) {
throw new RuntimeException("BAD!");
}
@Override
public Key getKey(String alias) {
return null;
}
@Override
public Key[] getKeys(String[] aliases) {
return null;
}
}
public static class FailingCipherProvider implements CipherProvider {
public FailingCipherProvider() {
super();
throw new RuntimeException("BAD!");
}
@Override
public Configuration getConf() {
return null;
}
@Override
public void setConf(Configuration conf) {
}
@Override
public String getName() {
return null;
}
@Override
public String[] getSupportedCiphers() {
return null;
}
@Override
public Cipher getCipher(String name) {
return null;
}
}
}
| ibmsoe/hbase | hbase-server/src/test/java/org/apache/hadoop/hbase/util/TestEncryptionTest.java | Java | apache-2.0 | 4,319 |
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.3-hudson-jaxb-ri-2.2-70-
// 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: 2011.02.02 at 03:31:08 PM MEZ
//
package reactionruleml;
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.XmlElements;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for Exists.type complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="Exists.type">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <group ref="{http://www.ruleml.org/1.0/xsd}Exists.content"/>
* <attGroup ref="{http://www.ruleml.org/1.0/xsd}Exists.attlist"/>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Exists.type", propOrder = {
"oid",
"declareOrVar",
"formula",
"atom",
"and",
"or",
"exists",
"equal",
"neg"
})
public class ExistsType {
protected OidType oid;
@XmlElements({
@XmlElement(name = "declare", type = DeclareType.class),
@XmlElement(name = "Var", type = VarType.class)
})
protected List<Object> declareOrVar;
protected FormulaExistsType formula;
@XmlElement(name = "Atom")
protected AtomType atom;
@XmlElement(name = "And")
protected AndInnerType and;
@XmlElement(name = "Or")
protected OrInnerType or;
@XmlElement(name = "Exists")
protected ExistsType exists;
@XmlElement(name = "Equal")
protected EqualType equal;
@XmlElement(name = "Neg")
protected NegType neg;
/**
* Gets the value of the oid property.
*
* @return
* possible object is
* {@link OidType }
*
*/
public OidType getOid() {
return oid;
}
/**
* Sets the value of the oid property.
*
* @param value
* allowed object is
* {@link OidType }
*
*/
public void setOid(OidType value) {
this.oid = value;
}
/**
* Gets the value of the declareOrVar 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 declareOrVar property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getDeclareOrVar().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link DeclareType }
* {@link VarType }
*
*
*/
public List<Object> getDeclareOrVar() {
if (declareOrVar == null) {
declareOrVar = new ArrayList<Object>();
}
return this.declareOrVar;
}
/**
* Gets the value of the formula property.
*
* @return
* possible object is
* {@link FormulaExistsType }
*
*/
public FormulaExistsType getFormula() {
return formula;
}
/**
* Sets the value of the formula property.
*
* @param value
* allowed object is
* {@link FormulaExistsType }
*
*/
public void setFormula(FormulaExistsType value) {
this.formula = value;
}
/**
* Gets the value of the atom property.
*
* @return
* possible object is
* {@link AtomType }
*
*/
public AtomType getAtom() {
return atom;
}
/**
* Sets the value of the atom property.
*
* @param value
* allowed object is
* {@link AtomType }
*
*/
public void setAtom(AtomType value) {
this.atom = value;
}
/**
* Gets the value of the and property.
*
* @return
* possible object is
* {@link AndInnerType }
*
*/
public AndInnerType getAnd() {
return and;
}
/**
* Sets the value of the and property.
*
* @param value
* allowed object is
* {@link AndInnerType }
*
*/
public void setAnd(AndInnerType value) {
this.and = value;
}
/**
* Gets the value of the or property.
*
* @return
* possible object is
* {@link OrInnerType }
*
*/
public OrInnerType getOr() {
return or;
}
/**
* Sets the value of the or property.
*
* @param value
* allowed object is
* {@link OrInnerType }
*
*/
public void setOr(OrInnerType value) {
this.or = value;
}
/**
* Gets the value of the exists property.
*
* @return
* possible object is
* {@link ExistsType }
*
*/
public ExistsType getExists() {
return exists;
}
/**
* Sets the value of the exists property.
*
* @param value
* allowed object is
* {@link ExistsType }
*
*/
public void setExists(ExistsType value) {
this.exists = value;
}
/**
* Gets the value of the equal property.
*
* @return
* possible object is
* {@link EqualType }
*
*/
public EqualType getEqual() {
return equal;
}
/**
* Sets the value of the equal property.
*
* @param value
* allowed object is
* {@link EqualType }
*
*/
public void setEqual(EqualType value) {
this.equal = value;
}
/**
* Gets the value of the neg property.
*
* @return
* possible object is
* {@link NegType }
*
*/
public NegType getNeg() {
return neg;
}
/**
* Sets the value of the neg property.
*
* @param value
* allowed object is
* {@link NegType }
*
*/
public void setNeg(NegType value) {
this.neg = value;
}
}
| mswiderski/drools | drools-ruleml/src/main/resources/reactionruleml/ExistsType.java | Java | apache-2.0 | 6,577 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.axis2.deployment;
import org.apache.axis2.deployment.resolver.AARBasedWSDLLocator;
import org.apache.axis2.deployment.resolver.WarBasedWSDLLocator;
import org.xml.sax.InputSource;
import junit.framework.TestCase;
public class WSDLLocatorTest extends TestCase {
public void testGetInputSource() {
AARBasedWSDLLocator aarBasedWSDLLocator=new AARBasedWSDLLocator(null, null, null);
WarBasedWSDLLocator warBasedWSDLLocator=new WarBasedWSDLLocator(null, null, null);
InputSource inputSource=aarBasedWSDLLocator.resolveEntity(null, "http://www.test.org/test.xsd", "http://www.test.org/schema.xsd");
assertNotNull(inputSource);
assertEquals(inputSource.getSystemId(), "http://www.test.org/test.xsd");
inputSource=warBasedWSDLLocator.resolveEntity(null, "http://www.test.org/test.xsd", "http://www.test.org/schema.xsd");
assertNotNull(inputSource);
assertEquals(inputSource.getSystemId(), "http://www.test.org/test.xsd");
}
}
| apache/axis2-java | modules/kernel/test/org/apache/axis2/deployment/WSDLLocatorTest.java | Java | apache-2.0 | 1,821 |
/**
* Copyright 2011-2019 Asakusa Framework Team.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.asakusafw.utils.java.parser.javadoc;
import com.asakusafw.utils.java.internal.parser.javadoc.ir.IrLocation;
/**
* An exception which represents a documentation comment has unexpected end of comment.
*/
public class IllegalEndOfCommentException extends JavadocParseException {
private static final long serialVersionUID = 1L;
/**
* Creates a new instance.
* @param location the location
* @param cause the original cause
*/
public IllegalEndOfCommentException(IrLocation location, Throwable cause) {
super(buildMessage(), location, cause);
}
private static String buildMessage() {
return "Unexpected end of comment (*/)";
}
}
| akirakw/asakusafw | utils-project/javadoc-parser/src/main/java/com/asakusafw/utils/java/parser/javadoc/IllegalEndOfCommentException.java | Java | apache-2.0 | 1,317 |
/**
* Copyright 2014-2016 CyberVision, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kaaproject.kaa.demo.smarthousedemo.command.music;
import java.util.Map;
import org.kaaproject.kaa.demo.smarthouse.music.MusicEventClassFamily;
import org.kaaproject.kaa.demo.smarthousedemo.command.EndpointCommandKey;
import org.kaaproject.kaa.demo.smarthousedemo.concurrent.BlockingCallable;
public abstract class AbstractPlayerCommand<V> extends BlockingCallable<V> {
private final Map<EndpointCommandKey, BlockingCallable<?>> commandMap;
protected final MusicEventClassFamily players;
protected final String endpontKey;
protected final Class<V> clazz;
AbstractPlayerCommand(Map<EndpointCommandKey, BlockingCallable<?>> commandMap,
MusicEventClassFamily players,
String endpontKey,
Class<V> clazz) {
this.commandMap = commandMap;
this.players = players;
this.endpontKey = endpontKey;
this.clazz = clazz;
}
@Override
protected void executeAsync() {
EndpointCommandKey key = new EndpointCommandKey(clazz.getName(), endpontKey);
commandMap.put(key, this);
executePlayerCommand();
}
protected abstract void executePlayerCommand();
}
| maxml/sample-apps | smarthousedemo/source/src/org/kaaproject/kaa/demo/smarthousedemo/command/music/AbstractPlayerCommand.java | Java | apache-2.0 | 1,823 |
package com.cardpay.pccredit.manager.service;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.cardpay.pccredit.customer.model.CustomerManagerTarget;
import com.cardpay.pccredit.manager.constant.ManagerTargetType;
import com.cardpay.pccredit.manager.dao.AccountManagerParameterDao;
import com.cardpay.pccredit.manager.dao.comdao.AccountManagerParameterComdao;
import com.cardpay.pccredit.manager.filter.AccountManagerParameterFilter;
import com.cardpay.pccredit.manager.model.AccountManagerParameter;
import com.cardpay.pccredit.manager.web.AccountManagerParameterForm;
import com.wicresoft.jrad.base.auth.IUser;
import com.wicresoft.jrad.base.database.dao.common.CommonDao;
import com.wicresoft.jrad.base.database.model.QueryResult;
import com.wicresoft.jrad.base.web.security.LoginManager;
import com.wicresoft.jrad.modules.privilege.model.User;
import com.wicresoft.util.date.DateHelper;
import com.wicresoft.util.spring.Beans;
/**
* AccountManagerParameterService类的描述
*
* @author 王海东
* @created on 2014-11-7
*
* @version $Id:$
*/
@Service
public class AccountManagerParameterService {
@Autowired
private CommonDao commonDao;
@Autowired
private AccountManagerParameterDao accountManagerParameterDao;
@Autowired
private AccountManagerParameterComdao accountManagerParameterComdao;
public String insertAccountManagerParameter(AccountManagerParameter accountManagerParameter) {
accountManagerParameter.setCreatedTime(Calendar.getInstance().getTime());
if(accountManagerParameter != null){
String basePay = accountManagerParameter.getBasePay();
if(basePay !=null && !basePay.equals("")){
Double basePayDouble = Double.parseDouble(basePay) * 100;
String basePayValue = basePayDouble.toString();
accountManagerParameter.setBasePay(basePayValue);
}
}
commonDao.insertObject(accountManagerParameter);
return accountManagerParameter.getId();
}
/**
* 客户经理参数配置新增
* @param request
*/
public void insertAccountManagerParameter(HttpServletRequest request) {
Calendar calendar = Calendar.getInstance();
IUser user = Beans.get(LoginManager.class).getLoggedInUser(request);
String userId = user.getId();
String customerManagerId= request.getParameter("userId");
String accountManagerParameterId= request.getParameter("accountManagerParameterId");
String levelInformation= request.getParameter("levelInformation");
String entryTime= request.getParameter("entryTime");
Date entryTimedate = DateHelper.getDateFormat(entryTime, "yyyy-MM-dd");
String basePay= request.getParameter("basePay");
AccountManagerParameter accountManagerParameter = new AccountManagerParameter();
accountManagerParameter.setLevelInformation(levelInformation);
accountManagerParameter.setEntryTime(entryTimedate);
accountManagerParameter.setBasePay(basePay);
accountManagerParameter.setModifiedBy(userId);
accountManagerParameter.setModifiedTime(calendar.getTime());
if(accountManagerParameterId == null || accountManagerParameterId.equals("")){
accountManagerParameter.setUserId(customerManagerId);
accountManagerParameter.setCreatedBy(userId);
accountManagerParameter.setCreatedTime(calendar.getTime());
commonDao.insertObject(accountManagerParameter);
}else{
accountManagerParameter.setId(accountManagerParameterId);
commonDao.updateObject(accountManagerParameter);
}
// String[] id= request.getParameterValues("id");
// String[] targetDate= request.getParameterValues("targetDate");
// String[] targetCredit= request.getParameterValues("targetCredit");
// String[] targetNumber= request.getParameterValues("targetNumber");
// String[] targetNumberVisit= request.getParameterValues("targetNumberVisit");
// String[] targetNumberCustomers= request.getParameterValues("targetNumberCustomers");
// String[] activeNumber= request.getParameterValues("activeNumber");
// String[] activationNumber= request.getParameterValues("activationNumber");
//
// for(int i=0;i<targetDate.length;i++){
// CustomerManagerTarget customerManagerTarget = new CustomerManagerTarget();
// String targetDateValue= targetDate[i];
// String targetCreditValue=targetCredit[i];
// String idValue=id[i];
// if(targetNumber[i] !="" && targetNumber[i] !=null){
// int targetNumberValue=Integer.parseInt(targetNumber[i]);
// customerManagerTarget.setTargetNumber(targetNumberValue);
// }
// if(targetNumberVisit[i] !="" && targetNumberVisit[i] !=null){
// int targetNumberVisitValue=Integer.parseInt(targetNumberVisit[i]);
// customerManagerTarget.setTargetNumberVisit(targetNumberVisitValue);
//
// }
// if(targetNumberCustomers[i] !="" && targetNumberCustomers[i] !=null){
// int targetNumberCustomersValue=Integer.parseInt(targetNumberCustomers[i]);
// customerManagerTarget.setTargetNumberCustomers(targetNumberCustomersValue);
// }
// if(activeNumber[i] !="" && activeNumber[i] !=null){
// int activeNumberValue=Integer.parseInt(activeNumber[i]);
// customerManagerTarget.setActiveNumber(activeNumberValue);
// }
// if(activationNumber[i] !="" && activationNumber[i] !=null){
// int activationNumberValue=Integer.parseInt(activationNumber[i]);
// customerManagerTarget.setActivationNumber(activationNumberValue);
// }
// customerManagerTarget.setTargetDate(targetDateValue);
// customerManagerTarget.setTargetCredit(targetCreditValue);
//
//
// customerManagerTarget.setModifiedBy(userId);
// customerManagerTarget.setModifiedTime(calendar.getTime());
// customerManagerTarget.setCustomerManagerId(customerManagerId);
// if(idValue == "" || idValue == null){
// customerManagerTarget.setCreatedBy(userId);
// customerManagerTarget.setCreatedTime(calendar.getTime());
// commonDao.insertObject(customerManagerTarget);
//
// }else{
// customerManagerTarget.setId(idValue);
// commonDao.updateObject(customerManagerTarget);
// }
//
// }
//
}
/**
* 客户经理参数配置修改
* @param request
*/
public void updateAccountManagerParameter(HttpServletRequest request) {
Calendar calendar = Calendar.getInstance();
IUser user = Beans.get(LoginManager.class).getLoggedInUser(request);
String userId = user.getId();
String customerManagerId= request.getParameter("userId");
String accountManagerParameterId= request.getParameter("accountManagerParameterId");
String levelInformation= request.getParameter("levelInformation");
String entryTime= request.getParameter("entryTime");
Date entryTimedate = DateHelper.getDateFormat(entryTime, "yyyy-MM-dd");
String basePay= request.getParameter("basePay");
AccountManagerParameter accountManagerParameter = new AccountManagerParameter();
accountManagerParameter.setLevelInformation(levelInformation);
accountManagerParameter.setEntryTime(entryTimedate);
accountManagerParameter.setBasePay(basePay);
accountManagerParameter.setModifiedBy(userId);
accountManagerParameter.setModifiedTime(calendar.getTime());
if(accountManagerParameterId == null || accountManagerParameterId.equals("")){
accountManagerParameter.setUserId(customerManagerId);
accountManagerParameter.setCreatedBy(userId);
accountManagerParameter.setCreatedTime(calendar.getTime());
commonDao.insertObject(accountManagerParameter);
}else{
accountManagerParameter.setId(accountManagerParameterId);
commonDao.updateObject(accountManagerParameter);
}
// String[] id= request.getParameterValues("id");
// String[] targetDate= request.getParameterValues("targetDate");
// String[] targetCredit= request.getParameterValues("targetCredit");
// String[] targetNumber= request.getParameterValues("targetNumber");
// String[] targetNumberVisit= request.getParameterValues("targetNumberVisit");
// String[] targetNumberCustomers= request.getParameterValues("targetNumberCustomers");
// String[] activeNumber= request.getParameterValues("activeNumber");
// String[] activationNumber= request.getParameterValues("activationNumber");
//
// for(int i=0;i<targetDate.length;i++){
// CustomerManagerTarget customerManagerTarget = new CustomerManagerTarget();
// String targetDateValue= targetDate[i];
// String targetCreditValue=targetCredit[i];
// String idValue=id[i];
// if(targetNumber[i] !="" && targetNumber[i] !=null){
// int targetNumberValue=Integer.parseInt(targetNumber[i]);
// customerManagerTarget.setTargetNumber(targetNumberValue);
// }
// if(targetNumberVisit[i] !="" && targetNumberVisit[i] !=null){
// int targetNumberVisitValue=Integer.parseInt(targetNumberVisit[i]);
// customerManagerTarget.setTargetNumberVisit(targetNumberVisitValue);
//
// }
// if(targetNumberCustomers[i] !="" && targetNumberCustomers[i] !=null){
// int targetNumberCustomersValue=Integer.parseInt(targetNumberCustomers[i]);
// customerManagerTarget.setTargetNumberCustomers(targetNumberCustomersValue);
// }
// if(activeNumber[i] !="" && activeNumber[i] !=null){
// int activeNumberValue=Integer.parseInt(activeNumber[i]);
// customerManagerTarget.setActiveNumber(activeNumberValue);
// }
// if(activationNumber[i] !="" && activationNumber[i] !=null){
// int activationNumberValue=Integer.parseInt(activationNumber[i]);
// customerManagerTarget.setActivationNumber(activationNumberValue);
// }
// customerManagerTarget.setTargetDate(targetDateValue);
// customerManagerTarget.setTargetCredit(targetCreditValue);
//
//
// customerManagerTarget.setModifiedBy(userId);
// customerManagerTarget.setModifiedTime(calendar.getTime());
// customerManagerTarget.setCustomerManagerId(customerManagerId);
// if(idValue == "" || idValue == null){
// customerManagerTarget.setCreatedBy(userId);
// customerManagerTarget.setCreatedTime(calendar.getTime());
// commonDao.insertObject(customerManagerTarget);
//
// }else{
// customerManagerTarget.setId(idValue);
// commonDao.updateObject(customerManagerTarget);
// }
//}
}
/**
* 客户经理层级业绩目标修改
* @param request
*/
public void updatecustomerManagerTarget(HttpServletRequest request) {
Calendar calendar = Calendar.getInstance();
IUser user = Beans.get(LoginManager.class).getLoggedInUser(request);
String userId = user.getId();
String[] id_year= request.getParameterValues("id_year");
String[] hierarchy_year= request.getParameterValues("hierarchy_year");
String[] targetCredit_year= request.getParameterValues("targetCredit_year");
String[] targetNumber_year= request.getParameterValues("targetNumber_year");
String[] targetNumberVisit_year= request.getParameterValues("targetNumberVisit_year");
String[] targetNumberCustomers_year= request.getParameterValues("targetNumberCustomers_year");
String[] activeNumber_year= request.getParameterValues("activeNumber_year");
String[] activationNumber_year= request.getParameterValues("activationNumber_year");
String[] tubeNumber_year= request.getParameterValues("tubeNumber_year");
for(int i=0;i<hierarchy_year.length;i++){
CustomerManagerTarget customerManagerTarget = new CustomerManagerTarget();
String hierarchyValue= hierarchy_year[i];
//String targetCreditValue=targetCredit_year[i];
String idValue=id_year[i];
if(targetCredit_year[i] !=null && targetCredit_year[i] !=""){
Double targetCredit_yearDouble = Double.parseDouble(targetCredit_year[i]) * 100;
String targetCreditValue = targetCredit_yearDouble.toString();
customerManagerTarget.setTargetCredit(targetCreditValue);
}
if(targetNumber_year[i] !="" && targetNumber_year[i] !=null){
int targetNumberValue=Integer.parseInt(targetNumber_year[i]);
customerManagerTarget.setTargetNumber(targetNumberValue);
}
if(targetNumberVisit_year[i] !="" && targetNumberVisit_year[i] !=null){
int targetNumberVisitValue=Integer.parseInt(targetNumberVisit_year[i]);
customerManagerTarget.setTargetNumberVisit(targetNumberVisitValue);
}
if(targetNumberCustomers_year[i] !="" && targetNumberCustomers_year[i] !=null){
int targetNumberCustomersValue=Integer.parseInt(targetNumberCustomers_year[i]);
customerManagerTarget.setTargetNumberCustomers(targetNumberCustomersValue);
}
if(activeNumber_year[i] !="" && activeNumber_year[i] !=null){
int activeNumberValue=Integer.parseInt(activeNumber_year[i]);
customerManagerTarget.setActiveNumber(activeNumberValue);
}
if(activationNumber_year[i] !="" && activationNumber_year[i] !=null){
int activationNumberValue=Integer.parseInt(activationNumber_year[i]);
customerManagerTarget.setActivationNumber(activationNumberValue);
}
if(tubeNumber_year[i] !="" && tubeNumber_year[i] !=null){
int activationNumberValue=Integer.parseInt(tubeNumber_year[i]);
customerManagerTarget.setTubeNumber(activationNumberValue);
}
customerManagerTarget.setHierarchy(hierarchyValue);
customerManagerTarget.setModifiedBy(userId);
customerManagerTarget.setModifiedTime(calendar.getTime());
customerManagerTarget.setTargetDate(ManagerTargetType.year.name());
if(idValue == null || idValue.equals("")){
customerManagerTarget.setCreatedBy(userId);
customerManagerTarget.setCreatedTime(calendar.getTime());
commonDao.insertObject(customerManagerTarget);
}else{
customerManagerTarget.setId(idValue);
commonDao.updateObject(customerManagerTarget);
}
}
String[] id_month= request.getParameterValues("id_month");
String[] hierarchy_month= request.getParameterValues("hierarchy_month");
String[] targetCredit_month= request.getParameterValues("targetCredit_month");
String[] targetNumber_month= request.getParameterValues("targetNumber_month");
String[] targetNumberVisit_month= request.getParameterValues("targetNumberVisit_month");
String[] targetNumberCustomers_month= request.getParameterValues("targetNumberCustomers_month");
String[] activeNumber_month= request.getParameterValues("activeNumber_month");
String[] activationNumber_month= request.getParameterValues("activationNumber_month");
String[] tubeNumber_month= request.getParameterValues("tubeNumber_month");
for(int i=0;i<hierarchy_month.length;i++){
CustomerManagerTarget customerManagerTarget = new CustomerManagerTarget();
String hierarchyValue= hierarchy_month[i];
//String targetCreditValue=targetCredit_month[i];
String idValue=id_month[i];
if(targetCredit_month[i] !=null && targetCredit_month[i] !=""){
Double targetCredit_monthDouble = Double.parseDouble(targetCredit_month[i]) * 100;
String targetCreditValue = targetCredit_monthDouble.toString();
customerManagerTarget.setTargetCredit(targetCreditValue);
}
if(targetNumber_month[i] !="" && targetNumber_month[i] !=null){
int targetNumberValue=Integer.parseInt(targetNumber_month[i]);
customerManagerTarget.setTargetNumber(targetNumberValue);
}
if(targetNumberVisit_month[i] !="" && targetNumberVisit_month[i] !=null){
int targetNumberVisitValue=Integer.parseInt(targetNumberVisit_month[i]);
customerManagerTarget.setTargetNumberVisit(targetNumberVisitValue);
}
if(targetNumberCustomers_month[i] !="" && targetNumberCustomers_month[i] !=null){
int targetNumberCustomersValue=Integer.parseInt(targetNumberCustomers_month[i]);
customerManagerTarget.setTargetNumberCustomers(targetNumberCustomersValue);
}
if(activeNumber_month[i] !="" && activeNumber_month[i] !=null){
int activeNumberValue=Integer.parseInt(activeNumber_month[i]);
customerManagerTarget.setActiveNumber(activeNumberValue);
}
if(activationNumber_month[i] !="" && activationNumber_month[i] !=null){
int activationNumberValue=Integer.parseInt(activationNumber_month[i]);
customerManagerTarget.setActivationNumber(activationNumberValue);
}
if(tubeNumber_month[i] !="" && tubeNumber_month[i] !=null){
int activationNumberValue=Integer.parseInt(tubeNumber_month[i]);
customerManagerTarget.setTubeNumber(activationNumberValue);
}
customerManagerTarget.setHierarchy(hierarchyValue);
customerManagerTarget.setModifiedBy(userId);
customerManagerTarget.setModifiedTime(calendar.getTime());
customerManagerTarget.setTargetDate(ManagerTargetType.month.name());
if(idValue == null || idValue.equals("")){
customerManagerTarget.setCreatedBy(userId);
customerManagerTarget.setCreatedTime(calendar.getTime());
commonDao.insertObject(customerManagerTarget);
}else{
customerManagerTarget.setId(idValue);
commonDao.updateObject(customerManagerTarget);
}
}
String[] id_weekly= request.getParameterValues("id_weekly");
String[] hierarchy_weekly= request.getParameterValues("hierarchy_weekly");
String[] targetCredit_weekly= request.getParameterValues("targetCredit_weekly");
String[] targetNumber_weekly= request.getParameterValues("targetNumber_weekly");
String[] targetNumberVisit_weekly= request.getParameterValues("targetNumberVisit_weekly");
String[] targetNumberCustomers_weekly= request.getParameterValues("targetNumberCustomers_weekly");
String[] activeNumber_weekly= request.getParameterValues("activeNumber_weekly");
String[] activationNumber_weekly= request.getParameterValues("activationNumber_weekly");
String[] tubeNumber_weekly= request.getParameterValues("tubeNumber_weekly");
for(int i=0;i<hierarchy_weekly.length;i++){
CustomerManagerTarget customerManagerTarget = new CustomerManagerTarget();
String hierarchyValue= hierarchy_weekly[i];
//String targetCreditValue=targetCredit_weekly[i];
String idValue=id_weekly[i];
if(targetCredit_weekly[i] !=null && targetCredit_weekly[i] !=""){
Double targetCredit_weeklyDouble = Double.parseDouble(targetCredit_weekly[i]) * 100;
String targetCreditValue = targetCredit_weeklyDouble.toString();
customerManagerTarget.setTargetCredit(targetCreditValue);
}
if(targetNumber_weekly[i] !="" && targetNumber_weekly[i] !=null){
int targetNumberValue=Integer.parseInt(targetNumber_weekly[i]);
customerManagerTarget.setTargetNumber(targetNumberValue);
}
if(targetNumberVisit_weekly[i] !="" && targetNumberVisit_weekly[i] !=null){
int targetNumberVisitValue=Integer.parseInt(targetNumberVisit_weekly[i]);
customerManagerTarget.setTargetNumberVisit(targetNumberVisitValue);
}
if(targetNumberCustomers_weekly[i] !="" && targetNumberCustomers_weekly[i] !=null){
int targetNumberCustomersValue=Integer.parseInt(targetNumberCustomers_weekly[i]);
customerManagerTarget.setTargetNumberCustomers(targetNumberCustomersValue);
}
if(activeNumber_weekly[i] !="" && activeNumber_weekly[i] !=null){
int activeNumberValue=Integer.parseInt(activeNumber_weekly[i]);
customerManagerTarget.setActiveNumber(activeNumberValue);
}
if(activationNumber_weekly[i] !="" && activationNumber_weekly[i] !=null){
int activationNumberValue=Integer.parseInt(activationNumber_weekly[i]);
customerManagerTarget.setActivationNumber(activationNumberValue);
}
if(tubeNumber_weekly[i] !="" && tubeNumber_weekly[i] !=null){
int activationNumberValue=Integer.parseInt(tubeNumber_weekly[i]);
customerManagerTarget.setTubeNumber(activationNumberValue);
}
customerManagerTarget.setHierarchy(hierarchyValue);
customerManagerTarget.setModifiedBy(userId);
customerManagerTarget.setModifiedTime(calendar.getTime());
customerManagerTarget.setTargetDate(ManagerTargetType.weekly.name());
if(idValue == null || idValue.equals("")){
customerManagerTarget.setCreatedBy(userId);
customerManagerTarget.setCreatedTime(calendar.getTime());
commonDao.insertObject(customerManagerTarget);
}else{
customerManagerTarget.setId(idValue);
commonDao.updateObject(customerManagerTarget);
}
}
}
public int updateAccountManagerParameter(AccountManagerParameter accountManagerParameter) {
accountManagerParameter.setModifiedTime(Calendar.getInstance().getTime());
if(accountManagerParameter != null){
String basePay = accountManagerParameter.getBasePay();
if(basePay !=null && basePay !=""){
Double basePayDouble = Double.parseDouble(basePay) * 100;
String basePayValue = basePayDouble.toString();
accountManagerParameter.setBasePay(basePayValue);
}
}
return commonDao.updateObject(accountManagerParameter);
}
public int deleteAccountManagerParameter(String managerId) {
return commonDao.deleteObject(AccountManagerParameter.class, managerId);
}
public AccountManagerParameter findAccountManagerParameterById(String managerId) {
return commonDao.findObjectById(AccountManagerParameter.class, managerId);
}
public QueryResult<AccountManagerParameterForm> findAccountManagerParametersByFilter(AccountManagerParameterFilter filter) {
List<AccountManagerParameterForm> accountManagerParameterForm = accountManagerParameterDao.findAccountManagerParametersByFilter(filter);
int size = accountManagerParameterDao.findAccountManagerParametersCountByFilter(filter);
QueryResult<AccountManagerParameterForm> qs = new QueryResult<AccountManagerParameterForm>(size , accountManagerParameterForm);
return qs;
}
public AccountManagerParameterForm findAccountManagerParameterByUserId(String userId) {
return accountManagerParameterDao.findAccountManagerParameterByUserId(userId);
}
/**
* 获取所有客户经理
*/
public List<AccountManagerParameterForm> findAccountManagerParameterAll(){
return accountManagerParameterDao.findAccountManagerParametersAll();
}
/**
* 获取客户经理的属性参数根据Id
* @return
*/
public List<CustomerManagerTarget> getcustomerManagerTargetBymanagerId(String managerId){
AccountManagerParameterForm accountManagerParameter =findAccountManagerParameterByUserId(managerId);
String hierarchy = accountManagerParameter.getLevelInformation();
return accountManagerParameterComdao.getcustomerManagerTargetBymanagerId(hierarchy);
}
/**
* 获取客户经理的属性参数根据周期
* @return
*/
public List<CustomerManagerTarget> getcustomerManagerTargetBytargetDate(String targetDate){
return accountManagerParameterComdao.getcustomerManagerTargetBytargetDate(targetDate);
}
/**
* 获取所有客户经理的属性参数
* @return
*/
public List<CustomerManagerTarget> getcustomerManagerTarget(){
return accountManagerParameterComdao.getcustomerManagerTarget();
}
/**
* 获取客户经理的属性参数根据Id和周期
* @return
*/
public CustomerManagerTarget getcustomerManagerTargetBymanagerIdDate(String managerId,String targetDate){
AccountManagerParameterForm accountManagerParameter =findAccountManagerParameterByUserId(managerId);
String hierarchy = accountManagerParameter.getLevelInformation();
return accountManagerParameterComdao.getcustomerManagerTargetBymanagerIdDate(hierarchy, targetDate);
}
//获取用户角色
public String findRoleNameByUserId(String userId){
return accountManagerParameterDao.findRoleNameByUserId(userId);
}
public List<User> findUserByName(String chineseName) {
// TODO Auto-generated method stub
String sql = "select * from sys_user where display_name like '%"+chineseName+"%' and id not in (select user_id from ACCOUNT_MANAGER_PARAMETER)";
return commonDao.queryBySql(User.class, sql, null);
}
public List<User> findUserByNameInMgr(String chineseName) {
// TODO Auto-generated method stub
String sql = "select * from sys_user where display_name like '%"+chineseName+"%' and id in (select user_id from ACCOUNT_MANAGER_PARAMETER)";
return commonDao.queryBySql(User.class, sql, null);
}
}
| JohnCny/PCCREDIT_QZ | src/java/com/cardpay/pccredit/manager/service/AccountManagerParameterService.java | Java | apache-2.0 | 24,353 |
package io.spotnext.core.persistence.query.lambda;
import com.trigersoft.jaque.expression.ConstantExpression;
import com.trigersoft.jaque.expression.Expression;
import com.trigersoft.jaque.expression.ParameterExpression;
import com.trigersoft.jaque.expression.SimpleExpressionVisitor;
/**
* Visitor which counts occurrences of given Expression types
*
* @author mojo2012
* @version 1.0
* @since 1.0
*/
public class CountingVisitor extends SimpleExpressionVisitor {
private int constantExpressionsCount = 0;
private int parameterExpressionCount = 0;
/** {@inheritDoc} */
@Override
public Expression visit(final ConstantExpression e) {
constantExpressionsCount++;
return super.visit(e);
}
/** {@inheritDoc} */
@Override
public Expression visit(final ParameterExpression e) {
parameterExpressionCount++;
return super.visit(e);
}
/**
* <p>Getter for the field <code>constantExpressionsCount</code>.</p>
*
* @return a int.
*/
public int getConstantExpressionsCount() {
return constantExpressionsCount;
}
/**
* <p>getParameterExpressionsCount.</p>
*
* @return a int.
*/
public int getParameterExpressionsCount() {
return parameterExpressionCount;
}
}
| mojo2012/spot-framework | spot-core/src/main/java/io/spotnext/core/persistence/query/lambda/CountingVisitor.java | Java | apache-2.0 | 1,202 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.flink.streaming.api.graph;
import org.apache.flink.annotation.Internal;
import org.apache.flink.annotation.VisibleForTesting;
import org.apache.flink.api.common.typeutils.TypeSerializer;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.runtime.jobgraph.OperatorID;
import org.apache.flink.runtime.operators.util.CorruptConfigurationException;
import org.apache.flink.runtime.state.StateBackend;
import org.apache.flink.runtime.util.ClassLoaderUtil;
import org.apache.flink.streaming.api.CheckpointingMode;
import org.apache.flink.streaming.api.TimeCharacteristic;
import org.apache.flink.streaming.api.collector.selector.OutputSelector;
import org.apache.flink.streaming.api.operators.SimpleOperatorFactory;
import org.apache.flink.streaming.api.operators.StreamOperator;
import org.apache.flink.streaming.api.operators.StreamOperatorFactory;
import org.apache.flink.streaming.runtime.tasks.StreamTaskException;
import org.apache.flink.util.InstantiationUtil;
import org.apache.flink.util.OutputTag;
import org.apache.flink.util.Preconditions;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Internal configuration for a {@link StreamOperator}. This is created and populated by the
* {@link StreamingJobGraphGenerator}.
*/
@Internal
public class StreamConfig implements Serializable {
private static final long serialVersionUID = 1L;
// ------------------------------------------------------------------------
// Config Keys
// ------------------------------------------------------------------------
private static final String NUMBER_OF_OUTPUTS = "numberOfOutputs";
private static final String NUMBER_OF_INPUTS = "numberOfInputs";
private static final String CHAINED_OUTPUTS = "chainedOutputs";
private static final String CHAINED_TASK_CONFIG = "chainedTaskConfig_";
private static final String IS_CHAINED_VERTEX = "isChainedSubtask";
private static final String CHAIN_INDEX = "chainIndex";
private static final String VERTEX_NAME = "vertexID";
private static final String ITERATION_ID = "iterationId";
private static final String OUTPUT_SELECTOR_WRAPPER = "outputSelectorWrapper";
private static final String SERIALIZEDUDF = "serializedUDF";
private static final String BUFFER_TIMEOUT = "bufferTimeout";
private static final String TYPE_SERIALIZER_IN_1 = "typeSerializer_in_1";
private static final String TYPE_SERIALIZER_IN_2 = "typeSerializer_in_2";
private static final String TYPE_SERIALIZER_OUT_1 = "typeSerializer_out";
private static final String TYPE_SERIALIZER_SIDEOUT_PREFIX = "typeSerializer_sideout_";
private static final String ITERATON_WAIT = "iterationWait";
private static final String NONCHAINED_OUTPUTS = "nonChainedOutputs";
private static final String EDGES_IN_ORDER = "edgesInOrder";
private static final String OUT_STREAM_EDGES = "outStreamEdges";
private static final String IN_STREAM_EDGES = "inStreamEdges";
private static final String OPERATOR_NAME = "operatorName";
private static final String OPERATOR_ID = "operatorID";
private static final String CHAIN_END = "chainEnd";
private static final String CHECKPOINTING_ENABLED = "checkpointing";
private static final String CHECKPOINT_MODE = "checkpointMode";
private static final String STATE_BACKEND = "statebackend";
private static final String STATE_PARTITIONER = "statePartitioner";
private static final String STATE_KEY_SERIALIZER = "statekeyser";
private static final String TIME_CHARACTERISTIC = "timechar";
// ------------------------------------------------------------------------
// Default Values
// ------------------------------------------------------------------------
private static final long DEFAULT_TIMEOUT = 100;
private static final CheckpointingMode DEFAULT_CHECKPOINTING_MODE = CheckpointingMode.EXACTLY_ONCE;
// ------------------------------------------------------------------------
// Config
// ------------------------------------------------------------------------
private final Configuration config;
public StreamConfig(Configuration config) {
this.config = config;
}
public Configuration getConfiguration() {
return config;
}
// ------------------------------------------------------------------------
// Configured Properties
// ------------------------------------------------------------------------
public void setVertexID(Integer vertexID) {
config.setInteger(VERTEX_NAME, vertexID);
}
public Integer getVertexID() {
return config.getInteger(VERTEX_NAME, -1);
}
public void setTimeCharacteristic(TimeCharacteristic characteristic) {
config.setInteger(TIME_CHARACTERISTIC, characteristic.ordinal());
}
public TimeCharacteristic getTimeCharacteristic() {
int ordinal = config.getInteger(TIME_CHARACTERISTIC, -1);
if (ordinal >= 0) {
return TimeCharacteristic.values()[ordinal];
} else {
throw new CorruptConfigurationException("time characteristic is not set");
}
}
public void setTypeSerializerIn1(TypeSerializer<?> serializer) {
setTypeSerializer(TYPE_SERIALIZER_IN_1, serializer);
}
public void setTypeSerializerIn2(TypeSerializer<?> serializer) {
setTypeSerializer(TYPE_SERIALIZER_IN_2, serializer);
}
public void setTypeSerializerOut(TypeSerializer<?> serializer) {
setTypeSerializer(TYPE_SERIALIZER_OUT_1, serializer);
}
public void setTypeSerializerSideOut(OutputTag<?> outputTag, TypeSerializer<?> serializer) {
setTypeSerializer(TYPE_SERIALIZER_SIDEOUT_PREFIX + outputTag.getId(), serializer);
}
public <T> TypeSerializer<T> getTypeSerializerIn1(ClassLoader cl) {
try {
return InstantiationUtil.readObjectFromConfig(this.config, TYPE_SERIALIZER_IN_1, cl);
} catch (Exception e) {
throw new StreamTaskException("Could not instantiate serializer.", e);
}
}
public <T> TypeSerializer<T> getTypeSerializerIn2(ClassLoader cl) {
try {
return InstantiationUtil.readObjectFromConfig(this.config, TYPE_SERIALIZER_IN_2, cl);
} catch (Exception e) {
throw new StreamTaskException("Could not instantiate serializer.", e);
}
}
public <T> TypeSerializer<T> getTypeSerializerOut(ClassLoader cl) {
try {
return InstantiationUtil.readObjectFromConfig(this.config, TYPE_SERIALIZER_OUT_1, cl);
} catch (Exception e) {
throw new StreamTaskException("Could not instantiate serializer.", e);
}
}
public <T> TypeSerializer<T> getTypeSerializerSideOut(OutputTag<?> outputTag, ClassLoader cl) {
Preconditions.checkNotNull(outputTag, "Side output id must not be null.");
try {
return InstantiationUtil.readObjectFromConfig(this.config, TYPE_SERIALIZER_SIDEOUT_PREFIX + outputTag.getId(), cl);
} catch (Exception e) {
throw new StreamTaskException("Could not instantiate serializer.", e);
}
}
private void setTypeSerializer(String key, TypeSerializer<?> typeWrapper) {
try {
InstantiationUtil.writeObjectToConfig(typeWrapper, this.config, key);
} catch (IOException e) {
throw new StreamTaskException("Could not serialize type serializer.", e);
}
}
public void setBufferTimeout(long timeout) {
config.setLong(BUFFER_TIMEOUT, timeout);
}
public long getBufferTimeout() {
return config.getLong(BUFFER_TIMEOUT, DEFAULT_TIMEOUT);
}
public boolean isFlushAlwaysEnabled() {
return getBufferTimeout() == 0;
}
@VisibleForTesting
public void setStreamOperator(StreamOperator<?> operator) {
setStreamOperatorFactory(SimpleOperatorFactory.of(operator));
}
public void setStreamOperatorFactory(StreamOperatorFactory<?> factory) {
if (factory != null) {
try {
InstantiationUtil.writeObjectToConfig(factory, this.config, SERIALIZEDUDF);
} catch (IOException e) {
throw new StreamTaskException("Cannot serialize operator object "
+ factory.getClass() + ".", e);
}
}
}
@VisibleForTesting
public <T extends StreamOperator<?>> T getStreamOperator(ClassLoader cl) {
SimpleOperatorFactory<?> factory = getStreamOperatorFactory(cl);
return (T) factory.getOperator();
}
public <T extends StreamOperatorFactory<?>> T getStreamOperatorFactory(ClassLoader cl) {
try {
return InstantiationUtil.readObjectFromConfig(this.config, SERIALIZEDUDF, cl);
}
catch (ClassNotFoundException e) {
String classLoaderInfo = ClassLoaderUtil.getUserCodeClassLoaderInfo(cl);
boolean loadableDoubleCheck = ClassLoaderUtil.validateClassLoadable(e, cl);
String exceptionMessage = "Cannot load user class: " + e.getMessage()
+ "\nClassLoader info: " + classLoaderInfo +
(loadableDoubleCheck ?
"\nClass was actually found in classloader - deserialization issue." :
"\nClass not resolvable through given classloader.");
throw new StreamTaskException(exceptionMessage, e);
}
catch (Exception e) {
throw new StreamTaskException("Cannot instantiate user function.", e);
}
}
public void setOutputSelectors(List<OutputSelector<?>> outputSelectors) {
try {
InstantiationUtil.writeObjectToConfig(outputSelectors, this.config, OUTPUT_SELECTOR_WRAPPER);
} catch (IOException e) {
throw new StreamTaskException("Could not serialize output selectors", e);
}
}
public <T> List<OutputSelector<T>> getOutputSelectors(ClassLoader userCodeClassloader) {
try {
List<OutputSelector<T>> selectors =
InstantiationUtil.readObjectFromConfig(this.config, OUTPUT_SELECTOR_WRAPPER, userCodeClassloader);
return selectors == null ? Collections.<OutputSelector<T>>emptyList() : selectors;
} catch (Exception e) {
throw new StreamTaskException("Could not read output selectors", e);
}
}
public void setIterationId(String iterationId) {
config.setString(ITERATION_ID, iterationId);
}
public String getIterationId() {
return config.getString(ITERATION_ID, "");
}
public void setIterationWaitTime(long time) {
config.setLong(ITERATON_WAIT, time);
}
public long getIterationWaitTime() {
return config.getLong(ITERATON_WAIT, 0);
}
public void setNumberOfInputs(int numberOfInputs) {
config.setInteger(NUMBER_OF_INPUTS, numberOfInputs);
}
public int getNumberOfInputs() {
return config.getInteger(NUMBER_OF_INPUTS, 0);
}
public void setNumberOfOutputs(int numberOfOutputs) {
config.setInteger(NUMBER_OF_OUTPUTS, numberOfOutputs);
}
public int getNumberOfOutputs() {
return config.getInteger(NUMBER_OF_OUTPUTS, 0);
}
public void setNonChainedOutputs(List<StreamEdge> outputvertexIDs) {
try {
InstantiationUtil.writeObjectToConfig(outputvertexIDs, this.config, NONCHAINED_OUTPUTS);
} catch (IOException e) {
throw new StreamTaskException("Cannot serialize non chained outputs.", e);
}
}
public List<StreamEdge> getNonChainedOutputs(ClassLoader cl) {
try {
List<StreamEdge> nonChainedOutputs = InstantiationUtil.readObjectFromConfig(this.config, NONCHAINED_OUTPUTS, cl);
return nonChainedOutputs == null ? new ArrayList<StreamEdge>() : nonChainedOutputs;
} catch (Exception e) {
throw new StreamTaskException("Could not instantiate non chained outputs.", e);
}
}
public void setChainedOutputs(List<StreamEdge> chainedOutputs) {
try {
InstantiationUtil.writeObjectToConfig(chainedOutputs, this.config, CHAINED_OUTPUTS);
} catch (IOException e) {
throw new StreamTaskException("Cannot serialize chained outputs.", e);
}
}
public List<StreamEdge> getChainedOutputs(ClassLoader cl) {
try {
List<StreamEdge> chainedOutputs = InstantiationUtil.readObjectFromConfig(this.config, CHAINED_OUTPUTS, cl);
return chainedOutputs == null ? new ArrayList<StreamEdge>() : chainedOutputs;
} catch (Exception e) {
throw new StreamTaskException("Could not instantiate chained outputs.", e);
}
}
public void setOutEdges(List<StreamEdge> outEdges) {
try {
InstantiationUtil.writeObjectToConfig(outEdges, this.config, OUT_STREAM_EDGES);
} catch (IOException e) {
throw new StreamTaskException("Cannot serialize outward edges.", e);
}
}
public List<StreamEdge> getOutEdges(ClassLoader cl) {
try {
List<StreamEdge> outEdges = InstantiationUtil.readObjectFromConfig(this.config, OUT_STREAM_EDGES, cl);
return outEdges == null ? new ArrayList<StreamEdge>() : outEdges;
} catch (Exception e) {
throw new StreamTaskException("Could not instantiate outputs.", e);
}
}
public void setInPhysicalEdges(List<StreamEdge> inEdges) {
try {
InstantiationUtil.writeObjectToConfig(inEdges, this.config, IN_STREAM_EDGES);
} catch (IOException e) {
throw new StreamTaskException("Cannot serialize inward edges.", e);
}
}
public List<StreamEdge> getInPhysicalEdges(ClassLoader cl) {
try {
List<StreamEdge> inEdges = InstantiationUtil.readObjectFromConfig(this.config, IN_STREAM_EDGES, cl);
return inEdges == null ? new ArrayList<StreamEdge>() : inEdges;
} catch (Exception e) {
throw new StreamTaskException("Could not instantiate inputs.", e);
}
}
// --------------------- checkpointing -----------------------
public void setCheckpointingEnabled(boolean enabled) {
config.setBoolean(CHECKPOINTING_ENABLED, enabled);
}
public boolean isCheckpointingEnabled() {
return config.getBoolean(CHECKPOINTING_ENABLED, false);
}
public void setCheckpointMode(CheckpointingMode mode) {
config.setInteger(CHECKPOINT_MODE, mode.ordinal());
}
public CheckpointingMode getCheckpointMode() {
int ordinal = config.getInteger(CHECKPOINT_MODE, -1);
if (ordinal >= 0) {
return CheckpointingMode.values()[ordinal];
} else {
return DEFAULT_CHECKPOINTING_MODE;
}
}
public void setOutEdgesInOrder(List<StreamEdge> outEdgeList) {
try {
InstantiationUtil.writeObjectToConfig(outEdgeList, this.config, EDGES_IN_ORDER);
} catch (IOException e) {
throw new StreamTaskException("Could not serialize outputs in order.", e);
}
}
public List<StreamEdge> getOutEdgesInOrder(ClassLoader cl) {
try {
List<StreamEdge> outEdgesInOrder = InstantiationUtil.readObjectFromConfig(this.config, EDGES_IN_ORDER, cl);
return outEdgesInOrder == null ? new ArrayList<StreamEdge>() : outEdgesInOrder;
} catch (Exception e) {
throw new StreamTaskException("Could not instantiate outputs in order.", e);
}
}
public void setTransitiveChainedTaskConfigs(Map<Integer, StreamConfig> chainedTaskConfigs) {
try {
InstantiationUtil.writeObjectToConfig(chainedTaskConfigs, this.config, CHAINED_TASK_CONFIG);
} catch (IOException e) {
throw new StreamTaskException("Could not serialize configuration.", e);
}
}
public Map<Integer, StreamConfig> getTransitiveChainedTaskConfigs(ClassLoader cl) {
try {
Map<Integer, StreamConfig> confs = InstantiationUtil.readObjectFromConfig(this.config, CHAINED_TASK_CONFIG, cl);
return confs == null ? new HashMap<Integer, StreamConfig>() : confs;
} catch (Exception e) {
throw new StreamTaskException("Could not instantiate configuration.", e);
}
}
public Map<Integer, StreamConfig> getTransitiveChainedTaskConfigsWithSelf(ClassLoader cl) {
//TODO: could this logic be moved to the user of #setTransitiveChainedTaskConfigs() ?
Map<Integer, StreamConfig> chainedTaskConfigs = getTransitiveChainedTaskConfigs(cl);
chainedTaskConfigs.put(getVertexID(), this);
return chainedTaskConfigs;
}
public void setOperatorID(OperatorID operatorID) {
this.config.setBytes(OPERATOR_ID, operatorID.getBytes());
}
public OperatorID getOperatorID() {
byte[] operatorIDBytes = config.getBytes(OPERATOR_ID, null);
return new OperatorID(Preconditions.checkNotNull(operatorIDBytes));
}
public void setOperatorName(String name) {
this.config.setString(OPERATOR_NAME, name);
}
public String getOperatorName() {
return this.config.getString(OPERATOR_NAME, null);
}
public void setChainIndex(int index) {
this.config.setInteger(CHAIN_INDEX, index);
}
public int getChainIndex() {
return this.config.getInteger(CHAIN_INDEX, 0);
}
// ------------------------------------------------------------------------
// State backend
// ------------------------------------------------------------------------
public void setStateBackend(StateBackend backend) {
if (backend != null) {
try {
InstantiationUtil.writeObjectToConfig(backend, this.config, STATE_BACKEND);
} catch (Exception e) {
throw new StreamTaskException("Could not serialize stateHandle provider.", e);
}
}
}
public StateBackend getStateBackend(ClassLoader cl) {
try {
return InstantiationUtil.readObjectFromConfig(this.config, STATE_BACKEND, cl);
} catch (Exception e) {
throw new StreamTaskException("Could not instantiate statehandle provider.", e);
}
}
public byte[] getSerializedStateBackend() {
return this.config.getBytes(STATE_BACKEND, null);
}
public void setStatePartitioner(int input, KeySelector<?, ?> partitioner) {
try {
InstantiationUtil.writeObjectToConfig(partitioner, this.config, STATE_PARTITIONER + input);
} catch (IOException e) {
throw new StreamTaskException("Could not serialize state partitioner.", e);
}
}
public KeySelector<?, Serializable> getStatePartitioner(int input, ClassLoader cl) {
try {
return InstantiationUtil.readObjectFromConfig(this.config, STATE_PARTITIONER + input, cl);
} catch (Exception e) {
throw new StreamTaskException("Could not instantiate state partitioner.", e);
}
}
public void setStateKeySerializer(TypeSerializer<?> serializer) {
try {
InstantiationUtil.writeObjectToConfig(serializer, this.config, STATE_KEY_SERIALIZER);
} catch (IOException e) {
throw new StreamTaskException("Could not serialize state key serializer.", e);
}
}
public <K> TypeSerializer<K> getStateKeySerializer(ClassLoader cl) {
try {
return InstantiationUtil.readObjectFromConfig(this.config, STATE_KEY_SERIALIZER, cl);
} catch (Exception e) {
throw new StreamTaskException("Could not instantiate state key serializer from task config.", e);
}
}
// ------------------------------------------------------------------------
// Miscellaneous
// ------------------------------------------------------------------------
public void setChainStart() {
config.setBoolean(IS_CHAINED_VERTEX, true);
}
public boolean isChainStart() {
return config.getBoolean(IS_CHAINED_VERTEX, false);
}
public void setChainEnd() {
config.setBoolean(CHAIN_END, true);
}
public boolean isChainEnd() {
return config.getBoolean(CHAIN_END, false);
}
@Override
public String toString() {
ClassLoader cl = getClass().getClassLoader();
StringBuilder builder = new StringBuilder();
builder.append("\n=======================");
builder.append("Stream Config");
builder.append("=======================");
builder.append("\nNumber of non-chained inputs: ").append(getNumberOfInputs());
builder.append("\nNumber of non-chained outputs: ").append(getNumberOfOutputs());
builder.append("\nOutput names: ").append(getNonChainedOutputs(cl));
builder.append("\nPartitioning:");
for (StreamEdge output : getNonChainedOutputs(cl)) {
int outputname = output.getTargetId();
builder.append("\n\t").append(outputname).append(": ").append(output.getPartitioner());
}
builder.append("\nChained subtasks: ").append(getChainedOutputs(cl));
try {
builder.append("\nOperator: ").append(getStreamOperatorFactory(cl).getClass().getSimpleName());
}
catch (Exception e) {
builder.append("\nOperator: Missing");
}
builder.append("\nBuffer timeout: ").append(getBufferTimeout());
builder.append("\nState Monitoring: ").append(isCheckpointingEnabled());
if (isChainStart() && getChainedOutputs(cl).size() > 0) {
builder.append("\n\n\n---------------------\nChained task configs\n---------------------\n");
builder.append(getTransitiveChainedTaskConfigs(cl));
}
return builder.toString();
}
}
| fhueske/flink | flink-streaming-java/src/main/java/org/apache/flink/streaming/api/graph/StreamConfig.java | Java | apache-2.0 | 20,668 |
/**
* Licensed to Big Data Genomics (BDG) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The BDG licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.bdgenomics.convert.ga4gh;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertNotNull;
import org.bdgenomics.convert.Converter;
import org.bdgenomics.convert.ConversionException;
import org.bdgenomics.convert.ConversionStringency;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Unit test for Ga4ghStrandToBdgenomicsStrand.
*/
public final class Ga4ghStrandToBdgenomicsStrandTest {
private final Logger logger = LoggerFactory.getLogger(Ga4ghStrandToBdgenomicsStrandTest.class);
private Converter<ga4gh.Common.Strand, org.bdgenomics.formats.avro.Strand> strandConverter;
@Before
public void setUp() {
strandConverter = new Ga4ghStrandToBdgenomicsStrand();
}
@Test
public void testConstructor() {
assertNotNull(strandConverter);
}
@Test(expected=ConversionException.class)
public void testConvertNullStrict() {
strandConverter.convert(null, ConversionStringency.STRICT, logger);
}
@Test
public void testConvertNullLenient() {
assertNull(strandConverter.convert(null, ConversionStringency.LENIENT, logger));
}
@Test
public void testConvertNullSilent() {
assertNull(strandConverter.convert(null, ConversionStringency.SILENT, logger));
}
@Test
public void testConvert() {
assertEquals(org.bdgenomics.formats.avro.Strand.FORWARD, strandConverter.convert(ga4gh.Common.Strand.POS_STRAND, ConversionStringency.STRICT, logger));
assertEquals(org.bdgenomics.formats.avro.Strand.REVERSE, strandConverter.convert(ga4gh.Common.Strand.NEG_STRAND, ConversionStringency.STRICT, logger));
assertEquals(org.bdgenomics.formats.avro.Strand.INDEPENDENT, strandConverter.convert(ga4gh.Common.Strand.UNRECOGNIZED, ConversionStringency.STRICT, logger));
assertEquals(org.bdgenomics.formats.avro.Strand.UNKNOWN, strandConverter.convert(ga4gh.Common.Strand.STRAND_UNSPECIFIED, ConversionStringency.STRICT, logger));
}
}
| bigdatagenomics/bdg-convert | convert-ga4gh/src/test/java/org/bdgenomics/convert/ga4gh/Ga4ghStrandToBdgenomicsStrandTest.java | Java | apache-2.0 | 2,900 |
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.flex.compiler.internal.units.requests;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import org.apache.flex.compiler.definitions.IDefinition;
import org.apache.flex.compiler.internal.scopes.ASFileScope;
import org.apache.flex.compiler.problems.ICompilerProblem;
import org.apache.flex.compiler.scopes.IASScope;
import org.apache.flex.compiler.units.requests.IFileScopeRequestResult;
/**
* Base implementation of an {@link IFileScopeRequestResult}.
*/
public class FileScopeRequestResultBase implements IFileScopeRequestResult
{
private static IASScope[] EMPTY_SCOPES = new IASScope[0];
private static ASFileScope[] EMPTY_FILE_SCOPES = new ASFileScope[0];
private static Collection<ICompilerProblem> getProblemCollection(Collection<ICompilerProblem> problems)
{
if ((problems != null) && (!(problems.isEmpty())))
return problems;
return Collections.emptyList();
}
private static IASScope[] getScopesArray(Collection<? extends IASScope> scopes)
{
if ((scopes == null) || scopes.isEmpty())
return EMPTY_SCOPES;
return scopes.toArray(new IASScope[scopes.size()]);
}
private static ASFileScope[] getFileScopesArray(Collection<? extends IASScope> scopes)
{
if ((scopes == null) || scopes.isEmpty())
return EMPTY_FILE_SCOPES;
List<ASFileScope> fileScopes = new LinkedList<ASFileScope>();
for (IASScope scope : scopes)
{
if (scope instanceof ASFileScope)
fileScopes.add((ASFileScope)scope);
}
return fileScopes.toArray(new ASFileScope[fileScopes.size()]);
}
/**
* Create an immutable {@link IFileScopeRequestResult} object.
*
* @param problems All the compiler problems will be stored in this
* collection.
* @param scopes Top-level scopes in this request result. The public
* definitions in the scopes will be collected and stored in field
* {@code definitions}.
*/
public FileScopeRequestResultBase(Collection<ICompilerProblem> problems,
Collection<? extends IASScope> scopes)
{
this.problems = getProblemCollection(problems);
this.scopes = getScopesArray(scopes);
this.fileScopes = getFileScopesArray(scopes);
this.definitions = new HashSet<IDefinition>();
for (final ASFileScope scope : this.fileScopes)
scope.collectExternallyVisibleDefinitions(definitions, false);
}
private Collection<ICompilerProblem> problems;
private final IASScope[] scopes;
private final ASFileScope[] fileScopes;
/** All the public definitions in the given file scope. */
protected final Collection<IDefinition> definitions;
@Override
public ICompilerProblem[] getProblems()
{
return problems.toArray(new ICompilerProblem[problems.size()]);
}
@Override
public IASScope[] getScopes()
{
return scopes;
}
public ASFileScope[] getFileScopes()
{
return fileScopes;
}
@Override
public IDefinition getMainDefinition(String qname)
{
return null;
}
/**
* Get all the public definitions.
* @return public definitions
*/
@Override
public Collection<IDefinition> getExternallyVisibleDefinitions()
{
return definitions;
}
/**
* This method allows sub-classes to add problems to the problems collection
* after running this classes constructor.
* @param newProblems Collection of {@link ICompilerProblem}'s to add
* to the problems list for this result object.
*/
protected void addProblems(Collection<ICompilerProblem> newProblems)
{
// This looks goofy, but when the problems collection is empty
// is could be an immutable empty collections returned by
// Collections.emptyList or Collections.emptySet.
// This code ensures that we end up with a collection we can add to.
if (problems.isEmpty())
problems = new ArrayList<ICompilerProblem>(newProblems.size());
problems.addAll(newProblems);
}
@Override
public Collection<ICompilerProblem> checkExternallyVisibleDefinitions(String dottedQName)
{
// by default just return an empty list.
// sub-classes will override this method and return non-empty collections.
return Collections.emptyList();
}
}
| adufilie/flex-falcon | compiler/src/org/apache/flex/compiler/internal/units/requests/FileScopeRequestResultBase.java | Java | apache-2.0 | 5,427 |
package info.androidautobook.helloauto;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import java.util.Date;
public class MessageReadBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.d ( TAG, "onReceive()..." + new Date() ) ;
int referenceId = intent.getIntExtra("reference_id", -1);
if ( referenceId > 0 ) {
((NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE)).cancel( referenceId);
} else {
Log.w ( TAG, "onReceive() could not find notification to cancel " ) ;
}
}
private static final String TAG = MessageReadBroadcastReceiver.class.getName() ;
}
| smitzey/AndroidAutoTourGuide | apps/2helloAutoA_prod/app/src/main/java/info/androidautobook/helloauto/MessageReadBroadcastReceiver.java | Java | apache-2.0 | 856 |
package org.grobid.core.engines;
/**
* @author Slava
* Date: 4/3/14
*/
public enum SegmentationLabel {
/**
* cover page <cover>,
* document header <header>,
* page footer <footnote>,
* page header <headnote>,
* document body <body>,
* bibliographical section <references>,
* page number <page>,
* annexes <annex>,
* acknowledgement <acknowledgement>,
* toc <toc> -> not yet used because not yet training data for this
*/
COVER("<cover>"),
HEADER("<header>"),
FOOTNOTE("<footnote>"),
HEADNOTE("<headnote>"),
BODY("<body>"),
PAGE_NUMBER("<page>"),
ANNEX("<annex>"),
REFERENCES("<references>"),
ACKNOWLEDGEMENT("<acknowledgement>"),
TOC("toc");
private String label;
SegmentationLabel(String label) {
this.label = label;
}
public String getLabel() {
return label;
}
}
| k8si/grobid | grobid-core/src/main/java/org/grobid/core/engines/SegmentationLabel.java | Java | apache-2.0 | 892 |
/*
* The Alluxio Open Foundation licenses this work under the Apache License, version 2.0
* (the "License"). You may not use this work except in compliance with the License, which is
* available at www.apache.org/licenses/LICENSE-2.0
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied, as more fully set forth in the License.
*
* See the NOTICE file distributed with this work for information regarding copyright ownership.
*/
package alluxio.master.journal.raft;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import alluxio.conf.PropertyKey;
import alluxio.conf.ServerConfiguration;
import alluxio.proto.journal.File;
import alluxio.proto.journal.Journal;
import org.apache.ratis.protocol.ClientId;
import org.apache.ratis.protocol.Message;
import org.apache.ratis.protocol.RaftClientReply;
import org.apache.ratis.protocol.RaftGroupId;
import org.apache.ratis.protocol.RaftGroupMemberId;
import org.junit.After;
import org.junit.Test;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
/**
* Unit tests for {@link RaftJournalWriter}.
*/
public class RaftJournalWriterTest {
private LocalFirstRaftClient mClient;
private RaftJournalWriter mRaftJournalWriter;
@After
public void after() throws Exception {
ServerConfiguration.reset();
}
private void setupRaftJournalWriter() throws IOException {
mClient = mock(LocalFirstRaftClient.class);
RaftClientReply reply = new RaftClientReply(ClientId.randomId(),
RaftGroupMemberId.valueOf(RaftJournalUtils.getPeerId(new InetSocketAddress(1)),
RaftGroupId.valueOf(UUID.fromString("02511d47-d67c-49a3-9011-abb3109a44c1"))),
1L, true, Message.valueOf("mp"), null, 1L, null);
CompletableFuture<RaftClientReply> future = new CompletableFuture<RaftClientReply>() {
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
return false;
}
@Override
public boolean isCancelled() {
return false;
}
@Override
public boolean isDone() {
return false;
}
@Override
public RaftClientReply get() {
return reply;
}
@Override
public RaftClientReply get(long timeout, TimeUnit unit) {
return reply;
}
};
when(mClient.sendAsync(any(), any())).thenReturn(future);
mRaftJournalWriter = new RaftJournalWriter(1, mClient);
}
@Test
public void writeAndFlush() throws Exception {
setupRaftJournalWriter();
for (int i = 0; i < 10; i++) {
String alluxioMountPoint = "/tmp/to/file" + i;
String ufsPath = "hdfs://location/file" + i;
mRaftJournalWriter.write(Journal.JournalEntry.newBuilder()
.setAddMountPoint(File.AddMountPointEntry.newBuilder()
.setAlluxioPath(alluxioMountPoint)
.setUfsPath(ufsPath).build()).build());
}
verify(mClient, never()).sendAsync(any(), any());
mRaftJournalWriter.flush();
verify(mClient, times(1)).sendAsync(any(), any());
mRaftJournalWriter.flush();
verify(mClient, times(1)).sendAsync(any(), any());
mRaftJournalWriter.write(Journal.JournalEntry.getDefaultInstance());
mRaftJournalWriter.flush();
verify(mClient, times(2)).sendAsync(any(), any());
}
@Test
public void writeTriggerFlush() throws Exception {
int flushBatchSize = 128;
ServerConfiguration.set(PropertyKey.MASTER_EMBEDDED_JOURNAL_ENTRY_SIZE_MAX, flushBatchSize * 3);
setupRaftJournalWriter();
int totalMessageBytes = 0;
for (int i = 0; i < 10; i++) {
String alluxioMountPoint = "/tmp/to/file" + i;
String ufsPath = "hdfs://location/file" + i;
totalMessageBytes += alluxioMountPoint.getBytes().length;
totalMessageBytes += ufsPath.getBytes().length;
mRaftJournalWriter.write(Journal.JournalEntry.newBuilder()
.setAddMountPoint(File.AddMountPointEntry.newBuilder()
.setAlluxioPath(alluxioMountPoint)
.setUfsPath(ufsPath).build()).build());
}
mRaftJournalWriter.write(Journal.JournalEntry.getDefaultInstance());
verify(mClient, atLeast(totalMessageBytes / flushBatchSize)).sendAsync(any(), any());
}
}
| calvinjia/tachyon | core/server/common/src/test/java/alluxio/master/journal/raft/RaftJournalWriterTest.java | Java | apache-2.0 | 4,603 |
/*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.diff.tools.util;
import com.intellij.diff.DiffContext;
import com.intellij.diff.impl.DiffSettingsHolder.DiffSettings;
import com.intellij.diff.requests.DiffRequest;
import com.intellij.diff.tools.holders.BinaryEditorHolder;
import com.intellij.icons.AllIcons;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.fileEditor.FileEditor;
import com.intellij.openapi.fileEditor.FileEditorState;
import com.intellij.openapi.fileEditor.FileEditorStateLevel;
import com.intellij.openapi.fileEditor.TransferableFileEditorState;
import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.util.Condition;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.Key;
import com.intellij.ui.ToggleActionButton;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.awt.*;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class TransferableFileEditorStateSupport {
@NotNull private static final Key<MyState> TRANSFERABLE_FILE_EDITOR_STATE =
Key.create("Diff.TransferableFileEditorState");
private static final Condition<BinaryEditorHolder> IS_SUPPORTED = holder -> {
return getEditorState(holder.getEditor()) != null;
};
@NotNull private final DiffSettings mySettings;
@NotNull private final List<BinaryEditorHolder> myHolders;
@NotNull private final List<? extends FileEditor> myEditors;
private final boolean mySupported;
private int myMasterIndex = 0;
private boolean myDuringUpdate = true;
public TransferableFileEditorStateSupport(@NotNull DiffSettings settings,
@NotNull List<BinaryEditorHolder> holders,
@NotNull Disposable disposable) {
mySettings = settings;
myHolders = holders;
myEditors = ContainerUtil.map(ContainerUtil.filter(holders, IS_SUPPORTED), holder -> holder.getEditor());
mySupported = myEditors.size() > 0;
new MySynchronizer().install(disposable);
}
public boolean isSupported() {
return mySupported;
}
public boolean isEnabled() {
return mySettings.isSyncBinaryEditorSettings();
}
public void setEnabled(boolean enabled) {
mySettings.setSyncBinaryEditorSettings(enabled);
}
public void syncStatesNow() {
if (myEditors.size() < 2) return;
FileEditor masterEditor = myHolders.get(myMasterIndex).getEditor();
syncStateFrom(masterEditor);
}
@NotNull
public AnAction createToggleAction() {
return new ToggleSynchronousEditorStatesAction(this);
}
public void processContextHints(@NotNull DiffRequest request, @NotNull DiffContext context) {
myDuringUpdate = false;
if (!isEnabled()) return;
MyState state = context.getUserData(TRANSFERABLE_FILE_EDITOR_STATE);
if (state == null) return;
int newMasterIndex = state.getMasterIndex();
if (newMasterIndex < myHolders.size()) myMasterIndex = newMasterIndex;
try {
myDuringUpdate = true;
for (BinaryEditorHolder holder : myHolders) {
state.restoreContextData(holder.getEditor());
}
syncStatesNow();
}
finally {
myDuringUpdate = false;
}
}
public void updateContextHints(@NotNull DiffRequest request, @NotNull DiffContext context) {
if (!isEnabled()) return;
MyState state = new MyState(myMasterIndex);
context.putUserData(TRANSFERABLE_FILE_EDITOR_STATE, state);
// master editor has priority
state.storeContextData(myHolders.get(myMasterIndex).getEditor());
for (BinaryEditorHolder holder : myHolders) {
state.storeContextData(holder.getEditor());
}
}
private class MySynchronizer implements PropertyChangeListener {
public void install(@NotNull Disposable disposable) {
if (myEditors.size() < 2) return;
for (FileEditor editor : myEditors) {
editor.addPropertyChangeListener(this);
}
Disposer.register(disposable, new Disposable() {
@Override
public void dispose() {
for (FileEditor editor : myEditors) {
editor.removePropertyChangeListener(MySynchronizer.this);
}
}
});
}
@Override
public void propertyChange(PropertyChangeEvent evt) {
if (myDuringUpdate || !isEnabled()) return;
if (!(evt.getSource() instanceof FileEditor)) return;
FileEditor editor = (FileEditor)evt.getSource();
if (!editor.getComponent().isShowing()) return;
Dimension size = editor.getComponent().getSize();
if (size.width <= 0 || size.height <= 0) return;
int holderIndex = ContainerUtil.indexOf(myHolders, (Condition<BinaryEditorHolder>)holder -> editor.equals(holder.getEditor()));
if (holderIndex != -1) myMasterIndex = holderIndex;
syncStateFrom(editor);
}
}
private void syncStateFrom(@NotNull FileEditor sourceEditor) {
TransferableFileEditorState sourceState = getEditorState(sourceEditor);
if (sourceState == null) return;
Map<String, String> options = sourceState.getTransferableOptions();
String id = sourceState.getEditorId();
for (FileEditor editor : myEditors) {
if (sourceEditor != editor) {
updateEditor(editor, id, options);
}
}
}
private void updateEditor(@NotNull FileEditor editor, @NotNull String id, @NotNull Map<String, String> options) {
try {
myDuringUpdate = true;
TransferableFileEditorState state = getEditorState(editor);
if (state != null && state.getEditorId().equals(id)) {
state.setTransferableOptions(options);
state.setCopiedFromMasterEditor();
editor.setState(state);
}
}
finally {
myDuringUpdate = false;
}
}
@Nullable
private static TransferableFileEditorState getEditorState(@NotNull FileEditor editor) {
FileEditorState state = editor.getState(FileEditorStateLevel.FULL);
return state instanceof TransferableFileEditorState ? (TransferableFileEditorState)state : null;
}
private static class ToggleSynchronousEditorStatesAction extends ToggleActionButton implements DumbAware {
@NotNull private final TransferableFileEditorStateSupport mySupport;
public ToggleSynchronousEditorStatesAction(@NotNull TransferableFileEditorStateSupport support) {
super("Synchronize Editors Settings", AllIcons.Actions.SyncPanels);
mySupport = support;
}
@Override
public boolean isVisible() {
return mySupport.isSupported();
}
@Override
public boolean isSelected(AnActionEvent e) {
return mySupport.isEnabled();
}
@Override
public void setSelected(AnActionEvent e, boolean state) {
mySupport.setEnabled(state);
if (state) {
mySupport.syncStatesNow();
}
}
}
private static class MyState {
private final Map<String, Map<String, String>> myMap = new HashMap<>();
private final int myMasterIndex;
public MyState(int masterIndex) {
myMasterIndex = masterIndex;
}
public int getMasterIndex() {
return myMasterIndex;
}
public void restoreContextData(@NotNull FileEditor editor) {
TransferableFileEditorState editorState = getEditorState(editor);
if (editorState == null) return;
Map<String, String> options = myMap.get(editorState.getEditorId());
if (options == null) return;
editorState.setTransferableOptions(options);
editor.setState(editorState);
}
public void storeContextData(@NotNull FileEditor editor) {
TransferableFileEditorState editorState = getEditorState(editor);
if (editorState == null) return;
if (!myMap.containsKey(editorState.getEditorId())) {
myMap.put(editorState.getEditorId(), editorState.getTransferableOptions());
}
}
}
}
| jk1/intellij-community | platform/diff-impl/src/com/intellij/diff/tools/util/TransferableFileEditorStateSupport.java | Java | apache-2.0 | 8,668 |
package io.muoncore.transport.client;
import io.muoncore.channel.Dispatcher;
import io.muoncore.channel.Dispatchers;
import io.muoncore.message.MuonMessage;
import org.reactivestreams.Publisher;
import org.reactivestreams.Subscription;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.function.Predicate;
public class SimpleTransportMessageDispatcher implements TransportMessageDispatcher {
private List<QueuePredicate> queues = new ArrayList<>();
private Dispatcher dispatcher = Dispatchers.dispatcher();
private static final MuonMessage POISON = new MuonMessage(null, 0, null, null, null, null, null, null,null,null, null);
@Override
public void dispatch(MuonMessage message) {
dispatcher.dispatch(message, m ->
queues.stream().forEach(msg -> msg.add(m)), Throwable::printStackTrace);
}
@Override
public void shutdown() {
dispatch(POISON);
}
@Override
public Publisher<MuonMessage> observe(Predicate<MuonMessage> filter) {
LinkedBlockingQueue<MuonMessage> queue = new LinkedBlockingQueue<>();
QueuePredicate wrapper = new QueuePredicate(queue, filter);
queues.add(wrapper);
return s -> s.onSubscribe(new Subscription() {
@Override
public void request(long n) {
Dispatchers.poolDispatcher().dispatch(null, ev -> {
for (int i = 0; i < n; i++) {
try {
MuonMessage msg = queue.take();
if (msg == POISON) {
s.onComplete();
return;
} else {
s.onNext(msg);
}
} catch (InterruptedException e) {
s.onError(e);
}
}
}, throwable -> {});
}
@Override
public void cancel() {
queues.remove(wrapper);
queue.clear();
}
});
}
static class QueuePredicate {
private Queue<MuonMessage> queue;
private Predicate<MuonMessage> predicate;
public QueuePredicate(Queue<MuonMessage> queue, Predicate<MuonMessage> predicate) {
this.queue = queue;
this.predicate = predicate;
}
public void add(MuonMessage msg) {
if (msg == null) return;
if (predicate.test(msg)) {
queue.add(msg);
}
}
}
}
| microserviceux/muon-java | muon-core/src/main/java/io/muoncore/transport/client/SimpleTransportMessageDispatcher.java | Java | apache-2.0 | 2,705 |
package tdl.client.queue;
public interface ImplementationRunner {
void run();
}
| julianghionoiu/tdl-client-java | src/main/java/tdl/client/queue/ImplementationRunner.java | Java | apache-2.0 | 85 |
package bboss.org.apache.velocity.runtime;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import bboss.org.apache.velocity.Template;
import bboss.org.apache.velocity.app.event.EventCartridge;
import bboss.org.apache.velocity.context.Context;
import bboss.org.apache.velocity.exception.MethodInvocationException;
import bboss.org.apache.velocity.exception.ParseErrorException;
import bboss.org.apache.velocity.exception.ResourceNotFoundException;
import bboss.org.apache.velocity.runtime.directive.Directive;
import bboss.org.apache.velocity.runtime.log.Log;
import bboss.org.apache.velocity.runtime.parser.ParseException;
import bboss.org.apache.velocity.runtime.parser.Parser;
import bboss.org.apache.velocity.runtime.parser.node.Node;
import bboss.org.apache.velocity.runtime.parser.node.SimpleNode;
import bboss.org.apache.velocity.runtime.resource.ContentResource;
import bboss.org.apache.velocity.util.introspection.Introspector;
import bboss.org.apache.velocity.util.introspection.Uberspect;
import org.apache.commons.collections.ExtendedProperties;
import java.io.Reader;
import java.io.Writer;
import java.util.Properties;
/**
* Interface for internal runtime services that are needed by the
* various components w/in Velocity. This was taken from the old
* Runtime singleton, and anything not necessary was removed.
*
* Currently implemented by RuntimeInstance.
*
* @author <a href="mailto:[email protected]">Geir Magusson Jr.</a>
* @version $Id: RuntimeServices.java 898050 2010-01-11 20:15:31Z nbubna $
*/
public interface RuntimeServices extends RuntimeLogger
{
/**
* This is the primary initialization method in the Velocity
* Runtime. The systems that are setup/initialized here are
* as follows:
*
* <ul>
* <li>Logging System</li>
* <li>ResourceManager</li>
* <li>Parser Pool</li>
* <li>Global Cache</li>
* <li>Static Content Include System</li>
* <li>Velocimacro System</li>
* </ul>
*/
public void init();
/**
* Allows an external system to set a property in
* the Velocity Runtime.
*
* @param key property key
* @param value property value
*/
public void setProperty(String key, Object value);
/**
* Allow an external system to set an ExtendedProperties
* object to use. This is useful where the external
* system also uses the ExtendedProperties class and
* the velocity configuration is a subset of
* parent application's configuration. This is
* the case with Turbine.
*
* @param configuration
*/
public void setConfiguration( ExtendedProperties configuration);
/**
* Add a property to the configuration. If it already
* exists then the value stated here will be added
* to the configuration entry. For example, if
*
* resource.loader = file
*
* is already present in the configuration and you
*
* addProperty("resource.loader", "classpath")
*
* Then you will end up with a Vector like the
* following:
*
* ["file", "classpath"]
*
* @param key
* @param value
*/
public void addProperty(String key, Object value);
/**
* Clear the values pertaining to a particular
* property.
*
* @param key of property to clear
*/
public void clearProperty(String key);
/**
* Allows an external caller to get a property. The calling
* routine is required to know the type, as this routine
* will return an Object, as that is what properties can be.
*
* @param key property to return
* @return The value.
*/
public Object getProperty( String key );
/**
* Initialize the Velocity Runtime with a Properties
* object.
*
* @param p
*/
public void init(Properties p);
/**
* Initialize the Velocity Runtime with the name of
* ExtendedProperties object.
*
* @param configurationFile
*/
public void init(String configurationFile);
/**
* Wraps the String in a StringReader and passes it off to
* {@link #parse(Reader,String)}.
* @since 1.6
*/
public SimpleNode parse(String string, String templateName)
throws ParseException;
/**
* Parse the input and return the root of
* AST node structure.
* <br><br>
* In the event that it runs out of parsers in the
* pool, it will create and let them be GC'd
* dynamically, logging that it has to do that. This
* is considered an exceptional condition. It is
* expected that the user will set the
* PARSER_POOL_SIZE property appropriately for their
* application. We will revisit this.
*
* @param reader inputstream retrieved by a resource loader
* @param templateName name of the template being parsed
* @return The AST representing the template.
* @throws ParseException
*/
public SimpleNode parse( Reader reader, String templateName )
throws ParseException;
/**
* Parse the input and return the root of the AST node structure.
*
* @param reader inputstream retrieved by a resource loader
* @param templateName name of the template being parsed
* @param dumpNamespace flag to dump the Velocimacro namespace for this template
* @return The AST representing the template.
* @throws ParseException
*/
public SimpleNode parse( Reader reader, String templateName, boolean dumpNamespace )
throws ParseException;
/**
* Renders the input string using the context into the output writer.
* To be used when a template is dynamically constructed, or want to use
* Velocity as a token replacer.
*
* @param context context to use in rendering input string
* @param out Writer in which to render the output
* @param logTag string to be used as the template name for log
* messages in case of error
* @param instring input string containing the VTL to be rendered
*
* @return true if successful, false otherwise. If false, see
* Velocity runtime log
* @throws ParseErrorException The template could not be parsed.
* @throws MethodInvocationException A method on a context object could not be invoked.
* @throws ResourceNotFoundException A referenced resource could not be loaded.
* @since Velocity 1.6
*/
public boolean evaluate(Context context, Writer out,
String logTag, String instring);
/**
* Renders the input reader using the context into the output writer.
* To be used when a template is dynamically constructed, or want to
* use Velocity as a token replacer.
*
* @param context context to use in rendering input string
* @param writer Writer in which to render the output
* @param logTag string to be used as the template name for log messages
* in case of error
* @param reader Reader containing the VTL to be rendered
*
* @return true if successful, false otherwise. If false, see
* Velocity runtime log
* @throws ParseErrorException The template could not be parsed.
* @throws MethodInvocationException A method on a context object could not be invoked.
* @throws ResourceNotFoundException A referenced resource could not be loaded.
* @since Velocity 1.6
*/
public boolean evaluate(Context context, Writer writer,
String logTag, Reader reader);
/**
* Invokes a currently registered Velocimacro with the params provided
* and places the rendered stream into the writer.
* <br>
* Note : currently only accepts args to the VM if they are in the context.
*
* @param vmName name of Velocimacro to call
* @param logTag string to be used for template name in case of error. if null,
* the vmName will be used
* @param params keys for args used to invoke Velocimacro, in java format
* rather than VTL (eg "foo" or "bar" rather than "$foo" or "$bar")
* @param context Context object containing data/objects used for rendering.
* @param writer Writer for output stream
* @return true if Velocimacro exists and successfully invoked, false otherwise.
* @since 1.6
*/
public boolean invokeVelocimacro(final String vmName, String logTag,
String[] params, final Context context,
final Writer writer);
/**
* Returns a <code>Template</code> from the resource manager.
* This method assumes that the character encoding of the
* template is set by the <code>input.encoding</code>
* property. The default is "ISO-8859-1"
*
* @param name The file name of the desired template.
* @return The template.
* @throws ResourceNotFoundException if template not found
* from any available source.
* @throws ParseErrorException if template cannot be parsed due
* to syntax (or other) error.
*/
public Template getTemplate(String name)
throws ResourceNotFoundException, ParseErrorException;
/**
* Returns a <code>Template</code> from the resource manager
*
* @param name The name of the desired template.
* @param encoding Character encoding of the template
* @return The template.
* @throws ResourceNotFoundException if template not found
* from any available source.
* @throws ParseErrorException if template cannot be parsed due
* to syntax (or other) error.
*/
public Template getTemplate(String name, String encoding)
throws ResourceNotFoundException, ParseErrorException;
/**
* Returns a static content resource from the
* resource manager. Uses the current value
* if INPUT_ENCODING as the character encoding.
*
* @param name Name of content resource to get
* @return parsed ContentResource object ready for use
* @throws ResourceNotFoundException if template not found
* from any available source.
* @throws ParseErrorException
*/
public ContentResource getContent(String name)
throws ResourceNotFoundException, ParseErrorException;
/**
* Returns a static content resource from the
* resource manager.
*
* @param name Name of content resource to get
* @param encoding Character encoding to use
* @return parsed ContentResource object ready for use
* @throws ResourceNotFoundException if template not found
* from any available source.
* @throws ParseErrorException
*/
public ContentResource getContent( String name, String encoding )
throws ResourceNotFoundException, ParseErrorException;
/**
* Determines is a template exists, and returns name of the loader that
* provides it. This is a slightly less hokey way to support
* the Velocity.templateExists() utility method, which was broken
* when per-template encoding was introduced. We can revisit this.
*
* @param resourceName Name of template or content resource
* @return class name of loader than can provide it
*/
public String getLoaderNameForResource( String resourceName );
/**
* String property accessor method with default to hide the
* configuration implementation.
*
* @param key property key
* @param defaultValue default value to return if key not
* found in resource manager.
* @return String value of key or default
*/
public String getString( String key, String defaultValue);
/**
* Returns the appropriate VelocimacroProxy object if strVMname
* is a valid current Velocimacro.
*
* @param vmName Name of velocimacro requested
* @param templateName Name of the namespace.
* @return VelocimacroProxy
*/
public Directive getVelocimacro( String vmName, String templateName );
/**
* Returns the appropriate VelocimacroProxy object if strVMname
* is a valid current Velocimacro.
*
* @param vmName Name of velocimacro requested
* @param templateName Name of the namespace.
* @param renderingTemplate Name of the template we are currently rendering. This
* information is needed when VM_PERM_ALLOW_INLINE_REPLACE_GLOBAL setting is true
* and template contains a macro with the same name as the global macro library.
*
* @since Velocity 1.6
*
* @return VelocimacroProxy
*/
public Directive getVelocimacro( String vmName, String templateName, String renderingTemplate );
/**
* Adds a new Velocimacro. Usually called by Macro only while parsing.
*
* @param name Name of velocimacro
* @param macro String form of macro body
* @param argArray Array of strings, containing the
* #macro() arguments. the 0th is the name.
* @param sourceTemplate
*
* @deprecated Use addVelocimacro(String, Node, String[], String) instead
*
* @return boolean True if added, false if rejected for some
* reason (either parameters or permission settings)
*/
public boolean addVelocimacro( String name,
String macro,
String argArray[],
String sourceTemplate );
/**
* Adds a new Velocimacro. Usually called by Macro only while parsing.
*
* @param name Name of velocimacro
* @param macro root AST node of the parsed macro
* @param argArray Array of strings, containing the
* #macro() arguments. the 0th is the name.
* @param sourceTemplate
*
* @since Velocity 1.6
*
* @return boolean True if added, false if rejected for some
* reason (either parameters or permission settings)
*/
public boolean addVelocimacro( String name,
Node macro,
String argArray[],
String sourceTemplate );
/**
* Checks to see if a VM exists
*
* @param vmName Name of velocimacro
* @param templateName
* @return boolean True if VM by that name exists, false if not
*/
public boolean isVelocimacro( String vmName, String templateName );
/**
* tells the vmFactory to dump the specified namespace. This is to support
* clearing the VM list when in inline-VM-local-scope mode
* @param namespace
* @return True if the Namespace was dumped.
*/
public boolean dumpVMNamespace( String namespace );
/**
* String property accessor method to hide the configuration implementation
* @param key property key
* @return value of key or null
*/
public String getString(String key);
/**
* Int property accessor method to hide the configuration implementation.
*
* @param key property key
* @return int value
*/
public int getInt( String key );
/**
* Int property accessor method to hide the configuration implementation.
*
* @param key property key
* @param defaultValue default value
* @return int value
*/
public int getInt( String key, int defaultValue );
/**
* Boolean property accessor method to hide the configuration implementation.
*
* @param key property key
* @param def default default value if property not found
* @return boolean value of key or default value
*/
public boolean getBoolean( String key, boolean def );
/**
* Return the velocity runtime configuration object.
*
* @return ExtendedProperties configuration object which houses
* the velocity runtime properties.
*/
public ExtendedProperties getConfiguration();
/**
* Return the specified application attribute.
*
* @param key The name of the attribute to retrieve.
* @return The value of the attribute.
*/
public Object getApplicationAttribute( Object key );
/**
* Set the specified application attribute.
*
* @param key The name of the attribute to set.
* @param value The attribute value to set.
* @return the displaced attribute value
*/
public Object setApplicationAttribute( Object key, Object value );
/**
* Returns the configured class introspection/reflection
* implementation.
* @return The current Uberspect object.
*/
public Uberspect getUberspect();
/**
* Returns a convenient Log instance that wraps the current LogChute.
* @return A log object.
*/
public Log getLog();
/**
* Returns the event handlers for the application.
* @return The event handlers for the application.
*/
public EventCartridge getApplicationEventCartridge();
/**
* Returns the configured method introspection/reflection
* implementation.
* @return The configured method introspection/reflection
* implementation.
*/
public Introspector getIntrospector();
/**
* Returns true if the RuntimeInstance has been successfully initialized.
* @return True if the RuntimeInstance has been successfully initialized.
*/
public boolean isInitialized();
/**
* Create a new parser instance.
* @return A new parser instance.
*/
public Parser createNewParser();
/**
* Retrieve a previously instantiated directive.
* @param name name of the directive
* @return the directive with that name, if any
* @since 1.6
*/
public Directive getDirective(String name);
}
| bbossgroups/bbossgroups-3.5 | bboss-velocity/src-velocity/bboss/org/apache/velocity/runtime/RuntimeServices.java | Java | apache-2.0 | 18,983 |
package ca.uhn.fhir.jpa.provider.r4;
import ca.uhn.fhir.jpa.api.model.DaoMethodOutcome;
import ca.uhn.fhir.jpa.dao.r4.FhirResourceDaoR4TerminologyTest;
import ca.uhn.fhir.jpa.model.entity.ResourceTable;
import ca.uhn.fhir.jpa.model.util.JpaConstants;
import ca.uhn.fhir.rest.server.exceptions.InvalidRequestException;
import ca.uhn.fhir.rest.server.exceptions.ResourceNotFoundException;
import org.apache.commons.io.IOUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.hl7.fhir.r4.model.BooleanType;
import org.hl7.fhir.r4.model.CodeSystem;
import org.hl7.fhir.r4.model.CodeType;
import org.hl7.fhir.r4.model.Coding;
import org.hl7.fhir.r4.model.Enumerations;
import org.hl7.fhir.r4.model.Parameters;
import org.hl7.fhir.r4.model.StringType;
import org.hl7.fhir.r4.model.UriType;
import org.hl7.fhir.r4.model.codesystems.ConceptSubsumptionOutcome;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.transaction.annotation.Transactional;
import java.io.IOException;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.fail;
public class ResourceProviderR4CodeSystemVersionedTest extends BaseResourceProviderR4Test {
private static final String SYSTEM_PARENTCHILD = "http://parentchild";
private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(ResourceProviderR4CodeSystemVersionedTest.class);
private long parentChildCs1Id;
private long parentChildCs2Id;
@BeforeEach
@Transactional
public void before02() throws IOException {
CodeSystem cs = loadResourceFromClasspath(CodeSystem.class, "/extensional-case-3-cs.xml");
cs.setVersion("1");
for(CodeSystem.ConceptDefinitionComponent conceptDefinitionComponent : cs.getConcept()) {
conceptDefinitionComponent.setDisplay(conceptDefinitionComponent.getDisplay() + " v1");
}
myCodeSystemDao.create(cs, mySrd);
cs = loadResourceFromClasspath(CodeSystem.class, "/extensional-case-3-cs.xml");
cs.setVersion("2");
for(CodeSystem.ConceptDefinitionComponent conceptDefinitionComponent : cs.getConcept()) {
conceptDefinitionComponent.setDisplay(conceptDefinitionComponent.getDisplay() + " v2");
}
myCodeSystemDao.create(cs, mySrd);
CodeSystem parentChildCs = new CodeSystem();
parentChildCs.setUrl(SYSTEM_PARENTCHILD);
parentChildCs.setVersion("1");
parentChildCs.setName("Parent Child CodeSystem 1");
parentChildCs.setStatus(Enumerations.PublicationStatus.ACTIVE);
parentChildCs.setContent(CodeSystem.CodeSystemContentMode.COMPLETE);
parentChildCs.setHierarchyMeaning(CodeSystem.CodeSystemHierarchyMeaning.ISA);
CodeSystem.ConceptDefinitionComponent parentA = parentChildCs.addConcept().setCode("ParentA").setDisplay("Parent A");
parentA.addConcept().setCode("ChildAA").setDisplay("Child AA");
parentA.addConcept().setCode("ParentC").setDisplay("Parent C");
parentChildCs.addConcept().setCode("ParentB").setDisplay("Parent B");
DaoMethodOutcome parentChildCsOutcome = myCodeSystemDao.create(parentChildCs);
parentChildCs1Id = ((ResourceTable)parentChildCsOutcome.getEntity()).getId();
parentChildCs = new CodeSystem();
parentChildCs.setVersion("2");
parentChildCs.setName("Parent Child CodeSystem 2");
parentChildCs.setUrl(SYSTEM_PARENTCHILD);
parentChildCs.setStatus(Enumerations.PublicationStatus.ACTIVE);
parentChildCs.setContent(CodeSystem.CodeSystemContentMode.COMPLETE);
parentChildCs.setHierarchyMeaning(CodeSystem.CodeSystemHierarchyMeaning.ISA);
parentA = parentChildCs.addConcept().setCode("ParentA").setDisplay("Parent A v2");
parentA.addConcept().setCode("ChildAA").setDisplay("Child AA v2");
parentA.addConcept().setCode("ParentB").setDisplay("Parent B v2");
parentChildCs.addConcept().setCode("ParentC").setDisplay("Parent C v2");
parentChildCsOutcome = myCodeSystemDao.create(parentChildCs);
parentChildCs2Id = ((ResourceTable)parentChildCsOutcome.getEntity()).getId();
}
@Test
public void testLookupOnExternalCodeMultiVersion() {
runInTransaction(()->{
ResourceProviderR4ValueSetVerCSVerTest.createExternalCs(myCodeSystemDao, myResourceTableDao, myTermCodeSystemStorageSvc, mySrd, "1");
ResourceProviderR4ValueSetVerCSVerTest.createExternalCs(myCodeSystemDao, myResourceTableDao, myTermCodeSystemStorageSvc, mySrd, "2");
});
// First test with no version specified (should return from last version created)
Parameters respParam = myClient
.operation()
.onType(CodeSystem.class)
.named("lookup")
.withParameter(Parameters.class, "code", new CodeType("ParentA"))
.andParameter("system", new UriType(FhirResourceDaoR4TerminologyTest.URL_MY_CODE_SYSTEM))
.execute();
String resp = myFhirCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(respParam);
ourLog.info(resp);
assertEquals("name", respParam.getParameter().get(0).getName());
assertEquals("SYSTEM NAME", ((StringType) respParam.getParameter().get(0).getValue()).getValue());
assertEquals("version", respParam.getParameter().get(1).getName());
assertEquals("2", ((StringType) respParam.getParameter().get(1).getValue()).getValue());
assertEquals("display", respParam.getParameter().get(2).getName());
assertEquals("Parent A2", ((StringType) respParam.getParameter().get(2).getValue()).getValue());
assertEquals("abstract", respParam.getParameter().get(3).getName());
assertEquals(false, ((BooleanType) respParam.getParameter().get(3).getValue()).getValue());
// With HTTP GET
respParam = myClient
.operation()
.onType(CodeSystem.class)
.named("lookup")
.withParameter(Parameters.class, "code", new CodeType("ParentA"))
.andParameter("system", new UriType(FhirResourceDaoR4TerminologyTest.URL_MY_CODE_SYSTEM))
.useHttpGet()
.execute();
resp = myFhirCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(respParam);
ourLog.info(resp);
assertEquals("name", respParam.getParameter().get(0).getName());
assertEquals(("SYSTEM NAME"), ((StringType) respParam.getParameter().get(0).getValue()).getValue());
assertEquals("version", respParam.getParameter().get(1).getName());
assertEquals(("2"), ((StringType) respParam.getParameter().get(1).getValue()).getValue());
assertEquals("display", respParam.getParameter().get(2).getName());
assertEquals("Parent A2", ((StringType) respParam.getParameter().get(2).getValue()).getValue());
assertEquals("abstract", respParam.getParameter().get(3).getName());
assertEquals(false, ((BooleanType) respParam.getParameter().get(3).getValue()).getValue());
// Test with version 1 specified.
respParam = myClient
.operation()
.onType(CodeSystem.class)
.named("lookup")
.withParameter(Parameters.class, "code", new CodeType("ParentA"))
.andParameter("system", new UriType(FhirResourceDaoR4TerminologyTest.URL_MY_CODE_SYSTEM))
.andParameter("version", new StringType("1"))
.execute();
resp = myFhirCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(respParam);
ourLog.info(resp);
assertEquals("name", respParam.getParameter().get(0).getName());
assertEquals("SYSTEM NAME", ((StringType) respParam.getParameter().get(0).getValue()).getValue());
assertEquals("version", respParam.getParameter().get(1).getName());
assertEquals("1", ((StringType) respParam.getParameter().get(1).getValue()).getValue());
assertEquals("display", respParam.getParameter().get(2).getName());
assertEquals("Parent A1", ((StringType) respParam.getParameter().get(2).getValue()).getValue());
assertEquals("abstract", respParam.getParameter().get(3).getName());
assertEquals(false, ((BooleanType) respParam.getParameter().get(3).getValue()).getValue());
// With HTTP GET
respParam = myClient
.operation()
.onType(CodeSystem.class)
.named("lookup")
.withParameter(Parameters.class, "code", new CodeType("ParentA"))
.andParameter("system", new UriType(FhirResourceDaoR4TerminologyTest.URL_MY_CODE_SYSTEM))
.andParameter("version", new StringType("1"))
.useHttpGet()
.execute();
resp = myFhirCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(respParam);
ourLog.info(resp);
assertEquals("name", respParam.getParameter().get(0).getName());
assertEquals(("SYSTEM NAME"), ((StringType) respParam.getParameter().get(0).getValue()).getValue());
assertEquals("version", respParam.getParameter().get(1).getName());
assertEquals(("1"), ((StringType) respParam.getParameter().get(1).getValue()).getValue());
assertEquals("display", respParam.getParameter().get(2).getName());
assertEquals("Parent A1", ((StringType) respParam.getParameter().get(2).getValue()).getValue());
assertEquals("abstract", respParam.getParameter().get(3).getName());
assertEquals(false, ((BooleanType) respParam.getParameter().get(3).getValue()).getValue());
// Test with version 2 specified.
respParam = myClient
.operation()
.onType(CodeSystem.class)
.named("lookup")
.withParameter(Parameters.class, "code", new CodeType("ParentA"))
.andParameter("system", new UriType(FhirResourceDaoR4TerminologyTest.URL_MY_CODE_SYSTEM))
.andParameter("version", new StringType("2"))
.execute();
resp = myFhirCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(respParam);
ourLog.info(resp);
assertEquals("name", respParam.getParameter().get(0).getName());
assertEquals("SYSTEM NAME", ((StringType) respParam.getParameter().get(0).getValue()).getValue());
assertEquals("version", respParam.getParameter().get(1).getName());
assertEquals("2", ((StringType) respParam.getParameter().get(1).getValue()).getValue());
assertEquals("display", respParam.getParameter().get(2).getName());
assertEquals("Parent A2", ((StringType) respParam.getParameter().get(2).getValue()).getValue());
assertEquals("abstract", respParam.getParameter().get(3).getName());
assertEquals(false, ((BooleanType) respParam.getParameter().get(3).getValue()).getValue());
// With HTTP GET
respParam = myClient
.operation()
.onType(CodeSystem.class)
.named("lookup")
.withParameter(Parameters.class, "code", new CodeType("ParentA"))
.andParameter("system", new UriType(FhirResourceDaoR4TerminologyTest.URL_MY_CODE_SYSTEM))
.andParameter("version", new StringType("2"))
.useHttpGet()
.execute();
resp = myFhirCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(respParam);
ourLog.info(resp);
assertEquals("name", respParam.getParameter().get(0).getName());
assertEquals(("SYSTEM NAME"), ((StringType) respParam.getParameter().get(0).getValue()).getValue());
assertEquals("version", respParam.getParameter().get(1).getName());
assertEquals(("2"), ((StringType) respParam.getParameter().get(1).getValue()).getValue());
assertEquals("display", respParam.getParameter().get(2).getName());
assertEquals("Parent A2", ((StringType) respParam.getParameter().get(2).getValue()).getValue());
assertEquals("abstract", respParam.getParameter().get(3).getName());
assertEquals(false, ((BooleanType) respParam.getParameter().get(3).getValue()).getValue());
}
@Test
public void testLookupOperationByCodeAndSystemBuiltInCode() {
// First test with no version specified (should return the one and only version defined).
Parameters respParam = myClient
.operation()
.onType(CodeSystem.class)
.named("lookup")
.withParameter(Parameters.class, "code", new CodeType("ACSN"))
.andParameter("system", new UriType("http://terminology.hl7.org/CodeSystem/v2-0203"))
.execute();
String resp = myFhirCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(respParam);
ourLog.info(resp);
assertEquals("name", respParam.getParameter().get(0).getName());
assertEquals("v2.0203", ((StringType) respParam.getParameter().get(0).getValue()).getValue());
assertEquals("version", respParam.getParameter().get(1).getName());
assertEquals("2.9", ((StringType) respParam.getParameter().get(1).getValue()).getValue());
assertEquals("display", respParam.getParameter().get(2).getName());
assertEquals("Accession ID", ((StringType) respParam.getParameter().get(2).getValue()).getValue());
assertEquals("abstract", respParam.getParameter().get(3).getName());
assertEquals(false, ((BooleanType) respParam.getParameter().get(3).getValue()).getValue());
// Repeat with version specified.
respParam = myClient
.operation()
.onType(CodeSystem.class)
.named("lookup")
.withParameter(Parameters.class, "code", new CodeType("ACSN"))
.andParameter("system", new UriType("http://terminology.hl7.org/CodeSystem/v2-0203"))
.andParameter("version", new StringType("2.9"))
.execute();
resp = myFhirCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(respParam);
ourLog.info(resp);
assertEquals("name", respParam.getParameter().get(0).getName());
assertEquals("v2.0203", ((StringType) respParam.getParameter().get(0).getValue()).getValue());
assertEquals("version", respParam.getParameter().get(1).getName());
assertEquals("2.9", ((StringType) respParam.getParameter().get(1).getValue()).getValue());
assertEquals("display", respParam.getParameter().get(2).getName());
assertEquals("Accession ID", ((StringType) respParam.getParameter().get(2).getValue()).getValue());
assertEquals("abstract", respParam.getParameter().get(3).getName());
assertEquals(false, ((BooleanType) respParam.getParameter().get(3).getValue()).getValue());
}
@Test
public void testLookupOperationByCodeAndSystemBuiltInNonexistentVersion() {
try {
myClient
.operation()
.onType(CodeSystem.class)
.named("lookup")
.withParameter(Parameters.class, "code", new CodeType("ACSN"))
.andParameter("system", new UriType("http://hl7.org/fhir/v2/0203"))
.andParameter("version", new StringType("2.8"))
.execute();
fail();
} catch (ResourceNotFoundException e) {
ourLog.info("Lookup failed as expected");
}
}
@Test
public void testLookupOperationByCodeAndSystemUserDefinedCode() {
// First test with no version specified (should return from last version created)
Parameters respParam = myClient
.operation()
.onType(CodeSystem.class)
.named("lookup")
.withParameter(Parameters.class, "code", new CodeType("8450-9"))
.andParameter("system", new UriType("http://acme.org"))
.execute();
String resp = myFhirCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(respParam);
ourLog.info(resp);
assertEquals("name", respParam.getParameter().get(0).getName());
assertEquals(("ACME Codes"), ((StringType) respParam.getParameter().get(0).getValue()).getValue());
assertEquals("version", respParam.getParameter().get(1).getName());
assertEquals("2", ((StringType) respParam.getParameter().get(1).getValue()).getValue());
assertEquals("display", respParam.getParameter().get(2).getName());
assertEquals(("Systolic blood pressure--expiration v2"), ((StringType) respParam.getParameter().get(2).getValue()).getValue());
assertEquals("abstract", respParam.getParameter().get(3).getName());
assertEquals(false, ((BooleanType) respParam.getParameter().get(3).getValue()).getValue());
// Test with version 1 specified.
respParam = myClient
.operation()
.onType(CodeSystem.class)
.named("lookup")
.withParameter(Parameters.class, "code", new CodeType("8450-9"))
.andParameter("system", new UriType("http://acme.org"))
.andParameter("version", new StringType("1"))
.execute();
resp = myFhirCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(respParam);
ourLog.info(resp);
assertEquals("name", respParam.getParameter().get(0).getName());
assertEquals(("ACME Codes"), ((StringType) respParam.getParameter().get(0).getValue()).getValue());
assertEquals("version", respParam.getParameter().get(1).getName());
assertEquals("1", ((StringType) respParam.getParameter().get(1).getValue()).getValue());
assertEquals("display", respParam.getParameter().get(2).getName());
assertEquals(("Systolic blood pressure--expiration v1"), ((StringType) respParam.getParameter().get(2).getValue()).getValue());
assertEquals("abstract", respParam.getParameter().get(3).getName());
assertEquals(false, ((BooleanType) respParam.getParameter().get(3).getValue()).getValue());
// Test with version 2 specified
respParam = myClient
.operation()
.onType(CodeSystem.class)
.named("lookup")
.withParameter(Parameters.class, "code", new CodeType("8450-9"))
.andParameter("system", new UriType("http://acme.org"))
.andParameter("version", new StringType("2"))
.execute();
resp = myFhirCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(respParam);
ourLog.info(resp);
assertEquals("name", respParam.getParameter().get(0).getName());
assertEquals(("ACME Codes"), ((StringType) respParam.getParameter().get(0).getValue()).getValue());
assertEquals("version", respParam.getParameter().get(1).getName());
assertEquals("2", ((StringType) respParam.getParameter().get(1).getValue()).getValue());
assertEquals("display", respParam.getParameter().get(2).getName());
assertEquals(("Systolic blood pressure--expiration v2"), ((StringType) respParam.getParameter().get(2).getValue()).getValue());
assertEquals("abstract", respParam.getParameter().get(3).getName());
assertEquals(false, ((BooleanType) respParam.getParameter().get(3).getValue()).getValue());
}
@Test
public void testLookupOperationByCodeAndSystemUserDefinedNonExistentVersion() {
try {
myClient
.operation()
.onType(CodeSystem.class)
.named("lookup")
.withParameter(Parameters.class, "code", new CodeType("8450-9"))
.andParameter("system", new UriType("http://acme.org"))
.andParameter("version", new StringType("3"))
.execute();
fail();
} catch (ResourceNotFoundException e) {
ourLog.info("Lookup failed as expected");
}
}
@Test
public void testLookupOperationByCoding() {
// First test with no version specified (should return from last version created)
Parameters respParam = myClient
.operation()
.onType(CodeSystem.class)
.named("lookup")
.withParameter(Parameters.class, "coding", new Coding().setSystem("http://acme.org").setCode("8450-9"))
.execute();
String resp = myFhirCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(respParam);
ourLog.info(resp);
assertEquals("name", respParam.getParameter().get(0).getName());
assertEquals(("ACME Codes"), ((StringType) respParam.getParameter().get(0).getValue()).getValue());
assertEquals("version", respParam.getParameter().get(1).getName());
assertEquals("2", ((StringType) respParam.getParameter().get(1).getValue()).getValue());
assertEquals("display", respParam.getParameter().get(2).getName());
assertEquals(("Systolic blood pressure--expiration v2"), ((StringType) respParam.getParameter().get(2).getValue()).getValue());
assertEquals("abstract", respParam.getParameter().get(3).getName());
assertEquals(false, ((BooleanType) respParam.getParameter().get(3).getValue()).getValue());
// Test with version set to 1
respParam = myClient
.operation()
.onType(CodeSystem.class)
.named("lookup")
.withParameter(Parameters.class, "coding", new Coding().setSystem("http://acme.org").setCode("8450-9").setVersion("1"))
.execute();
resp = myFhirCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(respParam);
ourLog.info(resp);
assertEquals("name", respParam.getParameter().get(0).getName());
assertEquals(("ACME Codes"), ((StringType) respParam.getParameter().get(0).getValue()).getValue());
assertEquals("version", respParam.getParameter().get(1).getName());
assertEquals("1", ((StringType) respParam.getParameter().get(1).getValue()).getValue());
assertEquals("display", respParam.getParameter().get(2).getName());
assertEquals(("Systolic blood pressure--expiration v1"), ((StringType) respParam.getParameter().get(2).getValue()).getValue());
assertEquals("abstract", respParam.getParameter().get(3).getName());
assertEquals(false, ((BooleanType) respParam.getParameter().get(3).getValue()).getValue());
// Test with version set to 2
respParam = myClient
.operation()
.onType(CodeSystem.class)
.named("lookup")
.withParameter(Parameters.class, "coding", new Coding().setSystem("http://acme.org").setCode("8450-9").setVersion("2"))
.execute();
resp = myFhirCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(respParam);
ourLog.info(resp);
assertEquals("name", respParam.getParameter().get(0).getName());
assertEquals(("ACME Codes"), ((StringType) respParam.getParameter().get(0).getValue()).getValue());
assertEquals("version", respParam.getParameter().get(1).getName());
assertEquals("2", ((StringType) respParam.getParameter().get(1).getValue()).getValue());
assertEquals("display", respParam.getParameter().get(2).getName());
assertEquals(("Systolic blood pressure--expiration v2"), ((StringType) respParam.getParameter().get(2).getValue()).getValue());
assertEquals("abstract", respParam.getParameter().get(3).getName());
assertEquals(false, ((BooleanType) respParam.getParameter().get(3).getValue()).getValue());
}
@Test
public void testSubsumesOnCodes_Subsumes() {
// First test with no version specified (should return result for last version created).
Parameters respParam = myClient
.operation()
.onType(CodeSystem.class)
.named(JpaConstants.OPERATION_SUBSUMES)
.withParameter(Parameters.class, "codeA", new CodeType("ParentA"))
.andParameter("codeB", new CodeType("ParentB"))
.andParameter("system", new UriType(SYSTEM_PARENTCHILD))
.execute();
String resp = myFhirCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(respParam);
ourLog.info(resp);
assertEquals(1, respParam.getParameter().size());
assertEquals("outcome", respParam.getParameter().get(0).getName());
assertEquals(ConceptSubsumptionOutcome.SUBSUMES.toCode(), ((CodeType) respParam.getParameter().get(0).getValue()).getValue());
// Test with version set to 1.
respParam = myClient
.operation()
.onType(CodeSystem.class)
.named(JpaConstants.OPERATION_SUBSUMES)
.withParameter(Parameters.class, "codeA", new CodeType("ParentA"))
.andParameter("codeB", new CodeType("ParentC"))
.andParameter("system", new UriType(SYSTEM_PARENTCHILD))
.andParameter("version", new StringType("1"))
.execute();
resp = myFhirCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(respParam);
ourLog.info(resp);
assertEquals(1, respParam.getParameter().size());
assertEquals("outcome", respParam.getParameter().get(0).getName());
assertEquals(ConceptSubsumptionOutcome.SUBSUMES.toCode(), ((CodeType) respParam.getParameter().get(0).getValue()).getValue());
// Test with version set to 2.
respParam = myClient
.operation()
.onType(CodeSystem.class)
.named(JpaConstants.OPERATION_SUBSUMES)
.withParameter(Parameters.class, "codeA", new CodeType("ParentA"))
.andParameter("codeB", new CodeType("ParentB"))
.andParameter("system", new UriType(SYSTEM_PARENTCHILD))
.andParameter("version", new StringType("2"))
.execute();
resp = myFhirCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(respParam);
ourLog.info(resp);
assertEquals(1, respParam.getParameter().size());
assertEquals("outcome", respParam.getParameter().get(0).getName());
assertEquals(ConceptSubsumptionOutcome.SUBSUMES.toCode(), ((CodeType) respParam.getParameter().get(0).getValue()).getValue());
}
@Test
public void testSubsumesOnCodes_Subsumedby() {
// First test with no version specified (should return result for last version created).
Parameters respParam = myClient
.operation()
.onType(CodeSystem.class)
.named(JpaConstants.OPERATION_SUBSUMES)
.withParameter(Parameters.class, "codeA", new CodeType("ParentB"))
.andParameter("codeB", new CodeType("ParentA"))
.andParameter("system", new UriType(SYSTEM_PARENTCHILD))
.execute();
String resp = myFhirCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(respParam);
ourLog.info(resp);
assertEquals(1, respParam.getParameter().size());
assertEquals("outcome", respParam.getParameter().get(0).getName());
assertEquals(ConceptSubsumptionOutcome.SUBSUMEDBY.toCode(), ((CodeType) respParam.getParameter().get(0).getValue()).getValue());
// Test with version set to 1.
respParam = myClient
.operation()
.onType(CodeSystem.class)
.named(JpaConstants.OPERATION_SUBSUMES)
.withParameter(Parameters.class, "codeA", new CodeType("ParentC"))
.andParameter("codeB", new CodeType("ParentA"))
.andParameter("system", new UriType(SYSTEM_PARENTCHILD))
.andParameter("version", new StringType("1"))
.execute();
resp = myFhirCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(respParam);
ourLog.info(resp);
assertEquals(1, respParam.getParameter().size());
assertEquals("outcome", respParam.getParameter().get(0).getName());
assertEquals(ConceptSubsumptionOutcome.SUBSUMEDBY.toCode(), ((CodeType) respParam.getParameter().get(0).getValue()).getValue());
// Test with version set to 2.
respParam = myClient
.operation()
.onType(CodeSystem.class)
.named(JpaConstants.OPERATION_SUBSUMES)
.withParameter(Parameters.class, "codeA", new CodeType("ParentB"))
.andParameter("codeB", new CodeType("ParentA"))
.andParameter("system", new UriType(SYSTEM_PARENTCHILD))
.andParameter("version", new StringType("2"))
.execute();
resp = myFhirCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(respParam);
ourLog.info(resp);
assertEquals(1, respParam.getParameter().size());
assertEquals("outcome", respParam.getParameter().get(0).getName());
assertEquals(ConceptSubsumptionOutcome.SUBSUMEDBY.toCode(), ((CodeType) respParam.getParameter().get(0).getValue()).getValue());
}
@Test
public void testSubsumesOnCodes_Disjoint() {
// First test with no version specified (should return result for last version created).
Parameters respParam = myClient
.operation()
.onType(CodeSystem.class)
.named(JpaConstants.OPERATION_SUBSUMES)
.withParameter(Parameters.class, "codeA", new CodeType("ParentA"))
.andParameter("codeB", new CodeType("ParentC"))
.andParameter("system", new UriType(SYSTEM_PARENTCHILD))
.execute();
String resp = myFhirCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(respParam);
ourLog.info(resp);
assertEquals(1, respParam.getParameter().size());
assertEquals("outcome", respParam.getParameter().get(0).getName());
assertEquals(ConceptSubsumptionOutcome.NOTSUBSUMED.toCode(), ((CodeType) respParam.getParameter().get(0).getValue()).getValue());
// Test with version set to 1
respParam = myClient
.operation()
.onType(CodeSystem.class)
.named(JpaConstants.OPERATION_SUBSUMES)
.withParameter(Parameters.class, "codeA", new CodeType("ParentA"))
.andParameter("codeB", new CodeType("ParentB"))
.andParameter("system", new UriType(SYSTEM_PARENTCHILD))
.andParameter("version", new StringType("1"))
.execute();
resp = myFhirCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(respParam);
ourLog.info(resp);
assertEquals(1, respParam.getParameter().size());
assertEquals("outcome", respParam.getParameter().get(0).getName());
assertEquals(ConceptSubsumptionOutcome.NOTSUBSUMED.toCode(), ((CodeType) respParam.getParameter().get(0).getValue()).getValue());
// Test with version set to 2
respParam = myClient
.operation()
.onType(CodeSystem.class)
.named(JpaConstants.OPERATION_SUBSUMES)
.withParameter(Parameters.class, "codeA", new CodeType("ParentA"))
.andParameter("codeB", new CodeType("ParentC"))
.andParameter("system", new UriType(SYSTEM_PARENTCHILD))
.andParameter("version", new StringType("2"))
.execute();
resp = myFhirCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(respParam);
ourLog.info(resp);
assertEquals(1, respParam.getParameter().size());
assertEquals("outcome", respParam.getParameter().get(0).getName());
assertEquals(ConceptSubsumptionOutcome.NOTSUBSUMED.toCode(), ((CodeType) respParam.getParameter().get(0).getValue()).getValue());
}
@Test
public void testSubsumesOnCodings_MismatchedCsVersions() {
try {
myClient
.operation()
.onType(CodeSystem.class)
.named(JpaConstants.OPERATION_SUBSUMES)
.withParameter(Parameters.class, "codingA", new Coding().setSystem(SYSTEM_PARENTCHILD).setCode("ChildAA").setVersion("1"))
.andParameter("codingB", new Coding().setSystem(SYSTEM_PARENTCHILD).setCode("ParentA").setVersion("2"))
.execute();
fail();
} catch (InvalidRequestException e) {
assertEquals("HTTP 400 Bad Request: Unable to test subsumption across different code system versions", e.getMessage());
}
}
@Test
public void testSubsumesOnCodings_Subsumes() {
// First test with no version specified (should return result for last version created).
Parameters respParam = myClient
.operation()
.onType(CodeSystem.class)
.named(JpaConstants.OPERATION_SUBSUMES)
.withParameter(Parameters.class, "codingA", new Coding().setSystem(SYSTEM_PARENTCHILD).setCode("ParentA"))
.andParameter("codingB", new Coding().setSystem(SYSTEM_PARENTCHILD).setCode("ParentB"))
.execute();
String resp = myFhirCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(respParam);
ourLog.info(resp);
assertEquals(1, respParam.getParameter().size());
assertEquals("outcome", respParam.getParameter().get(0).getName());
assertEquals(ConceptSubsumptionOutcome.SUBSUMES.toCode(), ((CodeType) respParam.getParameter().get(0).getValue()).getValue());
// Test with version set to 1.
respParam = myClient
.operation()
.onType(CodeSystem.class)
.named(JpaConstants.OPERATION_SUBSUMES)
.withParameter(Parameters.class, "codingA", new Coding().setSystem(SYSTEM_PARENTCHILD).setCode("ParentA").setVersion("1"))
.andParameter("codingB", new Coding().setSystem(SYSTEM_PARENTCHILD).setCode("ParentC").setVersion("1"))
.execute();
resp = myFhirCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(respParam);
ourLog.info(resp);
assertEquals(1, respParam.getParameter().size());
assertEquals("outcome", respParam.getParameter().get(0).getName());
assertEquals(ConceptSubsumptionOutcome.SUBSUMES.toCode(), ((CodeType) respParam.getParameter().get(0).getValue()).getValue());
// Test with version set to 2.
respParam = myClient
.operation()
.onType(CodeSystem.class)
.named(JpaConstants.OPERATION_SUBSUMES)
.withParameter(Parameters.class, "codingA", new Coding().setSystem(SYSTEM_PARENTCHILD).setCode("ParentA").setVersion("2"))
.andParameter("codingB", new Coding().setSystem(SYSTEM_PARENTCHILD).setCode("ParentB").setVersion("2"))
.execute();
resp = myFhirCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(respParam);
ourLog.info(resp);
assertEquals(1, respParam.getParameter().size());
assertEquals("outcome", respParam.getParameter().get(0).getName());
assertEquals(ConceptSubsumptionOutcome.SUBSUMES.toCode(), ((CodeType) respParam.getParameter().get(0).getValue()).getValue());
}
@Test
public void testSubsumesOnCodings_Subsumedby() {
// First test with no version specified (should return result for last version created).
Parameters respParam = myClient
.operation()
.onType(CodeSystem.class)
.named(JpaConstants.OPERATION_SUBSUMES)
.withParameter(Parameters.class, "codingA", new Coding().setSystem(SYSTEM_PARENTCHILD).setCode("ParentB"))
.andParameter("codingB", new Coding().setSystem(SYSTEM_PARENTCHILD).setCode("ParentA"))
.execute();
String resp = myFhirCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(respParam);
ourLog.info(resp);
assertEquals(1, respParam.getParameter().size());
assertEquals("outcome", respParam.getParameter().get(0).getName());
assertEquals(ConceptSubsumptionOutcome.SUBSUMEDBY.toCode(), ((CodeType) respParam.getParameter().get(0).getValue()).getValue());
// Test with version set to 1.
respParam = myClient
.operation()
.onType(CodeSystem.class)
.named(JpaConstants.OPERATION_SUBSUMES)
.withParameter(Parameters.class, "codingA", new Coding().setSystem(SYSTEM_PARENTCHILD).setCode("ParentC").setVersion("1"))
.andParameter("codingB", new Coding().setSystem(SYSTEM_PARENTCHILD).setCode("ParentA").setVersion("1"))
.execute();
resp = myFhirCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(respParam);
ourLog.info(resp);
assertEquals(1, respParam.getParameter().size());
assertEquals("outcome", respParam.getParameter().get(0).getName());
assertEquals(ConceptSubsumptionOutcome.SUBSUMEDBY.toCode(), ((CodeType) respParam.getParameter().get(0).getValue()).getValue());
// Test with version set to 2.
respParam = myClient
.operation()
.onType(CodeSystem.class)
.named(JpaConstants.OPERATION_SUBSUMES)
.withParameter(Parameters.class, "codingA", new Coding().setSystem(SYSTEM_PARENTCHILD).setCode("ParentB").setVersion("2"))
.andParameter("codingB", new Coding().setSystem(SYSTEM_PARENTCHILD).setCode("ParentA").setVersion("2"))
.execute();
resp = myFhirCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(respParam);
ourLog.info(resp);
assertEquals(1, respParam.getParameter().size());
assertEquals("outcome", respParam.getParameter().get(0).getName());
assertEquals(ConceptSubsumptionOutcome.SUBSUMEDBY.toCode(), ((CodeType) respParam.getParameter().get(0).getValue()).getValue());
}
@Test
public void testSubsumesOnCodings_Disjoint() {
// First test with no version specified (should return result for last version created).
Parameters respParam = myClient
.operation()
.onType(CodeSystem.class)
.named(JpaConstants.OPERATION_SUBSUMES)
.withParameter(Parameters.class, "codingA", new Coding().setSystem(SYSTEM_PARENTCHILD).setCode("ParentA"))
.andParameter("codingB", new Coding().setSystem(SYSTEM_PARENTCHILD).setCode("ParentC"))
.execute();
String resp = myFhirCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(respParam);
ourLog.info(resp);
assertEquals(1, respParam.getParameter().size());
assertEquals("outcome", respParam.getParameter().get(0).getName());
assertEquals(ConceptSubsumptionOutcome.NOTSUBSUMED.toCode(), ((CodeType) respParam.getParameter().get(0).getValue()).getValue());
// Test with version set to 1
respParam = myClient
.operation()
.onType(CodeSystem.class)
.named(JpaConstants.OPERATION_SUBSUMES)
.withParameter(Parameters.class, "codingA", new Coding().setSystem(SYSTEM_PARENTCHILD).setCode("ParentA").setVersion("1"))
.andParameter("codingB", new Coding().setSystem(SYSTEM_PARENTCHILD).setCode("ParentB").setVersion("1"))
.execute();
resp = myFhirCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(respParam);
ourLog.info(resp);
assertEquals(1, respParam.getParameter().size());
assertEquals("outcome", respParam.getParameter().get(0).getName());
assertEquals(ConceptSubsumptionOutcome.NOTSUBSUMED.toCode(), ((CodeType) respParam.getParameter().get(0).getValue()).getValue());
// Test with version set to 2
respParam = myClient
.operation()
.onType(CodeSystem.class)
.named(JpaConstants.OPERATION_SUBSUMES)
.withParameter(Parameters.class, "codingA", new Coding().setSystem(SYSTEM_PARENTCHILD).setCode("ParentA").setVersion("2"))
.andParameter("codingB", new Coding().setSystem(SYSTEM_PARENTCHILD).setCode("ParentC").setVersion("2"))
.execute();
resp = myFhirCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(respParam);
ourLog.info(resp);
assertEquals(1, respParam.getParameter().size());
assertEquals("outcome", respParam.getParameter().get(0).getName());
assertEquals(ConceptSubsumptionOutcome.NOTSUBSUMED.toCode(), ((CodeType) respParam.getParameter().get(0).getValue()).getValue());
}
@Test
public void testUpdateCodeSystemById() throws IOException {
CodeSystem initialCodeSystem = myClient.read().resource(CodeSystem.class).withId(parentChildCs1Id).execute();
assertEquals("Parent Child CodeSystem 1", initialCodeSystem.getName());
initialCodeSystem.setName("Updated Parent Child CodeSystem 1");
String encoded = myFhirCtx.newJsonParser().encodeResourceToString(initialCodeSystem);
HttpPut putRequest = new HttpPut(ourServerBase + "/CodeSystem/" + parentChildCs1Id);
putRequest.setEntity(new StringEntity(encoded, ContentType.parse("application/json+fhir")));
myCaptureQueriesListener.clear();
CloseableHttpResponse resp = ourHttpClient.execute(putRequest);
myCaptureQueriesListener.logAllQueries();
try {
assertEquals(200, resp.getStatusLine().getStatusCode());
} finally {
IOUtils.closeQuietly(resp);
}
CodeSystem updatedCodeSystem = myClient.read().resource(CodeSystem.class).withId(parentChildCs1Id).execute();
assertEquals("Updated Parent Child CodeSystem 1", updatedCodeSystem.getName());
initialCodeSystem = myClient.read().resource(CodeSystem.class).withId(parentChildCs2Id).execute();
assertEquals("Parent Child CodeSystem 2", initialCodeSystem.getName());
initialCodeSystem.setName("Updated Parent Child CodeSystem 2");
encoded = myFhirCtx.newJsonParser().encodeResourceToString(initialCodeSystem);
putRequest = new HttpPut(ourServerBase + "/CodeSystem/" + parentChildCs2Id);
putRequest.setEntity(new StringEntity(encoded, ContentType.parse("application/json+fhir")));
resp = ourHttpClient.execute(putRequest);
try {
assertEquals(200, resp.getStatusLine().getStatusCode());
} finally {
IOUtils.closeQuietly(resp);
}
updatedCodeSystem = myClient.read().resource(CodeSystem.class).withId(parentChildCs2Id).execute();
assertEquals("Updated Parent Child CodeSystem 2", updatedCodeSystem.getName());
}
}
| aemay2/hapi-fhir | hapi-fhir-jpaserver-base/src/test/java/ca/uhn/fhir/jpa/provider/r4/ResourceProviderR4CodeSystemVersionedTest.java | Java | apache-2.0 | 38,014 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.sysds.test.component.tensor;
import org.apache.commons.lang.NotImplementedException;
import org.junit.Assert;
import org.junit.Test;
import org.apache.sysds.common.Types.ValueType;
import org.apache.sysds.runtime.data.DenseBlock;
import org.apache.sysds.runtime.data.DenseBlockBool;
import org.apache.sysds.runtime.data.DenseBlockFactory;
import org.apache.sysds.runtime.data.DenseBlockLBool;
import org.apache.sysds.runtime.data.DenseBlockLFP32;
import org.apache.sysds.runtime.data.DenseBlockLFP64;
import org.apache.sysds.runtime.data.DenseBlockLString;
import org.apache.sysds.runtime.data.DenseBlockLInt32;
import org.apache.sysds.runtime.data.DenseBlockLInt64;
public class DenseBlockSetRowTest {
@Test
public void testDenseBlock2FP32Row() {
DenseBlock db = getDenseBlock2(ValueType.FP32);
checkRow(setRow(db));
}
@Test
public void testDenseBlock2FP64Row() {
DenseBlock db = getDenseBlock2(ValueType.FP64);
checkRow(setRow(db));
}
@Test
public void testDenseBlock2BoolRow() {
DenseBlock db = getDenseBlock2(ValueType.BOOLEAN);
checkRow(setRow(db));
}
@Test
public void testDenseBlock2Int32Row() {
DenseBlock db = getDenseBlock2(ValueType.INT32);
checkRow(setRow(db));
}
@Test
public void testDenseBlock2Int64Row() {
DenseBlock db = getDenseBlock2(ValueType.INT64);
checkRow(setRow(db));
}
@Test
public void testDenseBlock2StringRow() {
DenseBlock db = getDenseBlock2(ValueType.STRING);
checkRow(setRow(db));
}
@Test
public void testDenseBlockLarge2FP32Row() {
DenseBlock db = getDenseBlockLarge2(ValueType.FP32);
checkRow(setRow(db));
}
@Test
public void testDenseBlockLarge2FP64Row() {
DenseBlock db = getDenseBlockLarge2(ValueType.FP64);
checkRow(setRow(db));
}
@Test
public void testDenseBlockLarge2BoolRow() {
DenseBlock db = getDenseBlockLarge2(ValueType.BOOLEAN);
checkRow(setRow(db));
}
@Test
public void testDenseBlockLarge2Int32Row() {
DenseBlock db = getDenseBlockLarge2(ValueType.INT32);
checkRow(setRow(db));
}
@Test
public void testDenseBlockLarge2Int64Row() {
DenseBlock db = getDenseBlockLarge2(ValueType.INT64);
checkRow(setRow(db));
}
@Test
public void testDenseBlockLarge2StringRow() {
DenseBlock db = getDenseBlockLarge2(ValueType.STRING);
checkRow(setRow(db));
}
@Test
public void testDenseBlock3FP32Row() {
DenseBlock db = getDenseBlock3(ValueType.FP32);
checkRow(setRow(db));
}
@Test
public void testDenseBlock3FP64Row() {
DenseBlock db = getDenseBlock3(ValueType.FP64);
checkRow(setRow(db));
}
@Test
public void testDenseBlock3BoolRow() {
DenseBlock db = getDenseBlock3(ValueType.BOOLEAN);
checkRow(setRow(db));
}
@Test
public void testDenseBlock3Int32Row() {
DenseBlock db = getDenseBlock3(ValueType.INT32);
checkRow(setRow(db));
}
@Test
public void testDenseBlock3Int64Row() {
DenseBlock db = getDenseBlock3(ValueType.INT64);
checkRow(setRow(db));
}
@Test
public void testDenseBlock3StringRow() {
DenseBlock db = getDenseBlock3(ValueType.STRING);
checkRow(setRow(db));
}
@Test
public void testDenseBlockLarge3FP32Row() {
DenseBlock db = getDenseBlockLarge3(ValueType.FP32);
checkRow(setRow(db));
}
@Test
public void testDenseBlockLarge3FP64Row() {
DenseBlock db = getDenseBlockLarge3(ValueType.FP64);
checkRow(setRow(db));
}
@Test
public void testDenseBlockLarge3BoolRow() {
DenseBlock db = getDenseBlockLarge3(ValueType.BOOLEAN);
checkRow(setRow(db));
}
@Test
public void testDenseBlockLarge3Int32Row() {
DenseBlock db = getDenseBlockLarge3(ValueType.INT32);
checkRow(setRow(db));
}
@Test
public void testDenseBlockLarge3Int64Row() {
DenseBlock db = getDenseBlockLarge3(ValueType.INT64);
checkRow(setRow(db));
}
@Test
public void testDenseBlockLarge3StringRow() {
DenseBlock db = getDenseBlockLarge3(ValueType.STRING);
checkRow(setRow(db));
}
private static DenseBlock getDenseBlock2(ValueType vt) {
return DenseBlockFactory.createDenseBlock(vt, new int[]{3, 5});
}
private static DenseBlock getDenseBlock3(ValueType vt) {
return DenseBlockFactory.createDenseBlock(vt, new int[]{3, 5, 7});
}
private static DenseBlock getDenseBlockLarge2(ValueType vt) {
int[] dims = {3, 5};
switch (vt) {
case FP32:
return new DenseBlockLFP32(dims);
case FP64:
return new DenseBlockLFP64(dims);
case BOOLEAN:
return new DenseBlockLBool(dims);
case INT32:
return new DenseBlockLInt32(dims);
case INT64:
return new DenseBlockLInt64(dims);
case STRING:
return new DenseBlockLString(dims);
default:
throw new NotImplementedException();
}
}
private static DenseBlock getDenseBlockLarge3(ValueType vt) {
int[] dims = {3, 5, 7};
switch (vt) {
case FP32:
return new DenseBlockLFP32(dims);
case FP64:
return new DenseBlockLFP64(dims);
case BOOLEAN:
return new DenseBlockLBool(dims);
case INT32:
return new DenseBlockLInt32(dims);
case INT64:
return new DenseBlockLInt64(dims);
case STRING:
return new DenseBlockLString(dims);
default:
throw new NotImplementedException();
}
}
private static DenseBlock setRow(DenseBlock db) {
if (db.numDims() == 3) {
int dim12 = 5 * 7;
double[] row = new double[dim12];
for (int i = 0; i < dim12; i++) {
row[i] = i;
}
db.set(1, row);
} else { //num dims = 2
int dim1 = 5;
double[] row = new double[dim1];
for (int i = 0; i < dim1; i++) {
row[i] = i;
}
db.set(1, row);
}
return db;
}
private static void checkRow(DenseBlock db) {
boolean isBool = (db instanceof DenseBlockBool) || (db instanceof DenseBlockLBool);
if (db.numDims() == 3) {
int dim1 = 5, dim2 = 7;
for (int i = 0; i < dim1; i++)
for (int j = 0; j < dim2; j++) {
int pos = i * dim2 + j;
double expected = isBool && pos != 0 ? 1 : (double) pos;
Assert.assertEquals(expected, db.get(1, pos), 0);
}
} else { //num dims = 2
int dim1 = 5;
for (int i = 0; i < dim1; i++) {
double expected = isBool && i != 0 ? 1 : (double) i;
Assert.assertEquals(expected, db.get(1, i), 0);
}
}
}
}
| apache/incubator-systemml | src/test/java/org/apache/sysds/test/component/tensor/DenseBlockSetRowTest.java | Java | apache-2.0 | 6,933 |
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.2-hudson-jaxb-ri-2.2-63-
// 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: 2013.10.29 at 05:05:13 \uc624\ud6c4 KST
//
package net.ion.open.oadr2.model;
import java.io.Serializable;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
import org.jvnet.jaxb2_commons.lang.Equals;
import org.jvnet.jaxb2_commons.lang.EqualsStrategy;
import org.jvnet.jaxb2_commons.lang.HashCode;
import org.jvnet.jaxb2_commons.lang.HashCodeStrategy;
import org.jvnet.jaxb2_commons.lang.JAXBEqualsStrategy;
import org.jvnet.jaxb2_commons.lang.JAXBHashCodeStrategy;
import org.jvnet.jaxb2_commons.lang.JAXBToStringStrategy;
import org.jvnet.jaxb2_commons.lang.ToString;
import org.jvnet.jaxb2_commons.lang.ToStringStrategy;
import org.jvnet.jaxb2_commons.locator.ObjectLocator;
import org.jvnet.jaxb2_commons.locator.util.LocatorUtils;
/**
* <p>Java class for signalPayloadType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="signalPayloadType">
* <complexContent>
* <extension base="{urn:ietf:params:xml:ns:icalendar-2.0:stream}StreamPayloadBaseType">
* <sequence>
* <element ref="{http://docs.oasis-open.org/ns/energyinterop/201110}payloadFloat"/>
* </sequence>
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "signalPayloadType", propOrder = {
"payloadFloat"
})
public class SignalPayload
extends StreamPayloadBase
implements Serializable, Equals, HashCode, ToString
{
private final static long serialVersionUID = 1L;
@XmlElement(required = true)
protected PayloadFloat payloadFloat;
/**
* Default no-arg constructor
*
*/
public SignalPayload() {
super();
}
/**
* Fully-initialising value constructor
*
*/
public SignalPayload(final PayloadFloat payloadFloat) {
super();
this.payloadFloat = payloadFloat;
}
/**
* Gets the value of the payloadFloat property.
*
* @return
* possible object is
* {@link PayloadFloat }
*
*/
public PayloadFloat getPayloadFloat() {
return payloadFloat;
}
/**
* Sets the value of the payloadFloat property.
*
* @param value
* allowed object is
* {@link PayloadFloat }
*
*/
public void setPayloadFloat(PayloadFloat value) {
this.payloadFloat = value;
}
public String toString() {
final ToStringStrategy strategy = JAXBToStringStrategy.INSTANCE;
final StringBuilder buffer = new StringBuilder();
append(null, buffer, strategy);
return buffer.toString();
}
public StringBuilder append(ObjectLocator locator, StringBuilder buffer, ToStringStrategy strategy) {
strategy.appendStart(locator, this, buffer);
appendFields(locator, buffer, strategy);
strategy.appendEnd(locator, this, buffer);
return buffer;
}
public StringBuilder appendFields(ObjectLocator locator, StringBuilder buffer, ToStringStrategy strategy) {
super.appendFields(locator, buffer, strategy);
{
PayloadFloat thePayloadFloat;
thePayloadFloat = this.getPayloadFloat();
strategy.appendField(locator, this, "payloadFloat", buffer, thePayloadFloat);
}
return buffer;
}
public boolean equals(ObjectLocator thisLocator, ObjectLocator thatLocator, Object object, EqualsStrategy strategy) {
if (!(object instanceof SignalPayload)) {
return false;
}
if (this == object) {
return true;
}
if (!super.equals(thisLocator, thatLocator, object, strategy)) {
return false;
}
final SignalPayload that = ((SignalPayload) object);
{
PayloadFloat lhsPayloadFloat;
lhsPayloadFloat = this.getPayloadFloat();
PayloadFloat rhsPayloadFloat;
rhsPayloadFloat = that.getPayloadFloat();
if (!strategy.equals(LocatorUtils.property(thisLocator, "payloadFloat", lhsPayloadFloat), LocatorUtils.property(thatLocator, "payloadFloat", rhsPayloadFloat), lhsPayloadFloat, rhsPayloadFloat)) {
return false;
}
}
return true;
}
public boolean equals(Object object) {
final EqualsStrategy strategy = JAXBEqualsStrategy.INSTANCE;
return equals(null, null, object, strategy);
}
public int hashCode(ObjectLocator locator, HashCodeStrategy strategy) {
int currentHashCode = super.hashCode(locator, strategy);
{
PayloadFloat thePayloadFloat;
thePayloadFloat = this.getPayloadFloat();
currentHashCode = strategy.hashCode(LocatorUtils.property(locator, "payloadFloat", thePayloadFloat), currentHashCode, thePayloadFloat);
}
return currentHashCode;
}
public int hashCode() {
final HashCodeStrategy strategy = JAXBHashCodeStrategy.INSTANCE;
return this.hashCode(null, strategy);
}
public SignalPayload withPayloadFloat(PayloadFloat value) {
setPayloadFloat(value);
return this;
}
}
| ezsimple/java | spring/apt/src/main/java/net/ion/open/oadr2/model/SignalPayload.java | Java | apache-2.0 | 5,708 |
package com.roboo.like.google.views;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.widget.LinearLayout;
import android.widget.Scroller;
/***
* 理解Scroller类
* @author bo.li
*
* 2014-6-24 下午5:19:39
*
* TODO
*/
public class CustomLinearLayout extends LinearLayout
{
private static final String TAG = "CustomView";
private Scroller mScroller;
private GestureDetector mGestureDetector;
public CustomLinearLayout(Context context)
{
this(context, null);
}
public CustomLinearLayout(Context context, AttributeSet attrs)
{
super(context, attrs);
setClickable(true);
setLongClickable(true);
mScroller = new Scroller(context);
mGestureDetector = new GestureDetector(context, new CustomGestureListener());
}
public CustomLinearLayout(Context context, AttributeSet attrs, int defStyle)
{
super(context, attrs, defStyle);
setClickable(true);
setLongClickable(true);
mScroller = new Scroller(context);
mGestureDetector = new GestureDetector(context, new CustomGestureListener());
}
// 调用此方法滚动到目标位置
public void smoothScrollTo(int fx, int fy)
{
int dx = fx - mScroller.getFinalX();
int dy = fy - mScroller.getFinalY();
smoothScrollBy(dx, dy);
}
// 调用此方法设置滚动的相对偏移
public void smoothScrollBy(int dx, int dy)
{
// 设置mScroller的滚动偏移量
mScroller.startScroll(mScroller.getFinalX(), mScroller.getFinalY(), dx, dy);
invalidate();// 这里必须调用invalidate()才能保证computeScroll()会被调用,否则不一定会刷新界面,看不到滚动效果
}
@Override
public void computeScroll()
{
// 先判断mScroller滚动是否完成
if (mScroller.computeScrollOffset())
{
// 这里调用View的scrollTo()完成实际的滚动
scrollTo(mScroller.getCurrX(), mScroller.getCurrY());
// 必须调用该方法,否则不一定能看到滚动效果
postInvalidate();
}
super.computeScroll();
}
@Override
public boolean onTouchEvent(MotionEvent event)
{
switch (event.getAction())
{
case MotionEvent.ACTION_UP:
Log.i(TAG, " ScorllY = " + getScrollY()+" ScrollX = " + getScrollX());
smoothScrollTo(0, 0);
break;
default:
return mGestureDetector.onTouchEvent(event);
}
return super.onTouchEvent(event);
}
class CustomGestureListener implements GestureDetector.OnGestureListener
{
public boolean onDown(MotionEvent e)
{
return true;
}
public void onShowPress(MotionEvent e)
{
}
@Override
public boolean onSingleTapUp(MotionEvent e)
{
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY)
{
int disY = (int) ((distanceY - 0.5) / 2);
int disX = (int) ((distanceX - 0.5) / 2);
Log.i(TAG, "disX =" + disX + " disY = " + disY);
// if ((Math.abs(disX) - Math.abs(disY)) >= 0)
// {
// smoothScrollBy(disX, 0);
// }
// else
// {
// smoothScrollBy(0, disY);
// }
smoothScrollBy(disX, 0);
return false;
}
public void onLongPress(MotionEvent e)
{
}
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY)
{
return false;
}
}
}
| haikuowuya/like_googleplus_layout | src/com/roboo/like/google/views/CustomLinearLayout.java | Java | apache-2.0 | 3,311 |
/*
* Copyright 2002-2006 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.ejb.config;
import junit.framework.TestCase;
import org.springframework.beans.factory.parsing.BeanComponentDefinition;
import org.springframework.beans.factory.parsing.CollectingReaderEventListener;
import org.springframework.beans.factory.parsing.ComponentDefinition;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.core.io.ClassPathResource;
/**
* @author Torsten Juergeleit
* @author Juergen Hoeller
*/
public class JeeNamespaceHandlerEventTests extends TestCase {
private CollectingReaderEventListener eventListener = new CollectingReaderEventListener();
private XmlBeanDefinitionReader reader;
private DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
public void setUp() throws Exception {
this.reader = new XmlBeanDefinitionReader(this.beanFactory);
this.reader.setEventListener(this.eventListener);
this.reader.loadBeanDefinitions(new ClassPathResource("jeeNamespaceHandlerTests.xml", getClass()));
}
public void testJndiLookupComponentEventReceived() {
ComponentDefinition component = this.eventListener.getComponentDefinition("simple");
assertTrue(component instanceof BeanComponentDefinition);
}
public void testLocalSlsbComponentEventReceived() {
ComponentDefinition component = this.eventListener.getComponentDefinition("simpleLocalEjb");
assertTrue(component instanceof BeanComponentDefinition);
}
public void testRemoteSlsbComponentEventReceived() {
ComponentDefinition component = this.eventListener.getComponentDefinition("simpleRemoteEjb");
assertTrue(component instanceof BeanComponentDefinition);
}
}
| cbeams-archive/spring-framework-2.5.x | tiger/test/org/springframework/ejb/config/JeeNamespaceHandlerEventTests.java | Java | apache-2.0 | 2,366 |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.pinot.spi.utils.retry;
/**
* Retry policy without delay between attempts.
*/
public class NoDelayRetryPolicy extends BaseRetryPolicy {
public NoDelayRetryPolicy(int maxNumAttempts) {
super(maxNumAttempts);
}
@Override
protected long getDelayMs(int currentAttempt) {
return 0L;
}
}
| linkedin/pinot | pinot-spi/src/main/java/org/apache/pinot/spi/utils/retry/NoDelayRetryPolicy.java | Java | apache-2.0 | 1,132 |
package com.twu.biblioteca;
public class User {
private String name;
private String libraryNum;
private String emailAddress;
private String phoneNum;
private String password;
public User(String name, String libraryNum, String emailAddress, String phoneNum, String password) {
this.name = name;
this.libraryNum = libraryNum;
this.emailAddress = emailAddress;
this.phoneNum = phoneNum;
this.password = password;
}
public boolean checkUser(String libraryNum, String userPassword) {
return this.libraryNum.equals(libraryNum) && this.password.equals(userPassword);
}
@Override
public String toString() {
return "name: " + name + "\nemail: " + emailAddress + "\nphone: " + phoneNum;
}
}
| y7624474/TWU-biblioteca | src/com/twu/biblioteca/User.java | Java | apache-2.0 | 789 |
/*
* Created on 25-Jan-2006
*/
package org.apache.lucene.search.similar;
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Set;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.similar.MoreLikeThis;
/**
* A simple wrapper for MoreLikeThis for use in scenarios where a Query object is required eg
* in custom QueryParser extensions. At query.rewrite() time the reader is used to construct the
* actual MoreLikeThis object and obtain the real Query object.
*/
public class MoreLikeThisQuery extends Query
{
private String likeText;
private String[] moreLikeFields;
private Analyzer analyzer;
float percentTermsToMatch=0.3f;
int minTermFrequency=1;
int maxQueryTerms=5;
Set stopWords=null;
int minDocFreq=-1;
/**
* @param moreLikeFields
*/
public MoreLikeThisQuery(String likeText, String[] moreLikeFields, Analyzer analyzer)
{
this.likeText=likeText;
this.moreLikeFields=moreLikeFields;
this.analyzer=analyzer;
}
public Query rewrite(IndexReader reader) throws IOException
{
MoreLikeThis mlt=new MoreLikeThis(reader);
mlt.setFieldNames(moreLikeFields);
mlt.setAnalyzer(analyzer);
mlt.setMinTermFreq(minTermFrequency);
if(minDocFreq>=0)
{
mlt.setMinDocFreq(minDocFreq);
}
mlt.setMaxQueryTerms(maxQueryTerms);
mlt.setStopWords(stopWords);
BooleanQuery bq= (BooleanQuery) mlt.like(new ByteArrayInputStream(likeText.getBytes()));
BooleanClause[] clauses = bq.getClauses();
//make at least half the terms match
bq.setMinimumNumberShouldMatch((int)(clauses.length*percentTermsToMatch));
return bq;
}
/* (non-Javadoc)
* @see org.apache.lucene.search.Query#toString(java.lang.String)
*/
public String toString(String field)
{
return "like:"+likeText;
}
public float getPercentTermsToMatch() {
return percentTermsToMatch;
}
public void setPercentTermsToMatch(float percentTermsToMatch) {
this.percentTermsToMatch = percentTermsToMatch;
}
public Analyzer getAnalyzer()
{
return analyzer;
}
public void setAnalyzer(Analyzer analyzer)
{
this.analyzer = analyzer;
}
public String getLikeText()
{
return likeText;
}
public void setLikeText(String likeText)
{
this.likeText = likeText;
}
public int getMaxQueryTerms()
{
return maxQueryTerms;
}
public void setMaxQueryTerms(int maxQueryTerms)
{
this.maxQueryTerms = maxQueryTerms;
}
public int getMinTermFrequency()
{
return minTermFrequency;
}
public void setMinTermFrequency(int minTermFrequency)
{
this.minTermFrequency = minTermFrequency;
}
public String[] getMoreLikeFields()
{
return moreLikeFields;
}
public void setMoreLikeFields(String[] moreLikeFields)
{
this.moreLikeFields = moreLikeFields;
}
public Set getStopWords()
{
return stopWords;
}
public void setStopWords(Set stopWords)
{
this.stopWords = stopWords;
}
public int getMinDocFreq()
{
return minDocFreq;
}
public void setMinDocFreq(int minDocFreq)
{
this.minDocFreq = minDocFreq;
}
}
| Overruler/retired-apache-sources | lucene-2.9.4/contrib/queries/src/java/org/apache/lucene/search/similar/MoreLikeThisQuery.java | Java | apache-2.0 | 4,253 |
package com.vipshop.microscope.collector.receiver;
public class NettyMessageReceiver implements MessageReceiver {
/**
* Start message receiver server.
*/
@Override
public void start() {
}
}
| fjfd/microscope | microscope-collector/src/main/java/com/vipshop/microscope/collector/receiver/NettyMessageReceiver.java | Java | apache-2.0 | 220 |
package org.codelibs.elasticsearch.taste.similarity;
public class LogLikelihoodSimilarityFactory<T> extends
AbstractUserSimilarityFactory<T> {
@Override
public T create() {
@SuppressWarnings("unchecked")
final T t = (T) new LogLikelihoodSimilarity(dataModel);
return t;
}
}
| codelibs/elasticsearch-taste | src/main/java/org/codelibs/elasticsearch/taste/similarity/LogLikelihoodSimilarityFactory.java | Java | apache-2.0 | 321 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.processor.aggregator;
import org.apache.camel.processor.aggregate.OptimisticLockRetryPolicy;
import org.junit.Assert;
import org.junit.Test;
public class OptimisticLockRetryPolicyTest extends Assert {
private static long precision = 100L; // give or take 100ms
@Test
public void testRandomBackOff() throws Exception {
OptimisticLockRetryPolicy policy = new OptimisticLockRetryPolicy();
policy.setRandomBackOff(true);
policy.setExponentialBackOff(false);
policy.setMaximumRetryDelay(100L);
for (int i = 0; i < 10; i++) {
long elapsed = doDelay(policy, i);
assertTrue(elapsed <= policy.getMaximumRetryDelay() + precision && elapsed >= 0);
}
}
@Test
public void testExponentialBackOff() throws Exception {
OptimisticLockRetryPolicy policy = new OptimisticLockRetryPolicy();
policy.setRandomBackOff(false);
policy.setExponentialBackOff(true);
policy.setMaximumRetryDelay(0L);
policy.setRetryDelay(10L);
for (int i = 0; i < 6; i++) {
long elapsed = doDelay(policy, i);
assertDelay(10L << i, elapsed);
}
}
@Test
public void testExponentialBackOffMaximumRetryDelay() throws Exception {
OptimisticLockRetryPolicy policy = new OptimisticLockRetryPolicy();
policy.setRandomBackOff(false);
policy.setExponentialBackOff(true);
policy.setMaximumRetryDelay(100L);
policy.setRetryDelay(50L);
for (int i = 0; i < 10; i++) {
long elapsed = doDelay(policy, i);
switch (i) {
case 0:
assertDelay(50L, elapsed);
break;
case 1:
assertDelay(100L, elapsed);
break;
default:
assertDelay(100L, elapsed);
break;
}
}
}
@Test
public void testRetryDelay() throws Exception {
OptimisticLockRetryPolicy policy = new OptimisticLockRetryPolicy();
policy.setRandomBackOff(false);
policy.setExponentialBackOff(false);
policy.setMaximumRetryDelay(0L);
policy.setRetryDelay(50L);
for (int i = 0; i < 10; i++) {
long elapsed = doDelay(policy, i);
assertDelay(50L, elapsed);
}
}
@Test
public void testMaximumRetries() throws Exception {
OptimisticLockRetryPolicy policy = new OptimisticLockRetryPolicy();
policy.setRandomBackOff(false);
policy.setExponentialBackOff(false);
policy.setMaximumRetryDelay(0L);
policy.setMaximumRetries(2);
policy.setRetryDelay(50L);
for (int i = 0; i < 10; i++) {
switch (i) {
case 0:
case 1:
assertTrue(policy.shouldRetry(i));
break;
default:
assertFalse(policy.shouldRetry(i));
}
}
}
private long doDelay(OptimisticLockRetryPolicy policy, int i) throws InterruptedException {
long start = System.currentTimeMillis();
policy.doDelay(i);
long elapsed = System.currentTimeMillis() - start;
return elapsed;
}
private void assertDelay(long expectedDelay, long actualDelay) {
String msg = String.format("%d <= %d", actualDelay, expectedDelay + precision);
assertTrue(msg, actualDelay <= expectedDelay + precision);
msg = String.format("%d >= %d", actualDelay, expectedDelay - precision);
assertTrue(msg, actualDelay >= expectedDelay - precision);
}
}
| objectiser/camel | core/camel-core/src/test/java/org/apache/camel/processor/aggregator/OptimisticLockRetryPolicyTest.java | Java | apache-2.0 | 4,458 |
package com.beecavegames.slots.data.match;
import com.beecavegames.slots.data.WindowMatch;
public class ScatterMatch extends WindowMatch {
}
| sgmiller/hiveelements | gameelements/src/main/java/slots/data/match/ScatterMatch.java | Java | apache-2.0 | 144 |
package org.apache.maven.repository.legacy;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import java.util.IdentityHashMap;
import java.util.Map;
import org.apache.maven.repository.ArtifactTransferEvent;
import org.apache.maven.repository.ArtifactTransferListener;
import org.apache.maven.repository.ArtifactTransferResource;
import org.apache.maven.wagon.events.TransferEvent;
import org.apache.maven.wagon.events.TransferListener;
import org.apache.maven.wagon.repository.Repository;
import org.apache.maven.wagon.resource.Resource;
public class TransferListenerAdapter
implements TransferListener
{
private final ArtifactTransferListener listener;
private final Map<Resource, ArtifactTransferResource> artifacts;
private final Map<Resource, Long> transfers;
public static TransferListener newAdapter( ArtifactTransferListener listener )
{
if ( listener == null )
{
return null;
}
else
{
return new TransferListenerAdapter( listener );
}
}
private TransferListenerAdapter( ArtifactTransferListener listener )
{
this.listener = listener;
this.artifacts = new IdentityHashMap<Resource, ArtifactTransferResource>();
this.transfers = new IdentityHashMap<Resource, Long>();
}
public void debug( String message )
{
}
public void transferCompleted( TransferEvent transferEvent )
{
ArtifactTransferEvent event = wrap( transferEvent );
Long transferred = null;
synchronized ( transfers )
{
transferred = transfers.remove( transferEvent.getResource() );
}
if ( transferred != null )
{
event.setTransferredBytes( transferred.longValue() );
}
synchronized ( artifacts )
{
artifacts.remove( transferEvent.getResource() );
}
listener.transferCompleted( event );
}
public void transferError( TransferEvent transferEvent )
{
synchronized ( transfers )
{
transfers.remove( transferEvent.getResource() );
}
synchronized ( artifacts )
{
artifacts.remove( transferEvent.getResource() );
}
}
public void transferInitiated( TransferEvent transferEvent )
{
listener.transferInitiated( wrap( transferEvent ) );
}
public void transferProgress( TransferEvent transferEvent, byte[] buffer, int length )
{
Long transferred;
synchronized ( transfers )
{
transferred = transfers.get( transferEvent.getResource() );
if ( transferred == null )
{
transferred = Long.valueOf( length );
}
else
{
transferred = Long.valueOf( transferred.longValue() + length );
}
transfers.put( transferEvent.getResource(), transferred );
}
ArtifactTransferEvent event = wrap( transferEvent );
event.setDataBuffer( buffer );
event.setDataOffset( 0 );
event.setDataLength( length );
event.setTransferredBytes( transferred.longValue() );
listener.transferProgress( event );
}
public void transferStarted( TransferEvent transferEvent )
{
listener.transferStarted( wrap( transferEvent ) );
}
private ArtifactTransferEvent wrap( TransferEvent event )
{
if ( event == null )
{
return null;
}
else
{
String wagon = event.getWagon().getClass().getName();
ArtifactTransferResource artifact = wrap( event.getWagon().getRepository(), event.getResource() );
ArtifactTransferEvent evt;
if ( event.getException() != null )
{
evt = new ArtifactTransferEvent( wagon, event.getException(), event.getRequestType(), artifact );
}
else
{
evt = new ArtifactTransferEvent( wagon, event.getEventType(), event.getRequestType(), artifact );
}
evt.setLocalFile( event.getLocalFile() );
return evt;
}
}
private ArtifactTransferResource wrap( Repository repository, Resource resource )
{
if ( resource == null )
{
return null;
}
else
{
synchronized ( artifacts )
{
ArtifactTransferResource artifact = artifacts.get( resource );
if ( artifact == null )
{
artifact = new MavenArtifact( repository.getUrl(), resource );
artifacts.put( resource, artifact );
}
return artifact;
}
}
}
}
| sonatype/maven-demo | maven-compat/src/main/java/org/apache/maven/repository/legacy/TransferListenerAdapter.java | Java | apache-2.0 | 5,593 |
/*
* Swift Parallel Scripting Language (http://swift-lang.org)
* Code from Java CoG Kit Project (see notice below) with modifications.
*
* Copyright 2005-2014 University of Chicago
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//----------------------------------------------------------------------
//This code is developed as part of the Java CoG Kit project
//The terms of the license can be found at http://www.cogkit.org/license
//This message may not be removed or altered.
//----------------------------------------------------------------------
/*
* Created on Oct 3, 2009
*/
package org.globus.cog.coaster.channels;
public interface SendCallback {
void dataSent();
}
| swift-lang/swift-k | cogkit/modules/provider-coaster/src/org/globus/cog/coaster/channels/SendCallback.java | Java | apache-2.0 | 1,199 |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
//
// 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 General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
// THIS FILE IS AUTOGENERATED, PLEASE DO NOT EDIT OR ELSE
package gnu.trove;
/**
* Iterator for maps of type float and long.
* <p/>
* <p>The iterator semantics for Trove's primitive maps is slightly different
* from those defined in <tt>java.util.Iterator</tt>, but still well within
* the scope of the pattern, as defined by Gamma, et al.</p>
* <p/>
* <p>This iterator does <b>not</b> implicitly advance to the next entry when
* the value at the current position is retrieved. Rather, you must explicitly
* ask the iterator to <tt>advance()</tt> and then retrieve either the <tt>key()</tt>,
* the <tt>value()</tt> or both. This is done so that you have the option, but not
* the obligation, to retrieve keys and/or values as your application requires, and
* without introducing wrapper objects that would carry both. As the iteration is
* stateful, access to the key/value parts of the current map entry happens in
* constant time.</p>
* <p/>
* <p>In practice, the iterator is akin to a "search finger" that you move from
* position to position. Read or write operations affect the current entry only and
* do not assume responsibility for moving the finger.</p>
* <p/>
* <p>Here are some sample scenarios for this class of iterator:</p>
* <p/>
* <pre>
* // accessing keys/values through an iterator:
* for (TFloatLongIterator it = map.iterator();
* it.hasNext();) {
* it.forward();
* if (satisfiesCondition(it.key()) {
* doSomethingWithValue(it.value());
* }
* }
* </pre>
* <p/>
* <pre>
* // modifying values in-place through iteration:
* for (TFloatLongIterator it = map.iterator();
* it.hasNext();) {
* it.forward();
* if (satisfiesCondition(it.key()) {
* it.setValue(newValueForKey(it.key()));
* }
* }
* </pre>
* <p/>
* <pre>
* // deleting entries during iteration:
* for (TFloatLongIterator it = map.iterator();
* it.hasNext();) {
* it.forward();
* if (satisfiesCondition(it.key()) {
* it.remove();
* }
* }
* </pre>
* <p/>
* <pre>
* // faster iteration by avoiding hasNext():
* TFloatLongIterator iterator = map.iterator();
* for (int i = map.size(); i-- > 0;) {
* iterator.advance();
* doSomethingWithKeyAndValue(iterator.key(), iterator.value());
* }
* </pre>
*
* @author Eric D. Friedman
*/
public class TFloatLongIterator extends TPrimitiveIterator {
/**
* the collection being iterated over
*/
private final TFloatLongHashMap _map;
/**
* Creates an iterator over the specified map
*/
public TFloatLongIterator(TFloatLongHashMap map) {
super(map);
_map = map;
}
/**
* Moves the iterator forward to the next entry in the underlying map.
*
* @throws java.util.NoSuchElementException
* if the iterator is already exhausted
*/
public void advance() {
moveToNextIndex();
}
/**
* Provides access to the key of the mapping at the iterator's position.
* Note that you must <tt>advance()</tt> the iterator at least once
* before invoking this method.
*
* @return the key of the entry at the iterator's current position.
*/
public float key() {
return _map._set[_index];
}
/**
* Provides access to the value of the mapping at the iterator's position.
* Note that you must <tt>advance()</tt> the iterator at least once
* before invoking this method.
*
* @return the value of the entry at the iterator's current position.
*/
public long value() {
return _map._values[_index];
}
/**
* Replace the value of the mapping at the iterator's position with the
* specified value. Note that you must <tt>advance()</tt> the iterator at
* least once before invoking this method.
*
* @param val the value to set in the current entry
* @return the old value of the entry.
*/
public long setValue(long val) {
long old = value();
_map._values[_index] = val;
return old;
}
}// TFloatLongIterator
| amikey/haha | trove/trove4j-1.1-sources.jar-unzipped_flattened/TFloatLongIterator.java | Java | apache-2.0 | 5,039 |
// Copyright (C) 2016 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.httpd.plugins;
import static com.google.common.truth.Truth.assertThat;
import org.junit.Test;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class LfsPluginServletTest {
@Test
public void noLfsEndPoint_noMatch() {
Pattern p = Pattern.compile(LfsPluginServlet.URL_REGEX);
doesNotMatch(p, "/foo");
doesNotMatch(p, "/a/foo");
doesNotMatch(p, "/p/foo");
doesNotMatch(p, "/a/p/foo");
doesNotMatch(p, "/info/lfs/objects/batch");
doesNotMatch(p, "/info/lfs/objects/batch/foo");
}
@Test
public void matchingLfsEndpoint_projectNameCaptured() {
Pattern p = Pattern.compile(LfsPluginServlet.URL_REGEX);
matches(p, "/foo/bar/info/lfs/objects/batch", "foo/bar");
matches(p, "/a/foo/bar/info/lfs/objects/batch", "foo/bar");
matches(p, "/p/foo/bar/info/lfs/objects/batch", "foo/bar");
matches(p, "/a/p/foo/bar/info/lfs/objects/batch", "foo/bar");
}
private void doesNotMatch(Pattern p, String input) {
Matcher m = p.matcher(input);
assertThat(m.matches()).isFalse();
}
private void matches(Pattern p, String input, String expectedProjectName) {
Matcher m = p.matcher(input);
assertThat(m.matches()).isTrue();
assertThat(m.group(1)).isEqualTo(expectedProjectName);
}
}
| MerritCR/merrit | gerrit-httpd/src/test/java/com/google/gerrit/httpd/plugins/LfsPluginServletTest.java | Java | apache-2.0 | 1,909 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.geronimo.farm.deployment;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;
/**
*
* @version $Rev:$ $Date:$
*/
public class ZipDirectoryPackager implements DirectoryPackager {
public File pack(File configurationDir) throws IOException {
File zippedDir = File.createTempFile(configurationDir.getName(), ".zip");
OutputStream out = new FileOutputStream(zippedDir);
out = new BufferedOutputStream(out);
ZipOutputStream zos = new ZipOutputStream(out);
zip(zos, configurationDir, configurationDir);
zos.close();
return zippedDir;
}
public File unpack(File packedConfigurationDir) throws IOException {
String tmpDirAsString = System.getProperty("java.io.tmpdir");
File targetDir = new File(new File(tmpDirAsString), packedConfigurationDir.getName() + "_unpack");
unpack(targetDir, packedConfigurationDir);
return targetDir;
}
public void unpack(File targetDir, File packedConfigurationDir) throws IOException {
ZipFile zipFile = new ZipFile(packedConfigurationDir);
Enumeration<? extends ZipEntry> zipEntries = zipFile.entries();
while (zipEntries.hasMoreElements()) {
ZipEntry zipEntry = zipEntries.nextElement();
File targetFile = new File(targetDir, zipEntry.getName());
if (zipEntry.isDirectory()) {
targetFile.mkdirs();
} else {
targetFile.getParentFile().mkdirs();
targetFile.createNewFile();
OutputStream out = new FileOutputStream(targetFile);
out = new BufferedOutputStream(out);
InputStream in = zipFile.getInputStream(zipEntry);
byte[] buffer = new byte[1024];
int read;
while (-1 != (read = in.read(buffer))) {
out.write(buffer, 0, read);
}
in.close();
out.close();
}
}
zipFile.close();
}
protected void zip(ZipOutputStream zos, File configurationDir, File nestedFile) throws IOException {
if (nestedFile.isDirectory()) {
File[] nestedFiles = nestedFile.listFiles();
for (int i = 0; i < nestedFiles.length; i++) {
zip(zos, configurationDir, nestedFiles[i]);
}
} else {
String nestedFilePath = nestedFile.getAbsolutePath();
String zipEntryName = nestedFilePath.substring(configurationDir.getAbsolutePath().length() + 1, nestedFilePath.length());
ZipEntry zipEntry = new ZipEntry(normalizePathOfEntry(zipEntryName));
zos.putNextEntry(zipEntry);
InputStream in = new FileInputStream(nestedFile);
in = new BufferedInputStream(in);
byte[] buffer = new byte[1024];
int read;
while (-1 != (read = in.read(buffer))) {
zos.write(buffer, 0, read);
}
in.close();
zos.closeEntry();
}
}
private String normalizePathOfEntry(String entryName){
return entryName.replace('\\', '/');
}
}
| apache/geronimo | plugins/clustering/geronimo-deploy-farm/src/main/java/org/apache/geronimo/farm/deployment/ZipDirectoryPackager.java | Java | apache-2.0 | 4,382 |
/*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014-2015 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.ning.billing.recurly;
import org.testng.Assert;
import org.testng.annotations.Test;
public class TestPaginationUtils {
@Test(groups = "fast")
public void testParserNext() throws Exception {
final String linkHeader = "<https://your-subdomain.recurly.com/v2/accounts?cursor=1304958672>; rel=\"next\"";
final String[] links = PaginationUtils.getLinks(linkHeader);
Assert.assertNull(links[0]);
Assert.assertNull(links[1]);
Assert.assertEquals(links[2], "https://your-subdomain.recurly.com/v2/accounts?cursor=1304958672");
}
@Test(groups = "fast")
public void testParserAll() throws Exception {
final String linkHeader = "<https://your-subdomain.recurly.com/v2/transactions>; rel=\"start\",\n" +
" <https://your-subdomain.recurly.com/v2/transactions?cursor=-1318344434>; rel=\"prev\"\n" +
" <https://your-subdomain.recurly.com/v2/transactions?cursor=1318388868>; rel=\"next\"";
final String[] links = PaginationUtils.getLinks(linkHeader);
Assert.assertEquals(links[0], "https://your-subdomain.recurly.com/v2/transactions");
Assert.assertEquals(links[1], "https://your-subdomain.recurly.com/v2/transactions?cursor=-1318344434");
Assert.assertEquals(links[2], "https://your-subdomain.recurly.com/v2/transactions?cursor=1318388868");
}
}
| 7thsense/recurly-java-library | src/test/java/com/ning/billing/recurly/TestPaginationUtils.java | Java | apache-2.0 | 2,107 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.artemis.tests.integration.spring;
import java.util.concurrent.TimeUnit;
import org.apache.activemq.artemis.tests.integration.IntegrationTestLogger;
import org.apache.activemq.artemis.tests.util.ActiveMQTestBase;
import org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory;
import org.apache.activemq.artemis.jms.server.embedded.EmbeddedJMS;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jms.listener.DefaultMessageListenerContainer;
public class SpringIntegrationTest extends ActiveMQTestBase {
IntegrationTestLogger log = IntegrationTestLogger.LOGGER;
@Override
@Before
public void setUp() throws Exception {
super.setUp();
// Need to force GC as the connection on the spring needs to be cleared
// otherwise the sprint thread may leak here
forceGC();
}
@Test
public void testSpring() throws Exception {
System.out.println("Creating bean factory...");
ApplicationContext context = null;
try {
context = new ClassPathXmlApplicationContext(new String[]{"spring-jms-beans.xml"});
MessageSender sender = (MessageSender) context.getBean("MessageSender");
System.out.println("Sending message...");
ExampleListener.latch.countUp();
sender.send("Hello world");
ExampleListener.latch.await(10, TimeUnit.SECONDS);
Thread.sleep(500);
Assert.assertEquals(ExampleListener.lastMessage, "Hello world");
((ActiveMQConnectionFactory) sender.getConnectionFactory()).close();
}
finally {
try {
if (context != null) {
DefaultMessageListenerContainer container = (DefaultMessageListenerContainer) context.getBean("listenerContainer");
container.stop();
}
}
catch (Throwable ignored) {
ignored.printStackTrace();
}
try {
if (context != null) {
EmbeddedJMS jms = (EmbeddedJMS) context.getBean("EmbeddedJms");
jms.stop();
}
}
catch (Throwable ignored) {
ignored.printStackTrace();
}
}
}
}
| lburgazzoli/apache-activemq-artemis | tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/spring/SpringIntegrationTest.java | Java | apache-2.0 | 3,166 |
/*
* Licensed to Apereo under one or more contributor license
* agreements. See the NOTICE file distributed with this work
* for additional information regarding copyright ownership.
* Apereo licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a
* copy of the License at the following location:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.jasig.portlet.notice.service.filter;
import org.jasig.portlet.notice.NotificationCategory;
import org.jasig.portlet.notice.NotificationEntry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This concrete implementation of {@link INotificationFilter} filters out notices that have a title
* that matches the regex value.
*
* @since 4.3
*/
/* package-private */ class TitleTextNotificationFilter extends TextNotificationFilter {
private Logger logger = LoggerFactory.getLogger(getClass());
public TitleTextNotificationFilter(String regex) {
super(regex);
}
@Override
public boolean doFilter(NotificationCategory category, NotificationEntry entry) {
assert entry != null;
if (entry.getTitle() == null || entry.getTitle().isEmpty()) {
// nothing to check
return false;
}
final boolean match = pattern.matcher(entry.getTitle()).matches();
logger.debug("Testing against title: {} = {}", entry.getTitle(), match);
return !match;
}
}
| bjagg/NotificationPortlet | notification-portlet-webapp/src/main/java/org/jasig/portlet/notice/service/filter/TitleTextNotificationFilter.java | Java | apache-2.0 | 1,866 |
/*
* Copyright (c) 2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.identity.sso.saml.servlet;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.identity.application.authentication.framework.cache.AuthenticationRequestCacheEntry;
import org.wso2.carbon.identity.application.authentication.framework.cache.AuthenticationResultCache;
import org.wso2.carbon.identity.application.authentication.framework.cache.AuthenticationResultCacheEntry;
import org.wso2.carbon.identity.application.authentication.framework.cache.AuthenticationResultCacheKey;
import org.wso2.carbon.identity.application.authentication.framework.model.AuthenticationRequest;
import org.wso2.carbon.identity.application.authentication.framework.model.AuthenticationResult;
import org.wso2.carbon.identity.application.authentication.framework.util.FrameworkConstants;
import org.wso2.carbon.identity.application.authentication.framework.util.FrameworkUtils;
import org.wso2.carbon.identity.application.common.cache.CacheEntry;
import org.wso2.carbon.identity.base.IdentityConstants;
import org.wso2.carbon.identity.base.IdentityException;
import org.wso2.carbon.identity.core.util.IdentityUtil;
import org.wso2.carbon.identity.sso.saml.SAMLSSOConstants;
import org.wso2.carbon.identity.sso.saml.SAMLSSOService;
import org.wso2.carbon.identity.sso.saml.cache.SessionDataCache;
import org.wso2.carbon.identity.sso.saml.cache.SessionDataCacheEntry;
import org.wso2.carbon.identity.sso.saml.cache.SessionDataCacheKey;
import org.wso2.carbon.identity.sso.saml.dto.SAMLSSOAuthnReqDTO;
import org.wso2.carbon.identity.sso.saml.dto.SAMLSSOReqValidationResponseDTO;
import org.wso2.carbon.identity.sso.saml.dto.SAMLSSORespDTO;
import org.wso2.carbon.identity.sso.saml.dto.SAMLSSOSessionDTO;
import org.wso2.carbon.identity.sso.saml.internal.IdentitySAMLSSOServiceComponent;
import org.wso2.carbon.identity.sso.saml.logout.LogoutRequestSender;
import org.wso2.carbon.identity.sso.saml.util.SAMLSSOUtil;
import org.wso2.carbon.registry.core.utils.UUIDGenerator;
import org.wso2.carbon.ui.CarbonUIUtil;
import org.wso2.carbon.ui.util.CharacterEncoder;
import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
/**
* This is the entry point for authentication process in an SSO scenario. This servlet is registered
* with the URL pattern /samlsso and act as the control servlet. The message flow of an SSO scenario
* is as follows.
* <ol>
* <li>SP sends a SAML Request via HTTP POST to the https://<ip>:<port>/samlsso endpoint.</li>
* <li>IdP validates the SAML Request and checks whether this user is already authenticated.</li>
* <li>If the user is authenticated, it will generate a SAML Response and send it back the SP via
* the samlsso_redirect_ajaxprocessor.jsp.</li>
* <li>If the user is not authenticated, it will send him to the login page and prompts user to
* enter his credentials.</li>
* <li>If these credentials are valid, then the user will be redirected back the SP with a valid
* SAML Assertion. If not, he will be prompted again for credentials.</li>
* </ol>
*/
public class SAMLSSOProviderServlet extends HttpServlet {
private static final long serialVersionUID = -5182312441482721905L;
private static Log log = LogFactory.getLog(SAMLSSOProviderServlet.class);
private SAMLSSOService samlSsoService = new SAMLSSOService();
@Override
protected void doGet(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse) throws ServletException, IOException {
try {
handleRequest(httpServletRequest, httpServletResponse, false);
} finally {
SAMLSSOUtil.removeSaaSApplicationThreaLocal();
SAMLSSOUtil.removeUserTenantDomainThreaLocal();
SAMLSSOUtil.removeTenantDomainFromThreadLocal();
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
try {
handleRequest(req, resp, true);
} finally {
SAMLSSOUtil.removeSaaSApplicationThreaLocal();
SAMLSSOUtil.removeUserTenantDomainThreaLocal();
SAMLSSOUtil.removeTenantDomainFromThreadLocal();
}
}
/**
* All requests are handled by this handleRequest method. In case of SAMLRequest the user
* will be redirected to commonAuth servlet for authentication. Based on successful
* authentication of the user a SAMLResponse is sent back to service provider.
* In case of logout requests, the IDP will send logout requests
* to the other session participants and then send the logout response back to the initiator.
*
* @param req
* @param resp
* @throws ServletException
* @throws IOException
*/
private void handleRequest(HttpServletRequest req, HttpServletResponse resp, boolean isPost)
throws ServletException, IOException {
String sessionId = null;
Cookie ssoTokenIdCookie = getTokenIdCookie(req);
if (ssoTokenIdCookie != null) {
sessionId = ssoTokenIdCookie.getValue();
}
Cookie rememberMeCookie = getRememberMeCookie(req);
if (rememberMeCookie != null) {
sessionId = rememberMeCookie.getValue();
}
String queryString = req.getQueryString();
if (log.isDebugEnabled()) {
log.debug("Query string : " + queryString);
}
// if an openid authentication or password authentication
String authMode = CharacterEncoder.getSafeText(req.getParameter("authMode"));
if (!SAMLSSOConstants.AuthnModes.OPENID.equals(authMode)) {
authMode = SAMLSSOConstants.AuthnModes.USERNAME_PASSWORD;
}
String relayState = CharacterEncoder.getSafeText(req.getParameter(SAMLSSOConstants.RELAY_STATE));
String spEntityID = CharacterEncoder.getSafeText(req.getParameter("spEntityID"));
String samlRequest = CharacterEncoder.getSafeText(req.getParameter("SAMLRequest"));
String sessionDataKey = CharacterEncoder.getSafeText(req.getParameter("sessionDataKey"));
boolean isExpFired = false;
try {
String tenantDomain = CharacterEncoder.getSafeText(req.getParameter("tenantDomain"));
SAMLSSOUtil.setTenantDomainInThreadLocal(tenantDomain);
if (sessionDataKey != null) { //Response from common authentication framework.
SAMLSSOSessionDTO sessionDTO = getSessionDataFromCache(sessionDataKey);
if (sessionDTO != null) {
SAMLSSOUtil.setTenantDomainInThreadLocal(sessionDTO.getTenantDomain());
if (sessionDTO.isInvalidLogout()) {
String errorResp = SAMLSSOUtil.buildErrorResponse(
SAMLSSOConstants.StatusCodes.REQUESTOR_ERROR,
"Invalid SAML SSO Logout Request");
sendNotification(errorResp, SAMLSSOConstants.Notification.INVALID_MESSAGE_STATUS,
SAMLSSOConstants.Notification.INVALID_MESSAGE_MESSAGE,
sessionDTO.getAssertionConsumerURL(), req, resp);
return;
}
if (sessionDTO.isLogoutReq()) {
handleLogoutReponseFromFramework(req, resp, sessionDTO);
} else {
handleAuthenticationReponseFromFramework(req, resp, sessionId, sessionDTO);
}
removeAuthenticationResultFromCache(sessionDataKey);
} else {
log.error("Failed to retrieve sessionDTO from the cache for key " + sessionDataKey);
String errorResp = SAMLSSOUtil.buildErrorResponse(
SAMLSSOConstants.StatusCodes.IDENTITY_PROVIDER_ERROR,
SAMLSSOConstants.Notification.EXCEPTION_STATUS);
sendNotification(errorResp, SAMLSSOConstants.Notification.EXCEPTION_STATUS,
SAMLSSOConstants.Notification.EXCEPTION_MESSAGE, null, req, resp);
return;
}
} else if (spEntityID != null) { // idp initiated SSO
handleIdPInitSSO(req, resp, spEntityID, relayState, queryString, authMode, sessionId);
} else if (samlRequest != null) {// SAMLRequest received. SP initiated SSO
handleSPInitSSO(req, resp, queryString, relayState, authMode, samlRequest, sessionId, isPost);
} else {
log.debug("Invalid request message or single logout message ");
if (sessionId == null) {
String errorResp = SAMLSSOUtil.buildErrorResponse(
SAMLSSOConstants.StatusCodes.REQUESTOR_ERROR,
"Invalid request message");
sendNotification(errorResp, SAMLSSOConstants.Notification.INVALID_MESSAGE_STATUS,
SAMLSSOConstants.Notification.INVALID_MESSAGE_MESSAGE, null, req, resp);
} else {
// Non-SAML request are assumed to be logout requests
sendToFrameworkForLogout(req, resp, null, null, sessionId, true, false);
}
}
} catch (UserStoreException e) {
if (log.isDebugEnabled()) {
log.debug("Error occurred while handling SAML2 SSO request", e);
}
String errorResp = null;
try {
errorResp = SAMLSSOUtil.buildErrorResponse(
SAMLSSOConstants.StatusCodes.IDENTITY_PROVIDER_ERROR,
"Error occurred while handling SAML2 SSO request");
} catch (IdentityException e1) {
log.error("Error while building SAML response", e1);
}
sendNotification(errorResp, SAMLSSOConstants.Notification.EXCEPTION_STATUS,
SAMLSSOConstants.Notification.EXCEPTION_MESSAGE, null, req, resp);
} catch (IdentityException e) {
log.error("Error when processing the authentication request!", e);
String errorResp = null;
try {
errorResp = SAMLSSOUtil.buildErrorResponse(
SAMLSSOConstants.StatusCodes.IDENTITY_PROVIDER_ERROR,
"Error when processing the authentication request");
} catch (IdentityException e1) {
log.error("Error while building SAML response", e1);
}
sendNotification(errorResp, SAMLSSOConstants.Notification.EXCEPTION_STATUS,
SAMLSSOConstants.Notification.EXCEPTION_MESSAGE, null, req, resp);
}
}
/**
* Prompts user a notification with the status and message
*
* @param req
* @param resp
* @throws ServletException
* @throws IOException
*/
private void sendNotification(String errorResp, String status, String message,
String acUrl, HttpServletRequest req,
HttpServletResponse resp) throws ServletException, IOException {
String redirectURL = CarbonUIUtil.getAdminConsoleURL(req);
redirectURL = redirectURL.replace("samlsso/carbon/",
"authenticationendpoint/samlsso_notification.do");
//TODO Send status codes rather than full messages in the GET request
String queryParams = "?" + SAMLSSOConstants.STATUS + "=" + URLEncoder.encode(status, "UTF-8") +
"&" + SAMLSSOConstants.STATUS_MSG + "=" + URLEncoder.encode(message, "UTF-8");
if (errorResp != null) {
queryParams += "&" + SAMLSSOConstants.SAML_RESP + "=" + URLEncoder.encode(errorResp, "UTF-8");
}
if (acUrl != null) {
queryParams += "&" + SAMLSSOConstants.ASSRTN_CONSUMER_URL + "=" + URLEncoder.encode(acUrl, "UTF-8");
}
resp.sendRedirect(redirectURL + queryParams);
}
private void handleIdPInitSSO(HttpServletRequest req, HttpServletResponse resp, String spEntityID, String relayState,
String queryString, String authMode, String sessionId)
throws UserStoreException, IdentityException, IOException, ServletException {
String rpSessionId = CharacterEncoder.getSafeText(req.getParameter(MultitenantConstants.SSO_AUTH_SESSION_ID));
SAMLSSOService samlSSOService = new SAMLSSOService();
SAMLSSOReqValidationResponseDTO signInRespDTO = samlSSOService.validateIdPInitSSORequest(req, resp,
spEntityID, relayState, queryString, sessionId, rpSessionId, authMode);
if (signInRespDTO.isValid()) {
sendToFrameworkForAuthentication(req, resp, signInRespDTO, relayState, false);
} else {
if (log.isDebugEnabled()) {
log.debug("Invalid SAML SSO Request");
}
String errorResp = signInRespDTO.getResponse();
sendNotification(errorResp, SAMLSSOConstants.Notification.EXCEPTION_STATUS,
SAMLSSOConstants.Notification.EXCEPTION_MESSAGE,
signInRespDTO.getAssertionConsumerURL(), req, resp);
}
}
/**
* If the SAMLRequest is a Logout request then IDP will send logout requests to other session
* participants and then sends the logout Response back to the initiator. In case of
* authentication request, check if there is a valid session for the user, if there is, the user
* will be redirected directly to the Service Provider, if not the user will be redirected to
* the login page.
*
* @param req
* @param resp
* @param sessionId
* @param samlRequest
* @param relayState
* @param authMode
* @throws IdentityException
* @throws IOException
* @throws ServletException
* @throws org.wso2.carbon.identity.base.IdentityException
*/
private void handleSPInitSSO(HttpServletRequest req, HttpServletResponse resp,
String queryString, String relayState, String authMode,
String samlRequest, String sessionId, boolean isPost)
throws UserStoreException, IdentityException, IOException, ServletException {
String rpSessionId = CharacterEncoder.getSafeText(req.getParameter(MultitenantConstants.SSO_AUTH_SESSION_ID));
SAMLSSOService samlSSOService = new SAMLSSOService();
SAMLSSOReqValidationResponseDTO signInRespDTO = samlSSOService.validateSPInitSSORequest(
samlRequest, queryString, sessionId, rpSessionId, authMode, isPost);
if (!signInRespDTO.isLogOutReq()) { // an <AuthnRequest> received
if (signInRespDTO.isValid()) {
sendToFrameworkForAuthentication(req, resp, signInRespDTO, relayState, isPost);
} else {
// send invalid response to SP TODO
if (log.isDebugEnabled()) {
log.debug("Invalid SAML SSO Request");
}
String errorResp = signInRespDTO.getResponse();
sendNotification(errorResp, SAMLSSOConstants.Notification.EXCEPTION_STATUS,
SAMLSSOConstants.Notification.EXCEPTION_MESSAGE,
signInRespDTO.getAssertionConsumerURL(), req, resp);
}
} else { // a <LogoutRequest> received
if (signInRespDTO.isValid()) {
sendToFrameworkForLogout(req, resp, signInRespDTO, relayState, sessionId, false, isPost);
} else {
// send invalid response to SP TODO
if (log.isDebugEnabled()) {
log.debug("Invalid SAML SSO Logout Request");
}
String errorResp = signInRespDTO.getResponse();
sendNotification(errorResp, SAMLSSOConstants.Notification.EXCEPTION_STATUS,
SAMLSSOConstants.Notification.EXCEPTION_MESSAGE,
signInRespDTO.getAssertionConsumerURL(), req, resp);
}
}
}
/**
* Sends the user for authentication to the login page
*
* @param req
* @param resp
* @param signInRespDTO
* @param relayState
* @throws ServletException
* @throws IOException
*/
private void sendToFrameworkForAuthentication(HttpServletRequest req, HttpServletResponse resp,
SAMLSSOReqValidationResponseDTO signInRespDTO, String relayState, boolean isPost)
throws ServletException, IOException, UserStoreException, IdentityException {
SAMLSSOSessionDTO sessionDTO = new SAMLSSOSessionDTO();
sessionDTO.setHttpQueryString(req.getQueryString());
sessionDTO.setDestination(signInRespDTO.getDestination());
sessionDTO.setRelayState(relayState);
sessionDTO.setRequestMessageString(signInRespDTO.getRequestMessageString());
sessionDTO.setIssuer(signInRespDTO.getIssuer());
sessionDTO.setRequestID(signInRespDTO.getId());
sessionDTO.setSubject(signInRespDTO.getSubject());
sessionDTO.setRelyingPartySessionId(signInRespDTO.getRpSessionId());
sessionDTO.setAssertionConsumerURL(signInRespDTO.getAssertionConsumerURL());
sessionDTO.setTenantDomain(SAMLSSOUtil.getTenantDomainFromThreadLocal());
if (sessionDTO.getTenantDomain() == null) {
String[] splitIssuer = sessionDTO.getIssuer().split("@");
if (splitIssuer != null && splitIssuer.length == 2 &&
!splitIssuer[0].trim().isEmpty() && !splitIssuer[1].trim().isEmpty()) {
sessionDTO.setTenantDomain(splitIssuer[1]);
} else {
sessionDTO.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
}
}
SAMLSSOUtil.setTenantDomainInThreadLocal(sessionDTO.getTenantDomain());
sessionDTO.setForceAuth(signInRespDTO.isForceAuthn());
sessionDTO.setPassiveAuth(signInRespDTO.isPassive());
sessionDTO.setValidationRespDTO(signInRespDTO);
sessionDTO.setIdPInitSSO(signInRespDTO.isIdPInitSSO());
String sessionDataKey = UUIDGenerator.generateUUID();
addSessionDataToCache(sessionDataKey, sessionDTO, req.getSession().getMaxInactiveInterval());
String commonAuthURL = CarbonUIUtil.getAdminConsoleURL(req);
commonAuthURL = commonAuthURL.replace(FrameworkConstants.RequestType
.CLAIM_TYPE_SAML_SSO + "/" + FrameworkConstants.CARBON + "/",
FrameworkConstants.COMMONAUTH);
String selfPath = URLEncoder.encode("/" + FrameworkConstants.RequestType
.CLAIM_TYPE_SAML_SSO, "UTF-8");
// Setting authentication request context
AuthenticationRequest authenticationRequest = new AuthenticationRequest();
// Adding query parameters
authenticationRequest.appendRequestQueryParams(req.getParameterMap());
for (Enumeration headerNames = req.getHeaderNames(); headerNames.hasMoreElements(); ) {
String headerName = headerNames.nextElement().toString();
authenticationRequest.addHeader(headerName, req.getHeader(headerName));
}
authenticationRequest.setRelyingParty(signInRespDTO.getIssuer());
authenticationRequest.setCommonAuthCallerPath(selfPath);
authenticationRequest.setForceAuth(signInRespDTO.isForceAuthn());
if (!authenticationRequest.getForceAuth() && authenticationRequest.getRequestQueryParam("forceAuth") != null) {
String[] forceAuth = authenticationRequest.getRequestQueryParam("forceAuth");
if (!forceAuth[0].trim().isEmpty() && Boolean.parseBoolean(forceAuth[0].trim())) {
authenticationRequest.setForceAuth(Boolean.parseBoolean(forceAuth[0].trim()));
}
}
authenticationRequest.setPassiveAuth(signInRespDTO.isPassive());
authenticationRequest.setTenantDomain(sessionDTO.getTenantDomain());
authenticationRequest.setPost(isPost);
// Creating cache entry and adding entry to the cache before calling to commonauth
AuthenticationRequestCacheEntry authRequest = new AuthenticationRequestCacheEntry
(authenticationRequest);
FrameworkUtils.addAuthenticationRequestToCache(sessionDataKey, authRequest,
req.getSession().getMaxInactiveInterval());
StringBuilder queryStringBuilder = new StringBuilder();
queryStringBuilder.append(commonAuthURL).
append("?").
append(SAMLSSOConstants.SESSION_DATA_KEY).
append("=").
append(sessionDataKey).
append("&").
append(FrameworkConstants.RequestParams.TYPE).
append("=").
append(FrameworkConstants.RequestType.CLAIM_TYPE_SAML_SSO);
FrameworkUtils.setRequestPathCredentials(req);
resp.sendRedirect(queryStringBuilder.toString());
}
private void sendToFrameworkForLogout(HttpServletRequest request, HttpServletResponse response,
SAMLSSOReqValidationResponseDTO signInRespDTO, String relayState, String sessionId,
boolean invalid, boolean isPost) throws ServletException, IOException {
if (sessionId != null) {
SAMLSSOSessionDTO sessionDTO = new SAMLSSOSessionDTO();
sessionDTO.setHttpQueryString(request.getQueryString());
sessionDTO.setRelayState(relayState);
sessionDTO.setSessionId(sessionId);
sessionDTO.setLogoutReq(true);
sessionDTO.setInvalidLogout(invalid);
if (signInRespDTO != null) {
sessionDTO.setDestination(signInRespDTO.getDestination());
sessionDTO.setRequestMessageString(signInRespDTO.getRequestMessageString());
sessionDTO.setIssuer(signInRespDTO.getIssuer());
sessionDTO.setRequestID(signInRespDTO.getId());
sessionDTO.setSubject(signInRespDTO.getSubject());
sessionDTO.setRelyingPartySessionId(signInRespDTO.getRpSessionId());
sessionDTO.setAssertionConsumerURL(signInRespDTO.getAssertionConsumerURL());
sessionDTO.setValidationRespDTO(signInRespDTO);
}
String sessionDataKey = UUIDGenerator.generateUUID();
addSessionDataToCache(sessionDataKey, sessionDTO, request.getSession().getMaxInactiveInterval());
String commonAuthURL = CarbonUIUtil.getAdminConsoleURL(request);
commonAuthURL = commonAuthURL.replace("samlsso/carbon/", "commonauth");
String selfPath = URLEncoder.encode("/samlsso", "UTF-8");
//Add all parameters to authentication context before sending to authentication
// framework
AuthenticationRequest authenticationRequest = new
AuthenticationRequest();
authenticationRequest.addRequestQueryParam(FrameworkConstants.RequestParams.LOGOUT,
new String[]{"true"});
authenticationRequest.setRequestQueryParams(request.getParameterMap());
authenticationRequest.setCommonAuthCallerPath(selfPath);
authenticationRequest.setPost(isPost);
if (signInRespDTO != null) {
authenticationRequest.setRelyingParty(signInRespDTO.getIssuer());
}
authenticationRequest.appendRequestQueryParams(request.getParameterMap());
//Add headers to AuthenticationRequestContext
for (Enumeration e = request.getHeaderNames(); e.hasMoreElements(); ) {
String headerName = e.nextElement().toString();
authenticationRequest.addHeader(headerName, request.getHeader(headerName));
}
AuthenticationRequestCacheEntry authRequest = new AuthenticationRequestCacheEntry
(authenticationRequest);
FrameworkUtils.addAuthenticationRequestToCache(sessionDataKey, authRequest,
request.getSession().getMaxInactiveInterval());
String queryParams = "?" + SAMLSSOConstants.SESSION_DATA_KEY + "=" + sessionDataKey
+ "&" + "type" + "=" + "samlsso";
response.sendRedirect(commonAuthURL + queryParams);
}
}
/**
* Sends the Response message back to the Service Provider.
*
* @param req
* @param resp
* @param relayState
* @param response
* @param acUrl
* @param subject
* @throws ServletException
* @throws IOException
*/
private void sendResponse(HttpServletRequest req, HttpServletResponse resp, String relayState,
String response, String acUrl, String subject, String authenticatedIdPs,
String tenantDomain)
throws ServletException, IOException, IdentityException {
if (relayState != null) {
relayState = URLDecoder.decode(relayState, "UTF-8");
relayState = relayState.replaceAll("&", "&").replaceAll("\"", """).replaceAll("'", "'").
replaceAll("<", "<").replaceAll(">", ">").replace("\n", "");
} else {
relayState = "null";
}
acUrl = getACSUrlWithTenantPartitioning(acUrl, tenantDomain);
if (acUrl == null || acUrl.trim().length() == 0) {
// if ACS is null. Send to error page
log.error("ACS Url is Null");
throw new IdentityException("Unexpected error in sending message out");
}
if (response == null || response.trim().length() == 0) {
// if response is null
log.error("Response message is Null");
throw new IdentityException("Unexpected error in sending message out");
}
if (IdentitySAMLSSOServiceComponent.getSsoRedirectHtml() != null) {
String finalPage = null;
String htmlPage = IdentitySAMLSSOServiceComponent.getSsoRedirectHtml();
String pageWithAcs = htmlPage.replace("$acUrl", acUrl);
String pageWithAcsResponse = pageWithAcs.replace("$response", response);
String pageWithAcsResponseRelay;
pageWithAcsResponseRelay = pageWithAcsResponse.replace("$relayState", relayState);
if (authenticatedIdPs == null || authenticatedIdPs.isEmpty()) {
finalPage = pageWithAcsResponseRelay;
} else {
finalPage = pageWithAcsResponseRelay.replace(
"<!--$additionalParams-->",
"<input type='hidden' name='AuthenticatedIdPs' value='"
+ URLEncoder.encode(authenticatedIdPs, "UTF-8") + "'>");
}
PrintWriter out = resp.getWriter();
out.print(finalPage);
if (log.isDebugEnabled()) {
log.debug("sso_redirect.html " + finalPage);
}
} else {
PrintWriter out = resp.getWriter();
out.println("<html>");
out.println("<body>");
out.println("<p>You are now redirected back to " + acUrl);
out.println(" If the redirection fails, please click the post button.</p>");
out.println("<form method='post' action='" + acUrl + "'>");
out.println("<p>");
out.println("<input type='hidden' name='SAMLResponse' value='" + response + "'>");
out.println("<input type='hidden' name='RelayState' value='" + relayState + "'>");
if (authenticatedIdPs != null && !authenticatedIdPs.isEmpty()) {
out.println("<input type='hidden' name='AuthenticatedIdPs' value='" + authenticatedIdPs + "'>");
}
out.println("<button type='submit'>POST</button>");
out.println("</p>");
out.println("</form>");
out.println("<script type='text/javascript'>");
out.println("document.forms[0].submit();");
out.println("</script>");
out.println("</body>");
out.println("</html>");
}
}
/**
* This method handles authentication and sends authentication Response message back to the
* Service Provider after successful authentication. In case of authentication failure the user
* is prompted back for authentication.
*
* @param req
* @param resp
* @param sessionId
* @throws IdentityException
* @throws IOException
* @throws ServletException
*/
private void handleAuthenticationReponseFromFramework(HttpServletRequest req, HttpServletResponse resp,
String sessionId, SAMLSSOSessionDTO sessionDTO)
throws UserStoreException, IdentityException, IOException, ServletException {
String sessionDataKey = CharacterEncoder.getSafeText(req.getParameter("sessionDataKey"));
AuthenticationResult authResult = getAuthenticationResultFromCache(sessionDataKey);
if (log.isDebugEnabled() && authResult == null) {
log.debug("Session data is not found for key : " + sessionDataKey);
}
SAMLSSOReqValidationResponseDTO reqValidationDTO = sessionDTO.getValidationRespDTO();
SAMLSSOAuthnReqDTO authnReqDTO = new SAMLSSOAuthnReqDTO();
if (authResult == null || !authResult.isAuthenticated()) {
if (log.isDebugEnabled() && authResult != null) {
log.debug("Unauthenticated User");
}
if (reqValidationDTO.isPassive()) { //if passive
List<String> statusCodes = new ArrayList<String>();
statusCodes.add(SAMLSSOConstants.StatusCodes.NO_PASSIVE);
statusCodes.add(SAMLSSOConstants.StatusCodes.IDENTITY_PROVIDER_ERROR);
reqValidationDTO.setResponse(SAMLSSOUtil.buildErrorResponse(
reqValidationDTO.getId(), statusCodes,
"Cannot authenticate Subject in Passive Mode"));
sendResponse(req, resp, sessionDTO.getRelayState(), reqValidationDTO.getResponse(),
reqValidationDTO.getAssertionConsumerURL(), reqValidationDTO.getSubject(),
null, sessionDTO.getTenantDomain());
return;
} else { // if forceAuthn or normal flow
//TODO send a saml response with a status message.
if (!authResult.isAuthenticated()) {
String errorResp = SAMLSSOUtil.buildErrorResponse(
SAMLSSOConstants.StatusCodes.AUTHN_FAILURE,
"User authentication failed");
sendNotification(errorResp, SAMLSSOConstants.Notification.EXCEPTION_STATUS,
SAMLSSOConstants.Notification.EXCEPTION_MESSAGE,
reqValidationDTO.getAssertionConsumerURL(), req, resp);
return;
} else {
throw new IdentityException("Session data is not found for authenticated user");
}
}
} else {
populateAuthnReqDTO(req, authnReqDTO, sessionDTO, authResult);
req.setAttribute(SAMLSSOConstants.AUTHENTICATION_RESULT, authResult);
String relayState = null;
if (req.getParameter(SAMLSSOConstants.RELAY_STATE) != null) {
relayState = req.getParameter(SAMLSSOConstants.RELAY_STATE);
} else {
relayState = sessionDTO.getRelayState();
}
startTenantFlow(authnReqDTO.getTenantDomain());
if (sessionId == null && !sessionDTO.isPassiveAuth()) {
sessionId = UUIDGenerator.generateUUID();
}
SAMLSSOService samlSSOService = new SAMLSSOService();
SAMLSSORespDTO authRespDTO = samlSSOService.authenticate(authnReqDTO, sessionId, authResult.isAuthenticated(),
authResult.getAuthenticatedAuthenticators(), SAMLSSOConstants.AuthnModes.USERNAME_PASSWORD);
if (authRespDTO.isSessionEstablished()) { // authenticated
if (StringUtils.equals(req.getParameter("chkRemember"), "on")) {
storeRememberMeCookie(sessionId, req, resp, SAMLSSOService.getSSOSessionTimeout());
}
storeTokenIdCookie(sessionId, req, resp);
removeSessionDataFromCache(CharacterEncoder.getSafeText(req.getParameter("sessionDataKey")));
sendResponse(req, resp, relayState, authRespDTO.getRespString(),
authRespDTO.getAssertionConsumerURL(), authRespDTO.getSubject().getAuthenticatedSubjectIdentifier(),
authResult.getAuthenticatedIdPs(), sessionDTO.getTenantDomain());
} else { // authentication FAILURE
String errorResp = authRespDTO.getRespString();
sendNotification(errorResp, SAMLSSOConstants.Notification.EXCEPTION_STATUS,
SAMLSSOConstants.Notification.EXCEPTION_MESSAGE,
authRespDTO.getAssertionConsumerURL(), req, resp);
}
}
}
private void handleLogoutReponseFromFramework(HttpServletRequest request,
HttpServletResponse response, SAMLSSOSessionDTO sessionDTO)
throws ServletException, IOException, IdentityException {
SAMLSSOReqValidationResponseDTO validatonResponseDTO = sessionDTO.getValidationRespDTO();
if (validatonResponseDTO != null) {
// sending LogoutRequests to other session participants
LogoutRequestSender.getInstance().sendLogoutRequests(validatonResponseDTO.getLogoutRespDTO());
SAMLSSOUtil.removeSession(sessionDTO.getSessionId(), validatonResponseDTO.getIssuer());
removeSessionDataFromCache(CharacterEncoder.getSafeText(request.getParameter("sessionDataKey")));
// sending LogoutResponse back to the initiator
sendResponse(request, response, sessionDTO.getRelayState(), validatonResponseDTO.getLogoutResponse(),
validatonResponseDTO.getAssertionConsumerURL(), validatonResponseDTO.getSubject(), null,
sessionDTO.getTenantDomain());
} else {
try {
samlSsoService.doSingleLogout(request.getSession().getId());
} catch (IdentityException e) {
log.error("Error when processing the logout request!", e);
}
String errorResp = SAMLSSOUtil.buildErrorResponse(
SAMLSSOConstants.StatusCodes.REQUESTOR_ERROR,
"Invalid request");
sendNotification(errorResp, SAMLSSOConstants.Notification.INVALID_MESSAGE_STATUS,
SAMLSSOConstants.Notification.INVALID_MESSAGE_MESSAGE,
sessionDTO.getAssertionConsumerURL(), request, response);
}
}
/**
* @param req
* @param authnReqDTO
*/
private void populateAuthnReqDTO(HttpServletRequest req, SAMLSSOAuthnReqDTO authnReqDTO,
SAMLSSOSessionDTO sessionDTO, AuthenticationResult authResult)
throws UserStoreException, IdentityException {
authnReqDTO.setAssertionConsumerURL(sessionDTO.getAssertionConsumerURL());
authnReqDTO.setId(sessionDTO.getRequestID());
authnReqDTO.setIssuer(sessionDTO.getIssuer());
authnReqDTO.setSubject(sessionDTO.getSubject());
authnReqDTO.setRpSessionId(sessionDTO.getRelyingPartySessionId());
authnReqDTO.setRequestMessageString(sessionDTO.getRequestMessageString());
authnReqDTO.setQueryString(sessionDTO.getHttpQueryString());
authnReqDTO.setDestination(sessionDTO.getDestination());
authnReqDTO.setUser(authResult.getSubject());
authnReqDTO.setIdPInitSSO(sessionDTO.isIdPInitSSO());
authnReqDTO.setClaimMapping(authResult.getClaimMapping());
authnReqDTO.setTenantDomain(sessionDTO.getTenantDomain());
SAMLSSOUtil.setIsSaaSApplication(authResult.isSaaSApp());
SAMLSSOUtil.setUserTenantDomain(authResult.getAuthenticatedUserTenantDomain());
}
/**
* @param req
* @return
*/
private Cookie getRememberMeCookie(HttpServletRequest req) {
Cookie[] cookies = req.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if (StringUtils.equals(cookie.getName(), "samlssoRememberMe")) {
return cookie;
}
}
}
return null;
}
/**
* @param sessionId
* @param req
* @param resp
*/
private void storeRememberMeCookie(String sessionId, HttpServletRequest req, HttpServletResponse resp,
int sessionTimeout) {
Cookie rememberMeCookie = getRememberMeCookie(req);
if (rememberMeCookie == null) {
rememberMeCookie = new Cookie("samlssoRememberMe", sessionId);
}
rememberMeCookie.setMaxAge(sessionTimeout);
rememberMeCookie.setSecure(true);
rememberMeCookie.setHttpOnly(true);
resp.addCookie(rememberMeCookie);
}
public void removeRememberMeCookie(HttpServletRequest req, HttpServletResponse resp) {
Cookie[] cookies = req.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if (StringUtils.equals(cookie.getName(), "samlssoRememberMe")) {
cookie.setMaxAge(0);
resp.addCookie(cookie);
break;
}
}
}
}
private Cookie getTokenIdCookie(HttpServletRequest req) {
Cookie[] cookies = req.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if (StringUtils.equals(cookie.getName(), "samlssoTokenId")) {
return cookie;
}
}
}
return null;
}
/**
* @param sessionId
* @param req
* @param resp
*/
private void storeTokenIdCookie(String sessionId, HttpServletRequest req, HttpServletResponse resp) {
Cookie rememberMeCookie = getRememberMeCookie(req);
if (rememberMeCookie == null) {
rememberMeCookie = new Cookie("samlssoTokenId", sessionId);
rememberMeCookie.setMaxAge(SAMLSSOService.getSSOSessionTimeout());
rememberMeCookie.setSecure(true);
rememberMeCookie.setHttpOnly(true);
}
resp.addCookie(rememberMeCookie);
}
public void removeTokenIdCookie(HttpServletRequest req, HttpServletResponse resp) {
Cookie[] cookies = req.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if (StringUtils.equals(cookie.getName(), "samlssoTokenId")) {
cookie.setMaxAge(0);
resp.addCookie(cookie);
break;
}
}
}
}
private String getACSUrlWithTenantPartitioning(String acsUrl, String tenantDomain) {
String acsUrlWithTenantDomain = acsUrl;
if (tenantDomain != null && "true".equals(IdentityUtil.getProperty(
IdentityConstants.ServerConfig.SSO_TENANT_PARTITIONING_ENABLED))) {
acsUrlWithTenantDomain =
acsUrlWithTenantDomain + "?" +
MultitenantConstants.TENANT_DOMAIN + "=" + tenantDomain;
}
return acsUrlWithTenantDomain;
}
private void addSessionDataToCache(String sessionDataKey, SAMLSSOSessionDTO sessionDTO, int cacheTimeout) {
SessionDataCacheKey cacheKey = new SessionDataCacheKey(sessionDataKey);
SessionDataCacheEntry cacheEntry = new SessionDataCacheEntry();
cacheEntry.setSessionDTO(sessionDTO);
SessionDataCache.getInstance(cacheTimeout).addToCache(cacheKey, cacheEntry);
}
private SAMLSSOSessionDTO getSessionDataFromCache(String sessionDataKey) {
SAMLSSOSessionDTO sessionDTO = null;
SessionDataCacheKey cacheKey = new SessionDataCacheKey(sessionDataKey);
Object cacheEntryObj = SessionDataCache.getInstance(0).getValueFromCache(cacheKey);
if (cacheEntryObj != null) {
sessionDTO = ((SessionDataCacheEntry) cacheEntryObj).getSessionDTO();
}
return sessionDTO;
}
private void removeSessionDataFromCache(String sessionDataKey) {
if (sessionDataKey != null) {
SessionDataCacheKey cacheKey = new SessionDataCacheKey(sessionDataKey);
SessionDataCache.getInstance(0).clearCacheEntry(cacheKey);
}
}
private AuthenticationResult getAuthenticationResultFromCache(String sessionDataKey) {
AuthenticationResultCacheKey authResultCacheKey = new AuthenticationResultCacheKey(sessionDataKey);
CacheEntry cacheEntry = AuthenticationResultCache.getInstance(0).getValueFromCache(authResultCacheKey);
AuthenticationResult authResult = null;
if (cacheEntry != null) {
AuthenticationResultCacheEntry authResultCacheEntry = (AuthenticationResultCacheEntry) cacheEntry;
authResult = authResultCacheEntry.getResult();
} else {
log.error("Cannot find AuthenticationResult from the cache");
}
return authResult;
}
/**
* @param sessionDataKey
*/
private void removeAuthenticationResultFromCache(String sessionDataKey) {
if (sessionDataKey != null) {
AuthenticationResultCacheKey cacheKey = new AuthenticationResultCacheKey(sessionDataKey);
AuthenticationResultCache.getInstance(0).clearCacheEntry(cacheKey);
}
}
private void startTenantFlow(String tenantDomain) throws IdentityException {
int tenantId = MultitenantConstants.SUPER_TENANT_ID;
if (tenantDomain != null && !tenantDomain.trim().isEmpty() && !"null".equalsIgnoreCase(tenantDomain.trim())) {
try {
tenantId = SAMLSSOUtil.getRealmService().getTenantManager().getTenantId(tenantDomain);
if (tenantId == -1) {
// invalid tenantId, hence throw exception to avoid setting invalid tenant info
// to CC
String message = "Invalid Tenant Domain : " + tenantDomain;
if (log.isDebugEnabled()) {
log.debug(message);
}
throw new IdentityException(message);
}
} catch (UserStoreException e) {
String message = "Error occurred while getting tenant ID from tenantDomain " + tenantDomain;
log.error(message, e);
throw new IdentityException(message, e);
}
} else {
tenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
}
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext
.getThreadLocalCarbonContext();
carbonContext.setTenantId(tenantId);
carbonContext.setTenantDomain(tenantDomain);
}
}
| omindu/carbon-identity | components/sso-saml/org.wso2.carbon.identity.sso.saml/src/main/java/org/wso2/carbon/identity/sso/saml/servlet/SAMLSSOProviderServlet.java | Java | apache-2.0 | 44,950 |
package com.xianyi.localalbum.common;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory.Options;
import android.graphics.Paint;
import android.os.Build;
import android.provider.MediaStore;
import android.view.View;
import android.view.Window;
import java.io.File;
/**
* Android各版本的兼容方法
* @author liux (http://my.oschina.net/liux)
* @version 1.0
* @created 2012-8-6
*/
public class MethodsCompat {
@TargetApi(5)
public static void overridePendingTransition(Activity activity, int enter_anim, int exit_anim) {
activity.overridePendingTransition(enter_anim, exit_anim);
}
@TargetApi(7)
public static Bitmap getThumbnail(ContentResolver cr, long origId, int kind, Options options) {
return MediaStore.Images.Thumbnails.getThumbnail(cr,origId,kind, options);
}
@TargetApi(8)
public static File getExternalCacheDir(Context context) {
// // return context.getExternalCacheDir(); API level 8
//
// // e.g. "<sdcard>/Android/data/<package_name>/cache/"
// final File extCacheDir = new File(Environment.getExternalStorageDirectory(),
// "/Android/data/" + context.getApplicationInfo().packageName + "/cache/");
// extCacheDir.mkdirs();
// return extCacheDir;
return context.getExternalCacheDir();
}
@TargetApi(11)
public static void recreate(Activity activity) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
activity.recreate();
}
}
@TargetApi(11)
public static void setLayerType(View view, int layerType, Paint paint) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
view.setLayerType(layerType, paint);
}
}
@TargetApi(14)
public static void setUiOptions(Window window, int uiOptions) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
window.setUiOptions(uiOptions);
}
}
} | orq518/xianyi | app/src/main/java/com/xianyi/localalbum/common/MethodsCompat.java | Java | apache-2.0 | 2,130 |
/*
* The Alluxio Open Foundation licenses this work under the Apache License, version 2.0
* (the "License"). You may not use this work except in compliance with the License, which is
* available at www.apache.org/licenses/LICENSE-2.0
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied, as more fully set forth in the License.
*
* See the NOTICE file distributed with this work for information regarding copyright ownership.
*/
package alluxio.cli;
import alluxio.Configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.concurrent.ThreadSafe;
/**
* Validate the Alluxio configuration.
*/
@ThreadSafe
public final class ValidateConf {
private static final Logger LOG = LoggerFactory.getLogger(ValidateConf.class);
/**
* Console program that validates the configuration.
*
* @param args there are no arguments needed
*/
public static void main(String[] args) {
int ret = 0;
LOG.info("Validating configuration.");
if (Configuration.validate()) {
LOG.info("All configuration entries are valid.");
} else {
LOG.info("Configuration has invalid entries.");
ret = -1;
}
System.exit(ret);
}
private ValidateConf() {} // prevent instantiation.
}
| yuluo-ding/alluxio | shell/src/main/java/alluxio/cli/ValidateConf.java | Java | apache-2.0 | 1,334 |
/*
* Copyright 2018 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kie.workbench.common.stunner.core.client.session.command.impl;
import java.lang.annotation.Annotation;
import org.jboss.errai.ioc.client.api.ManagedInstance;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.kie.workbench.common.stunner.core.client.canvas.AbstractCanvasHandler;
import org.kie.workbench.common.stunner.core.client.command.CanvasCommand;
import org.kie.workbench.common.stunner.core.client.command.CanvasCommandFactory;
import org.kie.workbench.common.stunner.core.client.command.SessionCommandManager;
import org.kie.workbench.common.stunner.core.client.session.command.ClientSessionCommand;
import org.kie.workbench.common.stunner.core.client.session.impl.EditorSession;
import org.kie.workbench.common.stunner.core.client.session.impl.ViewerSession;
import org.kie.workbench.common.stunner.core.command.CommandResult;
import org.kie.workbench.common.stunner.core.diagram.Diagram;
import org.kie.workbench.common.stunner.core.diagram.Metadata;
import org.kie.workbench.common.stunner.core.registry.command.CommandRegistry;
import org.kie.workbench.common.stunner.core.util.DefinitionUtils;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.uberfire.mocks.EventSourceMock;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class ClearSessionCommandTest {
@Mock
private SessionCommandManager<AbstractCanvasHandler> sessionCommandManager;
@Mock
private CanvasCommandFactory<AbstractCanvasHandler> canvasCommandFactory;
@Mock
private EventSourceMock<ClearSessionCommandExecutedEvent> commandExecutedEvent;
@Mock
private EditorSession session;
@Mock
private AbstractCanvasHandler canvasHandler;
@Mock
private ClientSessionCommand.Callback callback;
@Mock
private ClearSessionCommand command;
@Mock
private CommandRegistry commandRegistry;
@Mock
private CanvasCommand clearCanvasCommand;
@Mock
private CommandResult commandResult;
@Mock
private DefinitionUtils definitionUtils;
@Mock
private Diagram diagram;
@Mock
private Metadata metadata;
private final String DEFINITION_SET_ID = "mockDefinitionSetId";
@Mock
private Annotation qualifier;
@Mock
private ManagedInstance<CanvasCommandFactory<AbstractCanvasHandler>> canvasCommandFactoryInstance;
private ArgumentCaptor<ClearSessionCommandExecutedEvent> commandExecutedEventCaptor;
@Before
@SuppressWarnings("unchecked")
public void setUp() {
when(session.getCommandManager()).thenReturn(sessionCommandManager);
when(session.getCanvasHandler()).thenReturn(canvasHandler);
when(sessionCommandManager.getRegistry()).thenReturn(commandRegistry);
when(canvasCommandFactory.clearCanvas()).thenReturn(clearCanvasCommand);
when(canvasHandler.getDiagram()).thenReturn(diagram);
when(diagram.getMetadata()).thenReturn(metadata);
when(metadata.getDefinitionSetId()).thenReturn(DEFINITION_SET_ID);
when(definitionUtils.getQualifier(eq(DEFINITION_SET_ID))).thenReturn(qualifier);
when(canvasCommandFactoryInstance.select(eq(qualifier))).thenReturn(canvasCommandFactoryInstance);
when(canvasCommandFactoryInstance.isUnsatisfied()).thenReturn(false);
when(canvasCommandFactoryInstance.get()).thenReturn(canvasCommandFactory);
commandExecutedEventCaptor = ArgumentCaptor.forClass(ClearSessionCommandExecutedEvent.class);
command = new ClearSessionCommand(canvasCommandFactoryInstance,
sessionCommandManager,
commandExecutedEvent,
definitionUtils);
command.bind(session);
}
@Test
@SuppressWarnings("unchecked")
public void testExecuteSuccess() {
when(sessionCommandManager.execute(canvasHandler,
clearCanvasCommand)).thenReturn(null);
command.execute(callback);
verify(sessionCommandManager,
times(1)).execute(canvasHandler,
clearCanvasCommand);
verify(commandRegistry,
times(1)).clear();
verify(callback,
times(1)).onSuccess();
verify(commandExecutedEvent,
times(1)).fire(commandExecutedEventCaptor.capture());
assertEquals(session,
commandExecutedEventCaptor.getValue().getClientSession());
assertEquals(command,
commandExecutedEventCaptor.getValue().getExecutedCommand());
}
@Test
@SuppressWarnings("unchecked")
public void testExecuteWithErrors() {
when(sessionCommandManager.execute(canvasHandler,
clearCanvasCommand)).thenReturn(commandResult);
when(commandResult.getType()).thenReturn(CommandResult.Type.ERROR);
command.execute(callback);
verify(sessionCommandManager,
times(1)).execute(canvasHandler,
clearCanvasCommand);
verify(commandRegistry,
never()).clear();
verify(callback,
times(1)).onError(commandResult);
verify(commandExecutedEvent,
never()).fire(commandExecutedEventCaptor.capture());
}
@Test
public void testAcceptsSession() {
assertTrue(command.accepts(mock(EditorSession.class)));
assertFalse(command.accepts(mock(ViewerSession.class)));
}
}
| jhrcek/kie-wb-common | kie-wb-common-stunner/kie-wb-common-stunner-core/kie-wb-common-stunner-commons/kie-wb-common-stunner-client-common/src/test/java/org/kie/workbench/common/stunner/core/client/session/command/impl/ClearSessionCommandTest.java | Java | apache-2.0 | 6,627 |
// Copyright 2011-2016 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.security.zynamics.reil.translators.mips;
import com.google.security.zynamics.reil.OperandSize;
import com.google.security.zynamics.reil.ReilHelpers;
import com.google.security.zynamics.reil.ReilInstruction;
import com.google.security.zynamics.reil.translators.IInstructionTranslator;
import com.google.security.zynamics.reil.translators.ITranslationEnvironment;
import com.google.security.zynamics.reil.translators.InternalTranslationException;
import com.google.security.zynamics.reil.translators.TranslationHelpers;
import com.google.security.zynamics.zylib.disassembly.IInstruction;
import com.google.security.zynamics.zylib.disassembly.IOperandTree;
import com.google.security.zynamics.zylib.disassembly.IOperandTreeNode;
import java.util.List;
public class BgezlTranslator implements IInstructionTranslator {
@Override
public void translate(final ITranslationEnvironment environment, final IInstruction instruction,
final List<ReilInstruction> instructions) throws InternalTranslationException {
TranslationHelpers.checkTranslationArguments(environment, instruction, instructions, "bgezl");
final List<? extends IOperandTree> operands = instruction.getOperands();
final String rs = operands.get(0).getRootNode().getChildren().get(0).getValue();
final IOperandTreeNode target = operands.get(1).getRootNode().getChildren().get(0);
final OperandSize dw = OperandSize.DWORD;
final long baseOffset = ReilHelpers.toReilAddress(instruction.getAddress()).toLong();
long offset = baseOffset;
final String signBit = environment.getNextVariableString();
final String invertedSignBit = environment.getNextVariableString();
instructions
.add(ReilHelpers.createBsh(offset++, dw, rs, dw, String.valueOf(-31L), dw, signBit));
instructions.add(ReilHelpers.createBisz(offset++, dw, signBit, dw, invertedSignBit));
Helpers.generateDelayBranchLikely(instructions, offset, dw, invertedSignBit, dw, target);
}
}
| mayl8822/binnavi | src/main/java/com/google/security/zynamics/reil/translators/mips/BgezlTranslator.java | Java | apache-2.0 | 2,583 |
/**
* Copyright (C) 2014 Esup Portail http://www.esup-portail.org
* @Author (C) 2012 Julien Gribonvald <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.esupportail.publisher.web.rest;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Optional;
import javax.inject.Inject;
import org.esupportail.publisher.domain.ContextKey;
import org.esupportail.publisher.domain.Organization;
import org.esupportail.publisher.domain.enums.ContextType;
import org.esupportail.publisher.domain.enums.PermissionType;
import org.esupportail.publisher.repository.OrganizationRepository;
import org.esupportail.publisher.security.IPermissionService;
import org.esupportail.publisher.security.SecurityConstants;
import org.esupportail.publisher.service.OrganizationService;
import org.esupportail.publisher.service.bean.UserContextTree;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PostFilter;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.codahale.metrics.annotation.Timed;
/**
* REST controller for managing Organization.
*/
@RestController
@RequestMapping("/api")
public class OrganizationResource {
private final Logger log = LoggerFactory.getLogger(OrganizationResource.class);
@Inject
private OrganizationRepository organizationRepository;
@Inject
private OrganizationService organizationService;
@Inject
private IPermissionService permissionService;
@Inject
public UserContextTree userSessionTree;
/**
* POST /organizations -> Create a new organization.
*/
@RequestMapping(value = "/organizations", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
@PreAuthorize(SecurityConstants.IS_ROLE_ADMIN)
public ResponseEntity<Void> create(@RequestBody Organization organization) throws URISyntaxException {
log.debug("REST request to save Organization : {}", organization);
if (organization.getId() != null) {
return ResponseEntity.badRequest().header("Failure", "A new organization cannot already have an ID").build();
}
organization.setDisplayOrder(organizationRepository.getNextDisplayOrder());
organizationRepository.save(organization);
//userSessionTree.addCtx(organization.getContextKey(), null, null, PermissionType.ADMIN);
return ResponseEntity.created(new URI("/api/organizations/" + organization.getId())).build();
}
/**
* PUT /organizations -> Updates an existing organization.
*/
@RequestMapping(value = "/organizations", method = RequestMethod.PUT, produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
@PreAuthorize(SecurityConstants.IS_ROLE_ADMIN + " || " + SecurityConstants.IS_ROLE_USER
+ " && hasPermission(#organization, '" + SecurityConstants.PERM_MANAGER + "')")
public ResponseEntity<Void> update(@RequestBody Organization organization) throws URISyntaxException {
log.debug("REST request to update Organization : {}", organization);
PermissionType permType = permissionService.getRoleOfUserInContext(SecurityContextHolder.getContext().getAuthentication(), organization.getContextKey());
if (permType == null) {
log.warn("@PreAuthorize didn't work correctly, check Security !");
return new ResponseEntity<>(HttpStatus.FORBIDDEN);
}
if (organization.getId() == null && PermissionType.ADMIN.getMask() <= permType.getMask()) {
return create(organization);
} else if (organization.getId() == null) {
return new ResponseEntity<>(HttpStatus.FORBIDDEN);
}
// a manager role can only update DisplayName and if Notifications are allowed
if (PermissionType.MANAGER.getMask() <= permType.getMask()) {
Optional<Organization> optionalOrganization = organizationRepository.findById(organization.getId());
Organization model = optionalOrganization == null || !optionalOrganization.isPresent()? null : optionalOrganization.get();
model.setDisplayName(organization.getDisplayName());
model.setAllowNotifications(organization.isAllowNotifications());
organizationRepository.save(organization);
return ResponseEntity.ok().build();
}
organizationService.doMove(organization.getId(), organization.getDisplayOrder());
organizationRepository.save(organization);
return ResponseEntity.ok().build();
}
// @RequestMapping(value = "/organizations/{id}", method =
// RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
// @Timed
// public void moveOrder(@PathVariable Long id, @RequestBody MoveDTO pos) {
// organizationService.doMove(id, pos.getPosition());
// }
@RequestMapping(value = "/organizations/{id}", method = RequestMethod.PUT, produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
@PreAuthorize(SecurityConstants.IS_ROLE_ADMIN)
public void moveOrder(@PathVariable Long id, @RequestParam int pos) {
organizationService.doMove(id, pos);
}
/**
* GET /organizations -> get all the organizations.
*/
@PreAuthorize(SecurityConstants.IS_ROLE_USER)
@PostFilter("hasPermission(filterObject, '" + SecurityConstants.PERM_LOOKOVER + "')")
@RequestMapping(value = "/organizations", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public List<Organization> getAll() {
log.debug("REST request to get all Organizations");
return organizationRepository.findAll(sortByDisplayOrderAsc());
}
/**
* GET /organizations -> get all the organizations.
*/
// @RequestMapping(value = "/organizations",
// method = RequestMethod.GET,
// produces = MediaType.APPLICATION_JSON_VALUE)
// @Timed
// public ResponseEntity<List<Organization>> getAll(@RequestParam(value = "page" , required = false) Integer offset,
// @RequestParam(value = "per_page", required = false) Integer limit)
// throws URISyntaxException {
// Page<Organization> page = organizationRepository.findAll(PaginationUtil.generatePageRequest(offset, limit));
// HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/organizations", offset, limit);
// return new ResponseEntity<List<Organization>>(page.getContent(), headers, HttpStatus.OK);
// }
/**
* GET /organizations/:id -> get the "id" organization.
*/
@PreAuthorize("hasPermission(#id, 'ORGANIZATION', '" + SecurityConstants.PERM_LOOKOVER + "')")
@RequestMapping(value = "/organizations/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public ResponseEntity<Organization> get(@PathVariable Long id) {
log.debug("REST request to get Organization : {}", id);
Optional<Organization> optionalOrganization = organizationRepository.findById(id);
Organization organization = optionalOrganization == null || !optionalOrganization.isPresent()? null : optionalOrganization.get();
if (organization == null) {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
return new ResponseEntity<>(organization, HttpStatus.OK);
}
/**
* DELETE /organizations/:id -> delete the "id" organization.
*/
@PreAuthorize(SecurityConstants.IS_ROLE_ADMIN)
@RequestMapping(value = "/organizations/{id}", method = RequestMethod.DELETE, produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public void delete(@PathVariable Long id) {
log.debug("REST request to delete Organization : {}", id);
organizationRepository.deleteById(id);
userSessionTree.removeCtx(new ContextKey(id, ContextType.ORGANIZATION));
}
/**
* Returns a Sort object which sorts Organization in ascending order by
* using the displayOrder.
*
* @return
*/
private Sort sortByDisplayOrderAsc() {
return Sort.by(Sort.Direction.ASC, "displayOrder");
}
}
| GIP-RECIA/esup-publisher-ui | src/main/java/org/esupportail/publisher/web/rest/OrganizationResource.java | Java | apache-2.0 | 8,984 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.jena.sparql.algebra.optimize;
import java.util.Collection;
import org.apache.jena.sparql.algebra.op.OpProject;
import org.apache.jena.sparql.core.Var;
/**
* An after visitor for tracking variable usage
*
*/
public class VariableUsagePopper extends VariableUsageVisitor {
public VariableUsagePopper(VariableUsageTracker tracker) {
super(tracker);
}
@Override
protected void action(Collection<Var> vars) {
this.tracker.decrement(vars);
}
@Override
protected void action(Var var) {
this.tracker.decrement(var);
}
@Override
protected void action(String var) {
this.tracker.decrement(var);
}
@Override
public void visit(OpProject opProject) {
super.visit(opProject);
this.tracker.pop();
super.visit(opProject);
}
}
| apache/jena | jena-arq/src/main/java/org/apache/jena/sparql/algebra/optimize/VariableUsagePopper.java | Java | apache-2.0 | 1,659 |
/*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
/*
* This code was generated by https://github.com/googleapis/google-api-java-client-services/
* Modify at your own risk.
*/
package com.google.api.services.classroom.model;
/**
* Alternative identifier for a course. An alias uniquely identifies a course. It must be unique
* within one of the following scopes: * domain: A domain-scoped alias is visible to all users
* within the alias creator's domain and can be created only by a domain admin. A domain-scoped
* alias is often used when a course has an identifier external to Classroom. * project: A project-
* scoped alias is visible to any request from an application using the Developer Console project ID
* that created the alias and can be created by any project. A project-scoped alias is often used
* when an application has alternative identifiers. A random value can also be used to avoid
* duplicate courses in the event of transmission failures, as retrying a request will return
* `ALREADY_EXISTS` if a previous one has succeeded.
*
* <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is
* transmitted over HTTP when working with the Google Classroom API. For a detailed explanation see:
* <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a>
* </p>
*
* @author Google, Inc.
*/
@SuppressWarnings("javadoc")
public final class CourseAlias extends com.google.api.client.json.GenericJson {
/**
* Alias string. The format of the string indicates the desired alias scoping. * `d:` indicates a
* domain-scoped alias. Example: `d:math_101` * `p:` indicates a project-scoped alias. Example:
* `p:abc123` This field has a maximum length of 256 characters.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String alias;
/**
* Alias string. The format of the string indicates the desired alias scoping. * `d:` indicates a
* domain-scoped alias. Example: `d:math_101` * `p:` indicates a project-scoped alias. Example:
* `p:abc123` This field has a maximum length of 256 characters.
* @return value or {@code null} for none
*/
public java.lang.String getAlias() {
return alias;
}
/**
* Alias string. The format of the string indicates the desired alias scoping. * `d:` indicates a
* domain-scoped alias. Example: `d:math_101` * `p:` indicates a project-scoped alias. Example:
* `p:abc123` This field has a maximum length of 256 characters.
* @param alias alias or {@code null} for none
*/
public CourseAlias setAlias(java.lang.String alias) {
this.alias = alias;
return this;
}
@Override
public CourseAlias set(String fieldName, Object value) {
return (CourseAlias) super.set(fieldName, value);
}
@Override
public CourseAlias clone() {
return (CourseAlias) super.clone();
}
}
| googleapis/google-api-java-client-services | clients/google-api-services-classroom/v1/1.31.0/com/google/api/services/classroom/model/CourseAlias.java | Java | apache-2.0 | 3,512 |
/*
* Copyright (c) 2005-2013, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.event.builder.core.internal.type.text;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.databridge.commons.Attribute;
import org.wso2.carbon.databridge.commons.AttributeType;
import org.wso2.carbon.databridge.commons.StreamDefinition;
import org.wso2.carbon.event.builder.core.config.EventBuilderConfiguration;
import org.wso2.carbon.event.builder.core.config.InputMapper;
import org.wso2.carbon.event.builder.core.exception.EventBuilderConfigurationException;
import org.wso2.carbon.event.builder.core.exception.EventBuilderProcessingException;
import org.wso2.carbon.event.builder.core.internal.config.InputMappingAttribute;
import org.wso2.carbon.event.builder.core.internal.type.text.config.RegexData;
import org.wso2.carbon.event.builder.core.internal.util.EventBuilderConstants;
import org.wso2.carbon.event.builder.core.internal.util.EventBuilderUtil;
import org.wso2.carbon.event.builder.core.internal.util.helper.EventBuilderConfigHelper;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.PatternSyntaxException;
public class TextInputMapper implements InputMapper {
private List<RegexData> attributeRegexList = new ArrayList<RegexData>();
private EventBuilderConfiguration eventBuilderConfiguration = null;
private int[] attributePositions;
private static final Log log = LogFactory.getLog(TextInputMapper.class);
private int noMetaData;
private int noCorrelationData;
private int noPayloadData;
private StreamDefinition streamDefinition;
public TextInputMapper(EventBuilderConfiguration eventBuilderConfiguration,
StreamDefinition streamDefinition)
throws EventBuilderConfigurationException {
this.eventBuilderConfiguration = eventBuilderConfiguration;
this.streamDefinition = streamDefinition;
if (eventBuilderConfiguration != null && eventBuilderConfiguration.getInputMapping() instanceof TextInputMapping) {
if (eventBuilderConfiguration.getInputMapping().isCustomMappingEnabled()) {
TextInputMapping textInputMapping = (TextInputMapping) eventBuilderConfiguration.getInputMapping();
RegexData regexData = null;
if (textInputMapping.getInputMappingAttributes() != null || textInputMapping.getInputMappingAttributes().size() == 0) {
attributePositions = new int[textInputMapping.getInputMappingAttributes().size()];
} else {
throw new EventBuilderConfigurationException("Text input mapping attribute list cannot be null!");
}
List<Integer> attribPositionList = new LinkedList<Integer>();
int metaCount = 0;
int correlationCount = 0;
int attributeCount = 0;
for (InputMappingAttribute inputMappingAttribute : textInputMapping.getInputMappingAttributes()) {
String regex = inputMappingAttribute.getFromElementKey();
if (regexData == null || !regex.equals(regexData.getRegex())) {
try {
regexData = new RegexData(regex);
attributeRegexList.add(regexData);
} catch (PatternSyntaxException e) {
throw new EventBuilderConfigurationException("Error parsing regular expression: " + regex, e);
}
}
if (EventBuilderUtil.isMetaAttribute(inputMappingAttribute.getToElementKey())) {
attribPositionList.add(metaCount++, attributeCount++);
} else if (EventBuilderUtil.isCorrelationAttribute(inputMappingAttribute.getToElementKey())) {
attribPositionList.add(metaCount + correlationCount++, attributeCount++);
} else {
attribPositionList.add(attributeCount++);
}
String type = EventBuilderConstants.ATTRIBUTE_TYPE_CLASS_TYPE_MAP.get(inputMappingAttribute.getToElementType());
String defaultValue = inputMappingAttribute.getDefaultValue();
regexData.addMapping(type, defaultValue);
}
for (int i = 0; i < attribPositionList.size(); i++) {
attributePositions[attribPositionList.get(i)] = i;
}
} else {
this.noMetaData = streamDefinition.getMetaData() != null ? streamDefinition.getMetaData().size() : 0;
this.noCorrelationData += streamDefinition.getCorrelationData() != null ? streamDefinition.getCorrelationData().size() : 0;
this.noPayloadData += streamDefinition.getPayloadData() != null ? streamDefinition.getPayloadData().size() : 0;
}
}
}
@Override
public Object convertToMappedInputEvent(Object obj) throws EventBuilderProcessingException {
Object attributeArray[] = new Object[attributePositions.length];
if (obj instanceof String) {
String inputString = (String) obj;
int attributeCount = 0;
for (RegexData regexData : attributeRegexList) {
String formattedInputString = inputString.replaceAll("\\r", "");
regexData.matchInput(formattedInputString);
while (regexData.hasNext()) {
Object returnedAttribute = null;
String value = regexData.next();
if (value != null) {
String type = regexData.getType();
try {
Class<?> beanClass = Class.forName(type);
if (!beanClass.equals(String.class)) {
Class<?> stringClass = String.class;
Method valueOfMethod = beanClass.getMethod("valueOf", stringClass);
returnedAttribute = valueOfMethod.invoke(null, value);
} else {
returnedAttribute = value;
}
} catch (ClassNotFoundException e) {
throw new EventBuilderProcessingException("Cannot convert " + value + " to type " + type, e);
} catch (InvocationTargetException e) {
log.warn("Cannot convert " + value + " to type " + type + ": " + e.getMessage() + "; Sending null value.");
returnedAttribute = null;
} catch (NoSuchMethodException e) {
throw new EventBuilderProcessingException("Cannot convert " + value + " to type " + type, e);
} catch (IllegalAccessException e) {
throw new EventBuilderProcessingException("Cannot convert " + value + " to type " + type, e);
}
}
attributeArray[attributePositions[attributeCount++]] = returnedAttribute;
}
}
}
return attributeArray;
}
//TODO use = for default text mapping use a map instead of multiple for loops
@Override
public Object convertToTypedInputEvent(Object obj) throws EventBuilderProcessingException {
Object attributeArray[] = new Object[noMetaData + noCorrelationData + noPayloadData];
if (obj instanceof String) {
String inputString = ((String) obj).trim();
int attributeCount = 0;
String[] eventAttributes = inputString.trim().split(",");
for (String eventAttribute : eventAttributes) {
boolean setFlag = false;
if(noMetaData>0) {
for (Attribute metaData : streamDefinition.getMetaData()) {
if (eventAttribute.trim().startsWith(EventBuilderConstants.META_DATA_PREFIX + metaData.getName())) {
attributeArray[attributeCount++] = getPropertyValue(eventAttribute.split(EventBuilderConstants.EVENT_ATTRIBUTE_SEPARATOR)[1], metaData.getType());
setFlag = true;
break;
}
}
}
if(noCorrelationData>0) {
if (!setFlag) {
for (Attribute correlationData : streamDefinition.getCorrelationData()) {
if (eventAttribute.trim().startsWith(EventBuilderConstants.CORRELATION_DATA_PREFIX + correlationData.getName())) {
attributeArray[attributeCount++] = getPropertyValue(eventAttribute.split(EventBuilderConstants.EVENT_ATTRIBUTE_SEPARATOR)[1], correlationData.getType());
setFlag = true;
break;
}
}
}
}
if(noPayloadData>0) {
if (!setFlag) {
for (Attribute payloadData : streamDefinition.getPayloadData()) {
if (eventAttribute.trim().startsWith(payloadData.getName())) {
attributeArray[attributeCount++] = getPropertyValue(eventAttribute.split(EventBuilderConstants.EVENT_ATTRIBUTE_SEPARATOR)[1], payloadData.getType());
break;
}
}
}
}
}
if (noMetaData + noCorrelationData + noPayloadData != attributeCount) {
throw new EventBuilderProcessingException("Event attributes are not matching with the stream : " + this.eventBuilderConfiguration.getToStreamName() + ":" + eventBuilderConfiguration.getToStreamVersion());
}
}
return attributeArray;
}
@Override
public Attribute[] getOutputAttributes() {
TextInputMapping textInputMapping = (TextInputMapping) eventBuilderConfiguration.getInputMapping();
List<InputMappingAttribute> inputMappingAttributes = textInputMapping.getInputMappingAttributes();
return EventBuilderConfigHelper.getAttributes(inputMappingAttributes);
}
private Object getPropertyValue(Object propertyValue, AttributeType attributeType) {
if (AttributeType.BOOL.equals(attributeType)) {
return Boolean.parseBoolean(propertyValue.toString());
} else if (AttributeType.DOUBLE.equals(attributeType)) {
return Double.parseDouble(propertyValue.toString());
} else if (AttributeType.FLOAT.equals(attributeType)) {
return Float.parseFloat(propertyValue.toString());
} else if (AttributeType.INT.equals(attributeType)) {
return Integer.parseInt(propertyValue.toString());
} else if (AttributeType.LONG.equals(attributeType)) {
return Long.parseLong(propertyValue.toString());
} else {
return propertyValue.toString();
}
}
}
| lankavitharana/carbon-event-processing | components/event-stream/event-builder/org.wso2.carbon.event.builder.core/src/main/java/org/wso2/carbon/event/builder/core/internal/type/text/TextInputMapper.java | Java | apache-2.0 | 12,040 |
// ========================================================================
// $Id: URI.java,v 1.39 2006/01/04 13:55:31 gregwilkins Exp $
// Copyright 199-2004 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ========================================================================
package org.browsermob.proxy.jetty.util;
import org.apache.commons.logging.Log;
import org.browsermob.proxy.jetty.log.LogFactory;
import java.io.UnsupportedEncodingException;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
/* ------------------------------------------------------------ */
/** URI Holder.
* This class assists with the decoding and encoding or HTTP URI's.
* It differs from the java.net.URL class as it does not provide
* communications ability, but it does assist with query string
* formatting.
* <P>ISO_8859_1 encoding is used by default for % encoded characters. This
* may be overridden with the org.mortbay.util.URI.charset system property.
* @see UrlEncoded
* @version $Id: URI.java,v 1.39 2006/01/04 13:55:31 gregwilkins Exp $
* @author Greg Wilkins (gregw)
*/
public class URI
implements Cloneable
{
private static Log log = LogFactory.getLog(URI.class);
public static final String __CHARSET=System.getProperty("org.browsermob.proxy.jetty.util.URI.charset",StringUtil.__UTF_8);
public static final boolean __CHARSET_IS_DEFAULT=__CHARSET.equals(StringUtil.__UTF_8);
/* ------------------------------------------------------------ */
private String _uri;
private String _scheme;
private String _host;
private int _port;
private String _path;
private String _encodedPath;
private String _query;
private UrlEncoded _parameters;
private boolean _dirty;
/* ------------------------------------------------------------ */
/** Copy Constructor .
* @param uri
*/
public URI(URI uri)
throws IllegalArgumentException
{
_uri=uri.toString();
_scheme=uri._scheme;
_host=uri._host;
_port=uri._port;
_path=uri._path;
_encodedPath=uri._encodedPath;
_query=uri._query;
if (uri._parameters!=null)
_parameters=(UrlEncoded)uri._parameters.clone();
_dirty=false;
}
/* ------------------------------------------------------------ */
/** Construct from a String.
* The string must contain a URI path, but optionaly may contain a
* scheme, host, port and query string.
*
* @param uri [scheme://host[:port]]/path[?query]
*/
public URI(String uri)
throws IllegalArgumentException
{
setURI(uri);
}
/* ------------------------------------------------------------ */
public void setURI(String uri)
throws IllegalArgumentException
{
try
{
_uri=uri;
_scheme=null;
_host=null;
_port=0;
_path=null;
_encodedPath=null;
_query=null;
if (_parameters!=null)
_parameters.clear();
// Scan _uri for host, port, path & query
int maxi=uri.length()-1;
int mark=0;
int state=0;
int i=0;
if (maxi==0 || uri.charAt(0)=='/' && uri.charAt(1)!='/')
{
state=3;
_scheme=null;
_host=null;
_port=0;
}
else
{
for (i=0;state<3 && i<=maxi;i++)
{
char c=uri.charAt(i);
switch(state)
{
case 0: // looking for scheme or path
if (c==':' &&
uri.charAt(i+1)=='/' &&
uri.charAt(i+2)=='/')
{
// found end of scheme & start of host
_scheme=uri.substring(mark,i);
i+=2;
mark=i+1;
state=1;
}
else if (i==0 && c=='/')
{
// Found path
state=3;
}
else if (i==0 && c=='*')
{
state=5;
_path="*";
_encodedPath="*";
}
continue;
case 1: // Get host & look for port or path
if (c==':')
{
// found port
_host=uri.substring(mark,i);
mark=i+1;
state=2;
}
else if (c=='/')
{
// found path
_host=uri.substring(mark,i);
mark=i;
state=3;
}
continue;
case 2: // Get port & look for path
if (c=='/')
{
_port=TypeUtil.parseInt(uri,mark,i-mark,10);
mark=i;
state=3;
}
continue;
}
}
}
// State 3 - Get path & look for query
_query=null;
for (i++;i<=maxi;i++)
{
char c=uri.charAt(i);
if (c=='?')
{
// Found query
_encodedPath=uri.substring(mark,i);
_path=decodePath(_encodedPath);
mark=i+1;
state=4;
break;
}
}
// complete last state
switch(state)
{
case 0:
_dirty=false;
_encodedPath=_uri;
_path=decodePath(_encodedPath);
break;
case 1:
_dirty=true;
_encodedPath="/";
_path=_encodedPath;
_host=uri.substring(mark);
break;
case 2:
_dirty=true;
_encodedPath="/";
_path=_encodedPath;
_port=TypeUtil.parseInt(uri,mark,-1,10);
break;
case 3:
_dirty=(mark==maxi);
_encodedPath=uri.substring(mark);
_path=decodePath(_encodedPath);
break;
case 4:
_dirty=false;
if (mark<=maxi)
_query=uri.substring(mark);
break;
case 5:
_dirty=false;
}
if (_query!=null && _query.length()>0)
{
if (_parameters==null)
_parameters= new UrlEncoded();
else
_parameters.clear();
_parameters.decode(_query,__CHARSET);
}
else
_query=null;
}
catch (Exception e)
{
LogSupport.ignore(log,e);
throw new IllegalArgumentException("Malformed URI '"+uri+
"' : "+e.toString());
}
}
/* ------------------------------------------------------------ */
/** Is the URI an absolute URL?
* @return True if the URI has a scheme or host
*/
public boolean isAbsolute()
{
return _scheme!=null || _host!=null;
}
/* ------------------------------------------------------------ */
/** Get the uri scheme.
* @return the URI scheme
*/
public String getScheme()
{
return _scheme;
}
/* ------------------------------------------------------------ */
/** Set the uri scheme.
* @param scheme the uri scheme
*/
public void setScheme(String scheme)
{
_scheme=scheme;
_dirty=true;
}
/* ------------------------------------------------------------ */
/** Get the uri host.
* @return the URI host
*/
public String getHost()
{
return _host;
}
/* ------------------------------------------------------------ */
/** Set the uri host.
* @param host the uri host
*/
public void setHost(String host)
{
_host=host;
_dirty=true;
}
/* ------------------------------------------------------------ */
/** Get the uri port.
* @return the URI port
*/
public int getPort()
{
return _port;
}
/* ------------------------------------------------------------ */
/** Set the uri port.
* A port of 0 implies use the default port.
* @param port the uri port
*/
public void setPort(int port)
{
_port=port;
_dirty=true;
}
/* ------------------------------------------------------------ */
/** Get the uri path.
* @return the URI path
*/
public String getPath()
{
return _path;
}
/* ------------------------------------------------------------ */
/** Get the encoded uri path.
* @return the URI path
*/
public String getEncodedPath()
{
return _encodedPath;
}
/* ------------------------------------------------------------ */
/** Set the uri path.
* @param path the URI path
*/
public void setPath(String path)
{
_path=path;
_encodedPath=encodePath(_path);
_dirty=true;
}
/* ------------------------------------------------------------ */
/** Get the uri query String.
* @return the URI query string
*/
public String getQuery()
{
if (_dirty && _parameters!=null)
{
_query = _parameters.encode(__CHARSET);
if (_query!=null && _query.length()==0)
_query=null;
}
return _query;
}
/* ------------------------------------------------------------ */
/** Set the uri query String.
* @param query the URI query string
*/
public void setQuery(String query)
{
_query=query;
if (_parameters!=null)
_parameters.clear();
else if (query!=null)
_parameters=new UrlEncoded();
if (query!=null)
_parameters.decode(query,__CHARSET);
cleanURI();
}
/* ------------------------------------------------------------ */
/** Get the uri query _parameters names.
* @return Unmodifiable set of URI query _parameters names
*/
public Set getParameterNames()
{
if (_parameters==null)
return Collections.EMPTY_SET;
return _parameters.keySet();
}
/* ------------------------------------------------------------ */
/** Get the uri query _parameters.
* @return the URI query _parameters
*/
public MultiMap getParameters()
{
if (_parameters==null)
_parameters=new UrlEncoded();
_dirty=true;
return _parameters;
}
/* ------------------------------------------------------------ */
/** Get the uri query _parameters.
* @return the URI query _parameters in an unmodifiable map.
*/
public Map getUnmodifiableParameters()
{
if (_parameters==null)
return Collections.EMPTY_MAP;
return Collections.unmodifiableMap(_parameters);
}
/* ------------------------------------------------------------ */
/** Add the uri query _parameters to a MultiMap
*/
public void putParametersTo(MultiMap map)
{
if (_parameters!=null && _parameters.size()>0)
map.putAll(_parameters);
}
/* ------------------------------------------------------------ */
/** Clear the URI _parameters.
*/
public void clearParameters()
{
if (_parameters!=null)
{
_dirty=true;
_parameters.clear();
}
}
/* ------------------------------------------------------------ */
/** Add encoded _parameters.
* @param encoded A HTTP encoded string of _parameters: e.g.. "a=1&b=2"
*/
public void put(String encoded)
{
UrlEncoded params = new UrlEncoded(encoded);
put(params);
}
/* ------------------------------------------------------------ */
/** Add name value pair to the uri query _parameters.
* @param name name of value
* @param value The value, which may be a multi valued list or
* String array.
*/
public Object put(Object name, Object value)
{
return getParameters().put(name,value);
}
/* ------------------------------------------------------------ */
/** Add dictionary to the uri query _parameters.
*/
public void put(Map values)
{
getParameters().putAll(values);
}
/* ------------------------------------------------------------ */
/** Get named value
*/
public String get(String name)
{
if (_parameters==null)
return null;
return (String)_parameters.get(name);
}
/* ------------------------------------------------------------ */
/** Get named multiple values.
* @param name The parameter name
* @return Umodifiable list of values or null
*/
public List getValues(String name)
{
if (_parameters==null)
return null;
return _parameters.getValues(name);
}
/* ------------------------------------------------------------ */
/** Remove named value
*/
public void remove(String name)
{
if (_parameters!=null)
{
_dirty=
_parameters.remove(name)!=null;
}
}
/* ------------------------------------------------------------ */
/** @return the URI string encoded.
*/
public String toString()
{
if (_dirty)
{
getQuery();
cleanURI();
}
return _uri;
}
/* ------------------------------------------------------------ */
private void cleanURI()
{
StringBuffer buf = new StringBuffer(_uri.length()*2);
synchronized(buf)
{
if (_scheme!=null)
{
buf.append(_scheme);
buf.append("://");
buf.append(_host);
if (_port>0)
{
buf.append(':');
buf.append(_port);
}
}
buf.append(_encodedPath);
if (_query!=null && _query.length()>0)
{
buf.append('?');
buf.append(_query);
}
_uri=buf.toString();
_dirty=false;
}
}
/* ------------------------------------------------------------ */
/** Encode a URI path.
* This is the same encoding offered by URLEncoder, except that
* the '/' character is not encoded.
* @param path The path the encode
* @return The encoded path
*/
public static String encodePath(String path)
{
if (path==null || path.length()==0)
return path;
StringBuffer buf = encodePath(null,path);
return buf==null?path:buf.toString();
}
/* ------------------------------------------------------------ */
/** Encode a URI path.
* @param path The path the encode
* @param buf StringBuffer to encode path into (or null)
* @return The StringBuffer or null if no substitutions required.
*/
public static StringBuffer encodePath(StringBuffer buf, String path)
{
if (buf==null)
{
loop:
for (int i=0;i<path.length();i++)
{
char c=path.charAt(i);
switch(c)
{
case '%':
case '?':
case ';':
case '#':
case ' ':
buf=new StringBuffer(path.length()<<1);
break loop;
}
}
if (buf==null)
return null;
}
synchronized(buf)
{
for (int i=0;i<path.length();i++)
{
char c=path.charAt(i);
switch(c)
{
case '%':
buf.append("%25");
continue;
case '?':
buf.append("%3F");
continue;
case ';':
buf.append("%3B");
continue;
case '#':
buf.append("%23");
continue;
case ' ':
buf.append("%20");
continue;
default:
buf.append(c);
continue;
}
}
}
return buf;
}
/* ------------------------------------------------------------ */
/** Encode a URI path.
* @param path The path the encode
* @param buf StringBuffer to encode path into (or null)
* @param encode String of characters to encode. % is always encoded.
* @return The StringBuffer or null if no substitutions required.
*/
public static StringBuffer encodeString(StringBuffer buf,
String path,
String encode)
{
if (buf==null)
{
loop:
for (int i=0;i<path.length();i++)
{
char c=path.charAt(i);
if (c=='%' || encode.indexOf(c)>=0)
{
buf=new StringBuffer(path.length()<<1);
break loop;
}
}
if (buf==null)
return null;
}
synchronized(buf)
{
for (int i=0;i<path.length();i++)
{
char c=path.charAt(i);
if (c=='%' || encode.indexOf(c)>=0)
{
buf.append('%');
StringUtil.append(buf,(byte)(0xff&c),16);
}
else
buf.append(c);
}
}
return buf;
}
/* ------------------------------------------------------------ */
/* Decode a URI path.
* @param path The path the encode
* @param buf StringBuffer to encode path into
*/
public static String decodePath(String path)
{
int len=path.length();
byte[] bytes=null;
int n=0;
boolean noDecode=true;
for (int i=0;i<len;i++)
{
char c = path.charAt(i);
byte b = (byte)(0xff & c);
if (c=='%' && (i+2)<len)
{
noDecode=false;
b=(byte)(0xff&TypeUtil.parseInt(path,i+1,2,16));
i+=2;
}
else if (bytes==null)
{
n++;
continue;
}
if (bytes==null)
{
noDecode=false;
bytes=new byte[len];
for (int j=0;j<n;j++)
bytes[j]=(byte)(0xff & path.charAt(j));
}
bytes[n++]=b;
}
if (noDecode)
return path;
try
{
return new String(bytes,0,n,__CHARSET);
}
catch(UnsupportedEncodingException e)
{
log.warn(LogSupport.EXCEPTION,e);
return new String(bytes,0,n);
}
}
/* ------------------------------------------------------------ */
/** Clone URI.
* @return cloned URI
*/
public Object clone()
throws CloneNotSupportedException
{
URI u = (URI)super.clone();
if (_parameters!=null)
u._parameters=(UrlEncoded)_parameters.clone();
_dirty=false;
return u;
}
/* ------------------------------------------------------------ */
/** Add two URI path segments.
* Handles null and empty paths, path and query params (eg ?a=b or
* ;JSESSIONID=xxx) and avoids duplicate '/'
* @param p1 URI path segment
* @param p2 URI path segment
* @return Legally combined path segments.
*/
public static String addPaths(String p1, String p2)
{
if (p1==null || p1.length()==0)
{
if (p2==null || p2.length()==0)
return p1;
return p2;
}
if (p2==null || p2.length()==0)
return p1;
int split=p1.indexOf(';');
if (split<0)
split=p1.indexOf('?');
if (split==0)
return p2+p1;
if (split<0)
split=p1.length();
StringBuffer buf = new StringBuffer(p1.length()+p2.length()+2);
buf.append(p1);
if (buf.charAt(split-1)=='/')
{
if (p2.startsWith("/"))
{
buf.deleteCharAt(split-1);
buf.insert(split-1,p2);
}
else
buf.insert(split,p2);
}
else
{
if (p2.startsWith("/"))
buf.insert(split,p2);
else
{
buf.insert(split,'/');
buf.insert(split+1,p2);
}
}
return buf.toString();
}
/* ------------------------------------------------------------ */
/** Return the parent Path.
* Treat a URI like a directory path and return the parent directory.
*/
public static String parentPath(String p)
{
if (p==null || "/".equals(p))
return null;
int slash=p.lastIndexOf('/',p.length()-2);
if (slash>=0)
return p.substring(0,slash+1);
return null;
}
/* ------------------------------------------------------------ */
/** Strip parameters from a path.
* Return path upto any semicolon parameters.
*/
public static String stripPath(String path)
{
if (path==null)
return null;
int semi=path.indexOf(';');
if (semi<0)
return path;
return path.substring(0,semi);
}
/* ------------------------------------------------------------ */
/** Convert a path to a cananonical form.
* All instances of "." and ".." are factored out. Null is returned
* if the path tries to .. above it's root.
* @param path
* @return path or null.
*/
public static String canonicalPath(String path)
{
if (path==null || path.length()==0)
return path;
int end=path.length();
int queryIdx=path.indexOf('?');
int start = path.lastIndexOf('/', (queryIdx > 0 ? queryIdx : end));
search:
while (end>0)
{
switch(end-start)
{
case 2: // possible single dot
if (path.charAt(start+1)!='.')
break;
break search;
case 3: // possible double dot
if (path.charAt(start+1)!='.' || path.charAt(start+2)!='.')
break;
break search;
}
end=start;
start=path.lastIndexOf('/',end-1);
}
// If we have checked the entire string
if (start>=end)
return path;
StringBuffer buf = new StringBuffer(path);
int delStart=-1;
int delEnd=-1;
int skip=0;
while (end>0)
{
switch(end-start)
{
case 2: // possible single dot
if (buf.charAt(start+1)!='.')
{
if (skip>0 && --skip==0)
{
delStart=start>=0?start:0;
if(delStart>0 && delEnd==buf.length() && buf.charAt(delEnd-1)=='.')
delStart++;
}
break;
}
if(start<0 && buf.length()>2 && buf.charAt(1)=='/' && buf.charAt(2)=='/')
break;
if(delEnd<0)
delEnd=end;
delStart=start;
if (delStart<0 || delStart==0&&buf.charAt(delStart)=='/')
{
delStart++;
if (delEnd<buf.length() && buf.charAt(delEnd)=='/')
delEnd++;
break;
}
if (end==buf.length())
delStart++;
end=start--;
while (start>=0 && buf.charAt(start)!='/')
start--;
continue;
case 3: // possible double dot
if (buf.charAt(start+1)!='.' || buf.charAt(start+2)!='.')
{
if (skip>0 && --skip==0)
{ delStart=start>=0?start:0;
if(delStart>0 && delEnd==buf.length() && buf.charAt(delEnd-1)=='.')
delStart++;
}
break;
}
delStart=start;
if (delEnd<0)
delEnd=end;
skip++;
end=start--;
while (start>=0 && buf.charAt(start)!='/')
start--;
continue;
default:
if (skip>0 && --skip==0)
{
delStart=start>=0?start:0;
if(delEnd==buf.length() && buf.charAt(delEnd-1)=='.')
delStart++;
}
}
// Do the delete
if (skip<=0 && delStart>=0 && delStart>=0)
{
buf.delete(delStart,delEnd);
delStart=delEnd=-1;
if (skip>0)
delEnd=end;
}
end=start--;
while (start>=0 && buf.charAt(start)!='/')
start--;
}
// Too many ..
if (skip>0)
return null;
// Do the delete
if (delEnd>=0)
buf.delete(delStart,delEnd);
return buf.toString();
}
/* ------------------------------------------------------------ */
/**
* @param uri URI
* @return True if the uri has a scheme
*/
public static boolean hasScheme(String uri)
{
for (int i=0;i<uri.length();i++)
{
char c=uri.charAt(i);
if (c==':')
return true;
if (!(c>='a'&&c<='z' ||
c>='A'&&c<='Z' ||
(i>0 &&(c>='0'&&c<='9' ||
c=='.' ||
c=='+' ||
c=='-'))
))
break;
}
return false;
}
}
| Jimmy-Gao/browsermob-proxy | src/main/java/org/browsermob/proxy/jetty/util/URI.java | Java | apache-2.0 | 29,068 |
/*
* Copyright 2022 ThoughtWorks, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.thoughtworks.go.apiv1.featuretoggles;
import com.thoughtworks.go.api.ApiController;
import com.thoughtworks.go.api.ApiVersion;
import com.thoughtworks.go.api.representers.JsonReader;
import com.thoughtworks.go.api.spring.ApiAuthenticationHelper;
import com.thoughtworks.go.api.util.GsonTransformer;
import com.thoughtworks.go.apiv1.featuretoggles.representers.FeatureTogglesRepresenter;
import com.thoughtworks.go.config.exceptions.UnprocessableEntityException;
import com.thoughtworks.go.server.domain.support.toggle.FeatureToggles;
import com.thoughtworks.go.server.service.support.toggle.FeatureToggleService;
import com.thoughtworks.go.spark.Routes;
import com.thoughtworks.go.spark.spring.SparkSpringController;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import spark.Request;
import spark.Response;
import java.io.IOException;
import static spark.Spark.*;
@Component
public class FeatureTogglesControllerV1 extends ApiController implements SparkSpringController {
private final ApiAuthenticationHelper apiAuthenticationHelper;
private FeatureToggleService featureToggleService;
@Autowired
public FeatureTogglesControllerV1(ApiAuthenticationHelper apiAuthenticationHelper, FeatureToggleService featureToggleService) {
super(ApiVersion.v1);
this.apiAuthenticationHelper = apiAuthenticationHelper;
this.featureToggleService = featureToggleService;
}
@Override
public String controllerBasePath() {
return Routes.FeatureToggle.BASE;
}
@Override
public void setupRoutes() {
path(controllerBasePath(), () -> {
before("", mimeType, this::setContentType);
before("/*", mimeType, this::setContentType);
before("", mimeType, this.apiAuthenticationHelper::checkAdminUserAnd403);
before("/*", mimeType, this.apiAuthenticationHelper::checkAdminUserAnd403);
get("", mimeType, this::index);
put(Routes.FeatureToggle.FEATURE_TOGGLE_KEY, mimeType, this::update);
});
}
public String index(Request request, Response response) throws IOException {
FeatureToggles featureToggles = featureToggleService.allToggles();
return writerForTopLevelArray(request, response, outputWriter -> FeatureTogglesRepresenter.toJSON(outputWriter, featureToggles));
}
public String update(Request request, Response response) throws IOException {
JsonReader jsonReader = GsonTransformer.getInstance().jsonReaderFrom(request.body());
String toggleValue = jsonReader.getString("toggle_value");
if (!(StringUtils.equalsIgnoreCase("on", toggleValue) || StringUtils.equalsIgnoreCase("off", toggleValue))) {
throw new UnprocessableEntityException("Value of property \"toggle_value\" is invalid. Valid values are: \"on\" and \"off\".");
}
featureToggleService.changeValueOfToggle(request.params("toggle_key"), toggleValue.equalsIgnoreCase("on"));
return writerForTopLevelObject(request, response, writer -> writer.add("message", "success"));
}
}
| Skarlso/gocd | api/api-feature-toggles-v1/src/main/java/com/thoughtworks/go/apiv1/featuretoggles/FeatureTogglesControllerV1.java | Java | apache-2.0 | 3,800 |
/**
* Copyright (C) 2006-2009 Dustin Sallings
* Copyright (C) 2009-2013 Couchbase, Inc.
*
* 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 DEALING
* IN THE SOFTWARE.
*/
package net.spy.memcached.protocol.ascii;
import java.nio.ByteBuffer;
import java.util.Collection;
import java.util.Collections;
import net.spy.memcached.KeyUtil;
import net.spy.memcached.ops.TouchOperation;
import net.spy.memcached.ops.OperationState;
import net.spy.memcached.ops.OperationStatus;
import net.spy.memcached.ops.OperationCallback;
/**
* Memcached touch operation.
*/
final class TouchOperationImpl extends OperationImpl implements TouchOperation {
private static final int OVERHEAD = 9;
private static final OperationStatus OK =
new OperationStatus(true, "TOUCHED");
private final String key;
private final long exp;
public TouchOperationImpl(String k, long t, OperationCallback cb) {
super(cb);
key = k;
exp = t;
}
// This method implements getKeys in KeyedOperation and should be moved
// once TouchOperation in ops is unified with the binary touch method impl.
public Collection<String> getKeys() {
return Collections.singleton(key);
}
@Override
public void handleLine(String line) {
getLogger().debug("Touch completed successfully");
getCallback().receivedStatus(matchStatus(line, OK));
transitionState(OperationState.COMPLETE);
}
@Override
public void initialize() {
ByteBuffer b = null;
b = ByteBuffer.allocate(KeyUtil.getKeyBytes(key).length
+ String.valueOf(exp).length() + OVERHEAD);
b.put(("touch " + key + " " + exp + "\r\n").getBytes());
b.flip();
setBuffer(b);
}
@Override
public String toString() {
return "Cmd: touch key: " + key + " exp: " + exp;
}
}
| Alachisoft/TayzGrid | integrations/memcached/clients/spymemcached/src/net/spy/memcached/protocol/ascii/TouchOperationImpl.java | Java | apache-2.0 | 2,766 |
/*
* Copyright 2006-2011 The Virtual Laboratory for e-Science (VL-e)
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* For details, see the LICENCE.txt file location in the root directory of this
* distribution or obtain the Apache Licence at the following location:
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* See: http://www.vl-e.nl/
* See: LICENCE.txt (located in the root folder of this distribution).
* ---
* $Id: AttributeEditorForm.java,v 1.2 2011-04-18 12:27:13 ptdeboer Exp $
* $Date: 2011-04-18 12:27:13 $
*/
// source:
package nl.uva.vlet.gui.panels.attribute;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Rectangle;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.border.BevelBorder;
import nl.uva.vlet.ClassLogger;
import nl.uva.vlet.Global;
import nl.uva.vlet.data.VAttribute;
import nl.uva.vlet.data.VAttributeSet;
import nl.uva.vlet.gui.GuiSettings;
import nl.uva.vlet.gui.UIGlobal;
import nl.uva.vlet.gui.UIPlatform;
import nl.uva.vlet.gui.font.FontUtil;
public class AttributeEditorForm extends JDialog
{
private static final long serialVersionUID = 9136623460001660679L;
// ---
AttributePanel infoPanel;
// package accesable buttons:
JButton cancelButton;
JButton okButton;
JButton resetButton;
// data:
VAttribute[] originalAttributes;
// ui stuff
private JTextField topLabelTextField;
private JPanel buttonPanel;
private AttributeEditorController formController;
private String titleName;
//private JFrame frame=null;
private JPanel mainPanel;
private boolean isEditable;
private void initGUI(VAttribute attrs[])
{
try
{
this.setTitle(this.titleName);
BorderLayout thisLayout = new BorderLayout();
this.getContentPane().setLayout(thisLayout);
// this.setSize(398, 251);
// mainPanel:
/*{
mainPanel=new JPanel();
mainPanel.setLayout(new BorderLayout());
this.getContentPane().add(mainPanel,BorderLayout.CENTER);
}*/
Container rootContainer = this.getContentPane();
{
topLabelTextField = new JTextField();
rootContainer.add(topLabelTextField, BorderLayout.NORTH);
topLabelTextField.setText(this.titleName);
topLabelTextField.setEditable(false);
topLabelTextField.setFocusable(false);
topLabelTextField.setBorder(BorderFactory
.createEtchedBorder(BevelBorder.RAISED));
topLabelTextField.setFont(FontUtil.createFont("dialog")); // GuiSettings.current.default_label_font) ;
// new java.awt.Font("Lucida Sans", 1,14));
topLabelTextField.setHorizontalAlignment(SwingConstants.CENTER);
topLabelTextField.setName("huh");
}
{
infoPanel=new AttributePanel(attrs,isEditable);
rootContainer.add(infoPanel,BorderLayout.CENTER);
//infoPanel.setAttributes(attrs,true);
}
{
buttonPanel = new JPanel();
rootContainer.add(buttonPanel, BorderLayout.SOUTH);
{
okButton = new JButton();
buttonPanel.add(okButton);
okButton.setText("Accept");
okButton.addActionListener(formController);
okButton.setEnabled(this.isEditable);
}
{
resetButton = new JButton();
buttonPanel.add(resetButton);
resetButton.setText("Reset");
resetButton.addActionListener(formController);
}
{
cancelButton = new JButton();
buttonPanel.add(cancelButton);
cancelButton.setText("Cancel");
cancelButton.addActionListener(formController);
}
}
validate();
// update size:
//infoPanel.setSize(infoPanel.getPreferredSize());
Dimension size = this.getPreferredSize();
// bug in FormLayout ? Last row is now shown
// add extra space:
size.height+=32;
size.width+=128; // make extra wide
setSize(size);
}
catch (Exception e)
{
e.printStackTrace();
}
}
// ==========================================================================
// Constructor
// ==========================================================================
private void init(String titleName, VAttribute attrs[])
{
//frame = new JFrame();
this.originalAttributes=attrs;
this.titleName=titleName;
attrs=VAttribute.duplicateArray(attrs); // use duplicate to edit;
// Must first create ActionListener since it is used in initGui...
this.formController = new AttributeEditorController(this);
this.addWindowListener(formController);
// only set to editable if there exists at least one editable attribute
this.isEditable=false;
for (VAttribute attr:attrs)
{
if ((attr!=null) && (attr.isEditable()==true))
this.isEditable=true;
}
initGUI(attrs);
formController.update();
//frame.add(this);
//frame.pack();
Rectangle windowRec=GuiSettings.getOptimalWindow(this);
//this.setPreferredSize(windowRec.getSize());
this.setLocation(windowRec.getLocation());
this.validate();
// No auto-show: this.setVisible(true);
}
public AttributeEditorForm(String titleName, VAttribute attrs[])
{
super();
UIPlatform.getPlatform().getWindowRegistry().register(this);
init(titleName,attrs);
}
public AttributeEditorForm()
{
UIPlatform.getPlatform().getWindowRegistry().register(this);
//init("Example Attribute Editor",null);
}
// ==========================================================================
//
// ==========================================================================
public void setAttributes(VAttribute[] attributes)
{
this.originalAttributes=attributes;
// use duplicate to edit:
attributes=VAttribute.duplicateArray(attributes);
this.infoPanel.setAttributes(new VAttributeSet(attributes),true);
validate();
}
public synchronized void Exit()
{
// notify waiting threads: waitForDialog().
this.notifyAll();
myDispose();
}
private void myDispose()
{
this.dispose();
}
// ==========================================================================
// main
// ==========================================================================
/**
* Static method to interactively ask user for attribute settings
* Automatically call Swing invoke later if current thread is not the Gui Event thread.
*
*/
public static VAttribute[] editAttributes(final String titleName, final VAttribute[] attrs,
final boolean returnChangedAttributesOnly)
{
final AttributeEditorForm dialog = new AttributeEditorForm();
Runnable formTask=new Runnable()
{
public void run()
{
// perform init during GUI thread
dialog.init(titleName,attrs);
//is now in constructor: dialog.setEditable(true);
// modal=true => after setVisible, dialog will not return until windows closed
dialog.setModal(true);
dialog.setAlwaysOnTop(true);
dialog.setVisible(true);
synchronized(this)
{
this.notifyAll();
}
}
};
/** Run during gui thread of use Swing invokeLater() */
if (UIGlobal.isGuiThread())
{
formTask.run(); // run directly:
}
else
{
// go background:
SwingUtilities.invokeLater(formTask);
synchronized(formTask)
{
try
{
//System.err.println("EditForm.wait()");
formTask.wait();
}
catch (InterruptedException e)
{
Global.logException(ClassLogger.ERROR,AttributeEditorForm.class,e,"--- Interupted ---\n");
}
}
}
// wait
if (dialog.formController.isOk==true)
{
// boolean update=dialog.hasChangedAttributes();
if (returnChangedAttributesOnly)
return dialog.infoPanel.getChangedAttributes();
else
return dialog.infoPanel.getAttributes();
}
else
{
return null;
}
}
/*private void setEditable(boolean b)
{
this.infoPanel.setEditable(b);
}*/
public boolean hasChangedAttributes()
{
return this.infoPanel.hasChangedAttributes();
}
}
| skoulouzis/vlet-1.5.0 | source/core/nl.uva.vlet.gui.utils/src/nl/uva/vlet/gui/panels/attribute/AttributeEditorForm.java | Java | apache-2.0 | 10,061 |
// Copyright (c) 2008 The Board of Trustees of The Leland Stanford Junior University
// Copyright (c) 2011, 2012 Open Networking Foundation
// Copyright (c) 2012, 2013 Big Switch Networks, Inc.
// This library was generated by the LoxiGen Compiler.
// See the file LICENSE.txt which should have been included in the source distribution
// Automatically generated by LOXI from template of_class.java
// Do not modify
package org.projectfloodlight.openflow.protocol.ver13;
import org.projectfloodlight.openflow.protocol.*;
import org.projectfloodlight.openflow.protocol.action.*;
import org.projectfloodlight.openflow.protocol.actionid.*;
import org.projectfloodlight.openflow.protocol.bsntlv.*;
import org.projectfloodlight.openflow.protocol.errormsg.*;
import org.projectfloodlight.openflow.protocol.meterband.*;
import org.projectfloodlight.openflow.protocol.instruction.*;
import org.projectfloodlight.openflow.protocol.instructionid.*;
import org.projectfloodlight.openflow.protocol.match.*;
import org.projectfloodlight.openflow.protocol.stat.*;
import org.projectfloodlight.openflow.protocol.oxm.*;
import org.projectfloodlight.openflow.protocol.oxs.*;
import org.projectfloodlight.openflow.protocol.queueprop.*;
import org.projectfloodlight.openflow.types.*;
import org.projectfloodlight.openflow.util.*;
import org.projectfloodlight.openflow.exceptions.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Set;
import io.netty.buffer.ByteBuf;
import com.google.common.hash.PrimitiveSink;
import com.google.common.hash.Funnel;
class OFBadMatchErrorMsgVer13 implements OFBadMatchErrorMsg {
private static final Logger logger = LoggerFactory.getLogger(OFBadMatchErrorMsgVer13.class);
// version: 1.3
final static byte WIRE_VERSION = 4;
final static int MINIMUM_LENGTH = 12;
private final static long DEFAULT_XID = 0x0L;
private final static OFErrorCauseData DEFAULT_DATA = OFErrorCauseData.NONE;
// OF message fields
private final long xid;
private final OFBadMatchCode code;
private final OFErrorCauseData data;
//
// package private constructor - used by readers, builders, and factory
OFBadMatchErrorMsgVer13(long xid, OFBadMatchCode code, OFErrorCauseData data) {
if(code == null) {
throw new NullPointerException("OFBadMatchErrorMsgVer13: property code cannot be null");
}
if(data == null) {
throw new NullPointerException("OFBadMatchErrorMsgVer13: property data cannot be null");
}
this.xid = xid;
this.code = code;
this.data = data;
}
// Accessors for OF message fields
@Override
public OFVersion getVersion() {
return OFVersion.OF_13;
}
@Override
public OFType getType() {
return OFType.ERROR;
}
@Override
public long getXid() {
return xid;
}
@Override
public OFErrorType getErrType() {
return OFErrorType.BAD_MATCH;
}
@Override
public OFBadMatchCode getCode() {
return code;
}
@Override
public OFErrorCauseData getData() {
return data;
}
public OFBadMatchErrorMsg.Builder createBuilder() {
return new BuilderWithParent(this);
}
static class BuilderWithParent implements OFBadMatchErrorMsg.Builder {
final OFBadMatchErrorMsgVer13 parentMessage;
// OF message fields
private boolean xidSet;
private long xid;
private boolean codeSet;
private OFBadMatchCode code;
private boolean dataSet;
private OFErrorCauseData data;
BuilderWithParent(OFBadMatchErrorMsgVer13 parentMessage) {
this.parentMessage = parentMessage;
}
@Override
public OFVersion getVersion() {
return OFVersion.OF_13;
}
@Override
public OFType getType() {
return OFType.ERROR;
}
@Override
public long getXid() {
return xid;
}
@Override
public OFBadMatchErrorMsg.Builder setXid(long xid) {
this.xid = xid;
this.xidSet = true;
return this;
}
@Override
public OFErrorType getErrType() {
return OFErrorType.BAD_MATCH;
}
@Override
public OFBadMatchCode getCode() {
return code;
}
@Override
public OFBadMatchErrorMsg.Builder setCode(OFBadMatchCode code) {
this.code = code;
this.codeSet = true;
return this;
}
@Override
public OFErrorCauseData getData() {
return data;
}
@Override
public OFBadMatchErrorMsg.Builder setData(OFErrorCauseData data) {
this.data = data;
this.dataSet = true;
return this;
}
@Override
public OFBadMatchErrorMsg build() {
long xid = this.xidSet ? this.xid : parentMessage.xid;
OFBadMatchCode code = this.codeSet ? this.code : parentMessage.code;
if(code == null)
throw new NullPointerException("Property code must not be null");
OFErrorCauseData data = this.dataSet ? this.data : parentMessage.data;
if(data == null)
throw new NullPointerException("Property data must not be null");
//
return new OFBadMatchErrorMsgVer13(
xid,
code,
data
);
}
}
static class Builder implements OFBadMatchErrorMsg.Builder {
// OF message fields
private boolean xidSet;
private long xid;
private boolean codeSet;
private OFBadMatchCode code;
private boolean dataSet;
private OFErrorCauseData data;
@Override
public OFVersion getVersion() {
return OFVersion.OF_13;
}
@Override
public OFType getType() {
return OFType.ERROR;
}
@Override
public long getXid() {
return xid;
}
@Override
public OFBadMatchErrorMsg.Builder setXid(long xid) {
this.xid = xid;
this.xidSet = true;
return this;
}
@Override
public OFErrorType getErrType() {
return OFErrorType.BAD_MATCH;
}
@Override
public OFBadMatchCode getCode() {
return code;
}
@Override
public OFBadMatchErrorMsg.Builder setCode(OFBadMatchCode code) {
this.code = code;
this.codeSet = true;
return this;
}
@Override
public OFErrorCauseData getData() {
return data;
}
@Override
public OFBadMatchErrorMsg.Builder setData(OFErrorCauseData data) {
this.data = data;
this.dataSet = true;
return this;
}
//
@Override
public OFBadMatchErrorMsg build() {
long xid = this.xidSet ? this.xid : DEFAULT_XID;
if(!this.codeSet)
throw new IllegalStateException("Property code doesn't have default value -- must be set");
if(code == null)
throw new NullPointerException("Property code must not be null");
OFErrorCauseData data = this.dataSet ? this.data : DEFAULT_DATA;
if(data == null)
throw new NullPointerException("Property data must not be null");
return new OFBadMatchErrorMsgVer13(
xid,
code,
data
);
}
}
final static Reader READER = new Reader();
static class Reader implements OFMessageReader<OFBadMatchErrorMsg> {
@Override
public OFBadMatchErrorMsg readFrom(ByteBuf bb) throws OFParseError {
int start = bb.readerIndex();
// fixed value property version == 4
byte version = bb.readByte();
if(version != (byte) 0x4)
throw new OFParseError("Wrong version: Expected=OFVersion.OF_13(4), got="+version);
// fixed value property type == 1
byte type = bb.readByte();
if(type != (byte) 0x1)
throw new OFParseError("Wrong type: Expected=OFType.ERROR(1), got="+type);
int length = U16.f(bb.readShort());
if(length < MINIMUM_LENGTH)
throw new OFParseError("Wrong length: Expected to be >= " + MINIMUM_LENGTH + ", was: " + length);
if(bb.readableBytes() + (bb.readerIndex() - start) < length) {
// Buffer does not have all data yet
bb.readerIndex(start);
return null;
}
if(logger.isTraceEnabled())
logger.trace("readFrom - length={}", length);
long xid = U32.f(bb.readInt());
// fixed value property errType == 4
short errType = bb.readShort();
if(errType != (short) 0x4)
throw new OFParseError("Wrong errType: Expected=OFErrorType.BAD_MATCH(4), got="+errType);
OFBadMatchCode code = OFBadMatchCodeSerializerVer13.readFrom(bb);
OFErrorCauseData data = OFErrorCauseData.read(bb, length - (bb.readerIndex() - start), OFVersion.OF_13);
OFBadMatchErrorMsgVer13 badMatchErrorMsgVer13 = new OFBadMatchErrorMsgVer13(
xid,
code,
data
);
if(logger.isTraceEnabled())
logger.trace("readFrom - read={}", badMatchErrorMsgVer13);
return badMatchErrorMsgVer13;
}
}
public void putTo(PrimitiveSink sink) {
FUNNEL.funnel(this, sink);
}
final static OFBadMatchErrorMsgVer13Funnel FUNNEL = new OFBadMatchErrorMsgVer13Funnel();
static class OFBadMatchErrorMsgVer13Funnel implements Funnel<OFBadMatchErrorMsgVer13> {
private static final long serialVersionUID = 1L;
@Override
public void funnel(OFBadMatchErrorMsgVer13 message, PrimitiveSink sink) {
// fixed value property version = 4
sink.putByte((byte) 0x4);
// fixed value property type = 1
sink.putByte((byte) 0x1);
// FIXME: skip funnel of length
sink.putLong(message.xid);
// fixed value property errType = 4
sink.putShort((short) 0x4);
OFBadMatchCodeSerializerVer13.putTo(message.code, sink);
message.data.putTo(sink);
}
}
public void writeTo(ByteBuf bb) {
WRITER.write(bb, this);
}
final static Writer WRITER = new Writer();
static class Writer implements OFMessageWriter<OFBadMatchErrorMsgVer13> {
@Override
public void write(ByteBuf bb, OFBadMatchErrorMsgVer13 message) {
int startIndex = bb.writerIndex();
// fixed value property version = 4
bb.writeByte((byte) 0x4);
// fixed value property type = 1
bb.writeByte((byte) 0x1);
// length is length of variable message, will be updated at the end
int lengthIndex = bb.writerIndex();
bb.writeShort(U16.t(0));
bb.writeInt(U32.t(message.xid));
// fixed value property errType = 4
bb.writeShort((short) 0x4);
OFBadMatchCodeSerializerVer13.writeTo(bb, message.code);
message.data.writeTo(bb);
// update length field
int length = bb.writerIndex() - startIndex;
bb.setShort(lengthIndex, length);
}
}
@Override
public String toString() {
StringBuilder b = new StringBuilder("OFBadMatchErrorMsgVer13(");
b.append("xid=").append(xid);
b.append(", ");
b.append("code=").append(code);
b.append(", ");
b.append("data=").append(data);
b.append(")");
return b.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
OFBadMatchErrorMsgVer13 other = (OFBadMatchErrorMsgVer13) obj;
if( xid != other.xid)
return false;
if (code == null) {
if (other.code != null)
return false;
} else if (!code.equals(other.code))
return false;
if (data == null) {
if (other.data != null)
return false;
} else if (!data.equals(other.data))
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * (int) (xid ^ (xid >>> 32));
result = prime * result + ((code == null) ? 0 : code.hashCode());
result = prime * result + ((data == null) ? 0 : data.hashCode());
return result;
}
}
| mehdi149/OF_COMPILER_0.1 | gen-src/main/java/org/projectfloodlight/openflow/protocol/ver13/OFBadMatchErrorMsgVer13.java | Java | apache-2.0 | 12,857 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.pig.tuple;
import java.util.List;
import org.apache.pig.data.BagFactory;
import org.apache.pig.data.DataBag;
import org.apache.pig.data.Tuple;
import org.apache.pig.data.TupleFactory;
@SuppressWarnings("javadoc")
public class PigUtil {
/**
* Wraps input Objects in a Tuple
* @param objects Objects intended to be wrapped
* @return a Pig Tuple containing the input Objects
*/
public static Tuple objectsToTuple(final Object ... objects) {
final Tuple tuple = TupleFactory.getInstance().newTuple();
for (final Object object: objects) { tuple.append(object); }
return tuple;
}
/**
* Wraps a set of Tuples in a DataBag
* @param tuples Tuples to wrap
* @return a Pig DataBag containing the input Tuples
*/
public static DataBag tuplesToBag(final Tuple ... tuples) {
final DataBag bag = BagFactory.getInstance().newDefaultBag();
for (final Tuple tuple: tuples) { bag.add(tuple); }
return bag;
}
/**
* Wraps a List of objects into a DataBag of Tuples (one object per Tuple)
* @param list List of items to wrap
* @param <T> Type of objects in the List
* @return a Pig DataBag containing Tuples populated with list items
*/
public static <T> DataBag listToBagOfTuples(final List<T> list) {
final DataBag bag = BagFactory.getInstance().newDefaultBag();
for (final Object object: list) {
final Tuple tuple = TupleFactory.getInstance().newTuple();
tuple.append(object);
bag.add(tuple);
}
return bag;
}
}
| DataSketches/sketches-pig | src/test/java/org/apache/datasketches/pig/tuple/PigUtil.java | Java | apache-2.0 | 2,371 |
/*
* Copyright 2015 The Closure Compiler Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.javascript.jscomp;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link ImplicitNullabilityCheck}. */
@RunWith(JUnit4.class)
public final class ImplicitNullabilityCheckTest extends CompilerTestCase {
@Override
protected CompilerOptions getOptions(CompilerOptions options) {
options.setWarningLevel(DiagnosticGroups.ANALYZER_CHECKS, CheckLevel.WARNING);
return options;
}
@Override
protected CompilerPass getProcessor(Compiler compiler) {
return new ImplicitNullabilityCheck(compiler);
}
@Override
protected int getNumRepetitions() {
return 1;
}
@Override
@Before
public void setUp() throws Exception {
super.setUp();
enableTypeCheck();
}
@Test
public void testExplicitJsdocDoesntWarn() {
noWarning("/** @type {boolean} */ var x;");
noWarning("/** @type {symbol} */ var x;");
noWarning("/** @type {null} */ var x;");
noWarning("/** @type {!Object} */ var x;");
noWarning("/** @type {?Object} */ var x;");
noWarning("/** @type {function(new:Object)} */ function f(){}");
noWarning("/** @type {function(this:Object)} */ function f(){}");
noWarning("/** @typedef {!Object} */ var Obj; var /** Obj */ x;");
// Test let and const
noWarning("/** @type {boolean} */ let x;");
noWarning("/** @type {!Object} */ let x;");
noWarning("/** @type {!Object} */ const x = {};");
noWarning("/** @type {boolean} */ const x = true;");
}
@Test
public void testExplicitlyNullableUnion() {
noWarning("/** @type {(Object|null)} */ var x;");
noWarning("/** @type {(Object|number)?} */ var x;");
noWarning("/** @type {?(Object|number)} */ var x;");
noWarning("/** @type {(Object|?number)} */ var x;");
warnImplicitlyNullable("/** @type {(Object|number)} */ var x;");
noWarning("/** @type {(Object|null)} */ let x;");
warnImplicitlyNullable("/** @type {(Object|number)} */ let x;");
noWarning("/** @type {(Object|null)} */ const x = null;");
warnImplicitlyNullable("/** @type {(Object|number)} */ const x = 3;;");
}
@Test
public void testJsdocPositions() {
warnImplicitlyNullable("/** @type {Object} */ var x;");
warnImplicitlyNullable("var /** Object */ x;");
warnImplicitlyNullable("/** @typedef {Object} */ var x;");
warnImplicitlyNullable("/** @param {Object} x */ function f(x){}");
warnImplicitlyNullable("/** @return {Object} */ function f(x){ return {}; }");
warnImplicitlyNullable("/** @type {Object} */ let x;");
warnImplicitlyNullable("/** @type {Object} */ const x = {};");
}
@Test
public void testParameterizedObject() {
warnImplicitlyNullable(lines(
"/** @param {Object<string, string>=} opt_values */",
"function getMsg(opt_values) {};"));
}
@Test
public void testNullableTypedef() {
// Arguable whether or not this deserves a warning
warnImplicitlyNullable("/** @typedef {?number} */ var Num; var /** Num */ x;");
}
@Test
public void testUnknownTypenameDoesntWarn() {
test(
externs(DEFAULT_EXTERNS),
srcs("/** @type {gibberish} */ var x;"),
warning(RhinoErrorReporter.UNRECOGNIZED_TYPE_ERROR));
}
@Test
public void testThrowsDoesntWarn() {
noWarning("/** @throws {Error} */ function f() {}");
noWarning("/** @throws {TypeError}\n * @throws {SyntaxError} */ function f() {}");
}
@Test
public void testUserDefinedClass() {
warnImplicitlyNullable(lines(
"/** @constructor */",
"function Foo() {}",
"/** @type {Foo} */ var x;"));
warnImplicitlyNullable(lines(
"function f() {",
" /** @constructor */",
" function Foo() {}",
" /** @type {Foo} */ var x;",
"}"));
}
@Test
public void testNamespacedTypeDoesntCrash() {
warnImplicitlyNullable(lines(
"/** @const */ var a = {};",
"/** @const */ a.b = {};",
"/** @constructor */ a.b.Foo = function() {};",
"/** @type Array<!a.b.Foo> */ var foos = [];"));
}
private void warnImplicitlyNullable(String js) {
test(
externs(DEFAULT_EXTERNS),
srcs(js),
warning(ImplicitNullabilityCheck.IMPLICITLY_NULLABLE_JSDOC));
}
private void noWarning(String js) {
testSame(externs(DEFAULT_EXTERNS), srcs(js));
}
}
| shantanusharma/closure-compiler | test/com/google/javascript/jscomp/ImplicitNullabilityCheckTest.java | Java | apache-2.0 | 5,005 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.jena.ext.xerces.impl.dv.xs;
/**
* {@literal @xerces.internal}
*
* @version $Id: SchemaDateTimeException.java 446745 2006-09-15 21:43:58Z mrglavas $
*/
public class SchemaDateTimeException extends RuntimeException {
/** Serialization version. */
static final long serialVersionUID = -8520832235337769040L;
public SchemaDateTimeException () {
super();
}
public SchemaDateTimeException (String s) {
super (s);
}
}
| apache/jena | jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/SchemaDateTimeException.java | Java | apache-2.0 | 1,295 |
package cd.go.contrib.elasticagents.docker.requests;
import com.google.gson.JsonObject;
import org.junit.Test;
import java.util.Collections;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
public class ClusterStatusReportRequestTest {
@Test
public void shouldDeserializeFromJSON() {
JsonObject jsonObject = new JsonObject();
JsonObject clusterJSON = new JsonObject();
clusterJSON.addProperty("go_server_url", "https://go-server/go");
jsonObject.add("cluster_profile_properties", clusterJSON);
ClusterStatusReportRequest clusterStatusReportRequest = ClusterStatusReportRequest.fromJSON(jsonObject.toString());
ClusterStatusReportRequest expected = new ClusterStatusReportRequest(Collections.singletonMap("go_server_url", "https://go-server/go"));
assertThat(clusterStatusReportRequest, is(expected));
}
} | ketan/docker-elastic-agents | src/test/java/cd/go/contrib/elasticagents/docker/requests/ClusterStatusReportRequestTest.java | Java | apache-2.0 | 927 |
/* ========================================================================= *
* *
* The Apache Software License, Version 1.1 *
* *
* Copyright (c) 1999, 2000, 2001 The Apache Software Foundation. *
* All rights reserved. *
* *
* ========================================================================= *
* *
* Redistribution and use in source and binary forms, with or without modi- *
* fication, are permitted provided that the following conditions are met: *
* *
* 1. Redistributions of source code must retain the above copyright notice *
* notice, this list of conditions and the following disclaimer. *
* *
* 2. Redistributions in binary form must reproduce the above copyright *
* notice, this list of conditions and the following disclaimer in the *
* documentation and/or other materials provided with the distribution. *
* *
* 3. The end-user documentation included with the redistribution, if any, *
* must include the following acknowlegement: *
* *
* "This product includes software developed by the Apache Software *
* Foundation <http://www.apache.org/>." *
* *
* Alternately, this acknowlegement may appear in the software itself, if *
* and wherever such third-party acknowlegements normally appear. *
* *
* 4. The names "The Jakarta Project", "Tomcat", and "Apache Software *
* Foundation" must not be used to endorse or promote products derived *
* from this software without prior written permission. For written *
* permission, please contact <[email protected]>. *
* *
* 5. Products derived from this software may not be called "Apache" nor may *
* "Apache" appear in their names without prior written permission of the *
* Apache Software Foundation. *
* *
* THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESSED OR IMPLIED WARRANTIES *
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY *
* AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL *
* THE APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY *
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL *
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS *
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) *
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, *
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN *
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE *
* POSSIBILITY OF SUCH DAMAGE. *
* *
* ========================================================================= *
* *
* This software consists of voluntary contributions made by many indivi- *
* duals on behalf of the Apache Software Foundation. For more information *
* on the Apache Software Foundation, please see <http://www.apache.org/>. *
* *
* ========================================================================= */
package org.apache.tester;
import java.io.*;
import java.security.Principal;
import javax.servlet.*;
import javax.servlet.http.*;
/**
* Ensure that a resource protected a a security constratint that allows all
* roles will permit access to an authenticated user.
*
* @author Craig R. McClanahan
* @version $Revision: 1.1 $ $Date: 2001/05/10 23:57:05 $
*/
public class Authentication05 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
response.setContentType("text/plain");
PrintWriter writer = response.getWriter();
StringBuffer sb = new StringBuffer();
String remoteUser = request.getRemoteUser();
if (remoteUser == null)
sb.append(" No remote user returned/");
else if (!"tomcat".equals(remoteUser)) {
sb.append(" Remote user is '");
sb.append(remoteUser);
sb.append("'/");
}
Principal userPrincipal = request.getUserPrincipal();
if (userPrincipal == null)
sb.append(" No user principal returned/");
else if (!"tomcat".equals(userPrincipal.getName())) {
sb.append(" User principal is '");
sb.append(userPrincipal);
sb.append("'/");
}
if (!request.isUserInRole("tomcat"))
sb.append(" Not in role 'tomcat'/");
if (sb.length() < 1)
writer.println("Authentication05 PASSED");
else {
writer.print("Authentication05 FAILED -");
writer.println(sb.toString());
}
while (true) {
String message = StaticLogger.read();
if (message == null)
break;
writer.println(message);
}
StaticLogger.reset();
}
}
| devjin24/howtomcatworks | bookrefer/jakarta-tomcat-4.1.12-src/tester/src/tester/org/apache/tester/Authentication05.java | Java | apache-2.0 | 6,281 |
package com.senseidb.search.client.req.relevance;
import org.json.JSONException;
import org.json.JSONObject;
import com.senseidb.search.client.json.JsonHandler;
import com.senseidb.search.client.json.JsonSerializer;
public class RelevanceValuesHandler implements JsonHandler<RelevanceValues> {
@Override
public JSONObject serialize(RelevanceValues bean) throws JSONException {
if (bean == null) {
return null;
}
return (JSONObject) JsonSerializer.serialize(bean.values);
}
@Override
public RelevanceValues deserialize(JSONObject json) throws JSONException {
throw new UnsupportedOperationException();
}
}
| senseidb/sensei | clients/java/src/main/java/com/senseidb/search/client/req/relevance/RelevanceValuesHandler.java | Java | apache-2.0 | 645 |
/*
* Copyright 2017 IBM Corp. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.ibm.watson.developer_cloud.speech_to_text.v1.model;
import com.google.gson.annotations.SerializedName;
import com.ibm.watson.developer_cloud.service.model.GenericModel;
/**
* Customization corpus. The information includes the total number of
* words and out-of-vocabulary (OOV) words, name, and status of each corpus.
* Only the owner of a custom model can use this method to list the model's corpora.
*/
public class Corpus extends GenericModel {
/**
* Corpus Status.
*/
public enum Status {
/** The corpus has been successfully analyzed. */
@SerializedName("analyzed") ANALYZED,
/** The corpus is being processed. */
@SerializedName("being_processed") BEING_PROCESSED,
/** The corpus analysis has encountered a problem. */
@SerializedName("undetermined") UNDETERMINED
}
private String error;
private String name;
@SerializedName("out_of_vocabulary_words")
private Integer outOfVocabularyWords;
private Status status;
@SerializedName("total_words")
private Integer totalWords;
/**
* Gets the error.
*
* @return the error
*/
public String getError() {
return error;
}
/**
* Gets the name.
*
* @return the name
*/
public String getName() {
return name;
}
/**
* The number of OOV words in the corpus. The value is 0 while the corpus is being processed.
*
* @return the out of vocabulary words
*/
public Integer getOutOfVocabularyWords() {
return outOfVocabularyWords;
}
/**
* Gets the status.
*
* @return the status
*/
public Status getStatus() {
return status;
}
/**
* The total number of words in the corpus. The value is 0 while the corpus is being processed.
*
* @return the total words
*/
public Integer getTotalWords() {
return totalWords;
}
/**
* Sets the error.
*
* @param error the new error
*/
public void setError(String error) {
this.error = error;
}
/**
* Sets the name.
*
* @param name the new name
*/
public void setName(String name) {
this.name = name;
}
/**
* Sets the number of OOV words in the corpus.
*
* @param outOfVocabularyWOrds the new out of vocabulary words
*/
public void setOutOfVocabularyWords(Integer outOfVocabularyWOrds) {
this.outOfVocabularyWords = outOfVocabularyWOrds;
}
/**
* Sets the status.
*
* @param status the new status
*/
public void setStatus(Status status) {
this.status = status;
}
/**
* Sets the total words.
*
* @param totalWords the new total words
*/
public void setTotalWords(Integer totalWords) {
this.totalWords = totalWords;
}
}
| JoshSharpe/java-sdk | speech-to-text/src/main/java/com/ibm/watson/developer_cloud/speech_to_text/v1/model/Corpus.java | Java | apache-2.0 | 3,288 |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.common.base;
import com.google.common.annotations.GwtIncompatible;
import java.lang.ref.PhantomReference;
import java.lang.ref.ReferenceQueue;
/**
* Phantom reference with a {@code finalizeReferent()} method which a background thread invokes
* after the garbage collector reclaims the referent. This is a simpler alternative to using a
* {@link ReferenceQueue}.
*
* <p>Unlike a normal phantom reference, this reference will be cleared automatically.
*
* @author Bob Lee
* @since 2.0
*/
@GwtIncompatible
public abstract class FinalizablePhantomReference<T> extends PhantomReference<T>
implements FinalizableReference {
/**
* Constructs a new finalizable phantom reference.
*
* @param referent to phantom reference
* @param queue that should finalize the referent
*/
protected FinalizablePhantomReference(T referent, FinalizableReferenceQueue queue) {
super(referent, queue.queue);
queue.cleanUp();
}
}
| jakubmalek/guava | guava/src/com/google/common/base/FinalizablePhantomReference.java | Java | apache-2.0 | 1,561 |
package water.runner;
import org.junit.Ignore;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Minimal required cloud size for a JUnit test to run on
*/
@Ignore
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface CloudSize {
int value();
}
| h2oai/h2o-3 | h2o-test-support/src/main/java/water/runner/CloudSize.java | Java | apache-2.0 | 397 |
/*
* Copyright (c) 2011-2015, fortiss GmbH.
* Licensed under the Apache License, Version 2.0.
*
* Use, modification and distribution are subject to the terms specified
* in the accompanying license file LICENSE.txt located at the root directory
* of this software distribution.
*/
package org.fortiss.smg.actuatorclient.hexabus.test;
import java.io.File;
import java.io.InputStream;
import java.util.Dictionary;
import java.util.HashMap;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleException;
import org.osgi.framework.BundleListener;
import org.osgi.framework.Filter;
import org.osgi.framework.FrameworkListener;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceListener;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.ServiceRegistration;
public class FakedBundleContext implements BundleContext {
HashMap<String,String> properties;
public FakedBundleContext(HashMap<String, String> properties) {
this.properties = properties;
}
@Override
public String getProperty(String key) {
return properties.get(key);
}
@Override
public Bundle getBundle() {
// TODO Auto-generated method stub
return null;
}
@Override
public Bundle installBundle(String location, InputStream input)
throws BundleException {
// TODO Auto-generated method stub
return null;
}
@Override
public Bundle installBundle(String location) throws BundleException {
// TODO Auto-generated method stub
return null;
}
@Override
public Bundle getBundle(long id) {
// TODO Auto-generated method stub
return null;
}
@Override
public Bundle[] getBundles() {
// TODO Auto-generated method stub
return null;
}
@Override
public void addServiceListener(ServiceListener listener, String filter)
throws InvalidSyntaxException {
// TODO Auto-generated method stub
}
@Override
public void addServiceListener(ServiceListener listener) {
// TODO Auto-generated method stub
}
@Override
public void removeServiceListener(ServiceListener listener) {
// TODO Auto-generated method stub
}
@Override
public void addBundleListener(BundleListener listener) {
// TODO Auto-generated method stub
}
@Override
public void removeBundleListener(BundleListener listener) {
// TODO Auto-generated method stub
}
@Override
public void addFrameworkListener(FrameworkListener listener) {
// TODO Auto-generated method stub
}
@Override
public void removeFrameworkListener(FrameworkListener listener) {
// TODO Auto-generated method stub
}
@Override
public ServiceRegistration registerService(String[] clazzes,
Object service, Dictionary properties) {
// TODO Auto-generated method stub
return null;
}
@Override
public ServiceRegistration registerService(String clazz, Object service,
Dictionary properties) {
// TODO Auto-generated method stub
return null;
}
@Override
public ServiceReference[] getServiceReferences(String clazz, String filter)
throws InvalidSyntaxException {
// TODO Auto-generated method stub
return null;
}
@Override
public ServiceReference[] getAllServiceReferences(String clazz,
String filter) throws InvalidSyntaxException {
// TODO Auto-generated method stub
return null;
}
@Override
public ServiceReference getServiceReference(String clazz) {
// TODO Auto-generated method stub
return null;
}
@Override
public Object getService(ServiceReference reference) {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean ungetService(ServiceReference reference) {
// TODO Auto-generated method stub
return false;
}
@Override
public File getDataFile(String filename) {
// TODO Auto-generated method stub
return null;
}
@Override
public Filter createFilter(String filter) throws InvalidSyntaxException {
// TODO Auto-generated method stub
return null;
}
}
| B2M-Software/project-drahtlos-smg20 | actuatorclient.ipswitch.test/src/test/java/org/fortiss/smg/actuatorclient/hexabus/test/FakedBundleContext.java | Java | apache-2.0 | 3,958 |
package com.kuxhausen.huemore.persistence;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Color;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.support.annotation.Size;
import com.kuxhausen.huemore.persistence.Definitions.MoodColumns;
import com.kuxhausen.huemore.state.Mood;
import com.kuxhausen.huemore.utils.DeferredLog;
import java.util.Calendar;
public class Utils {
public static
@Nullable
Mood getMoodFromDatabase(String moodName, Context ctx) {
String[] moodColumns = {MoodColumns.COL_MOOD_VALUE};
String[] mWhereClause = {moodName};
Cursor moodCursor =
ctx.getContentResolver().query(Definitions.MoodColumns.MOODS_URI, moodColumns,
MoodColumns.COL_MOOD_NAME + "=?", mWhereClause, null);
if (!moodCursor.moveToFirst()) {
moodCursor.close();
return null;
}
String encodedMood = moodCursor.getString(0);
moodCursor.close();
try {
return HueUrlEncoder.decode(encodedMood).second.first;
} catch (InvalidEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
} catch (FutureEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
/**
* Inspired by https://github.com/PhilipsHue/PhilipsHueSDK-iOS-OSX/blob/master/ApplicationDesignNotes
* /RGB%20to%20xy%20Color%20conversion.md
*
* @param h in 0 to 1 in the wide RGB D65 space
* @param s in 0 to 1 in the wide RGB D65 space
* @return CIE 1931 xy each ranging 0 to 1
*/
public static float[] hsTOxy(float[] input) {
float h = input[0];
float s = input[1];
h = Math.max(0f, Math.min(h, 1f));
s = Math.max(0f, Math.min(s, 1f));
float[] hsv = {h * 360, s, 1};
int rgb = Color.HSVToColor(hsv);
float red = ((rgb >>> 16) & 0xFF) / 255f;
float green = ((rgb >>> 8) & 0xFF) / 255f;
float blue = ((rgb) & 0xFF) / 255f;
red =
(float) ((red > 0.04045f) ? Math.pow((red + 0.055f) / (1.0f + 0.055f), 2.4f)
: (red / 12.92f));
green =
(float) ((green > 0.04045f) ? Math.pow((green + 0.055f) / (1.0f + 0.055f), 2.4f)
: (green / 12.92f));
blue =
(float) ((blue > 0.04045f) ? Math.pow((blue + 0.055f) / (1.0f + 0.055f), 2.4f)
: (blue / 12.92f));
float X = red * 0.649926f + green * 0.103455f + blue * 0.197109f;
float Y = red * 0.234327f + green * 0.743075f + blue * 0.022598f;
float Z = red * 0.0000000f + green * 0.053077f + blue * 1.035763f;
float x = X / (X + Y + Z);
float y = Y / (X + Y + Z);
float[] result = {x, y};
// Log.e("colorspace", "h"+h+" s"+s+" to x"+x+" y"+y);
return result;
}
/**
* Inspired by https://github.com/PhilipsHue/PhilipsHueSDK-iOS-OSX/blob/master/ApplicationDesignNotes
* /RGB%20to%20xy%20Color%20conversion.md
*
* @param x CIE 1931 x ranging from 0 to 1
* @param y CIE 1931 y ranging from 0 to 1
* @return h, s each ranging 0 to 1 in the wide RGB D65 space
*/
public static float[] xyTOhs(float[] input) {
float x = input[0];
float y = input[1];
float z = 1.0f - x - y;
float Y = 1f; // The given brightness value
float X = (Y / y) * x;
float Z = (Y / y) * z;
float r = X * 1.612f - Y * 0.203f - Z * 0.302f;
float g = -X * 0.509f + Y * 1.412f + Z * 0.066f;
float b = X * 0.026f - Y * 0.072f + Z * 0.962f;
r =
(float) (r <= 0.0031308f ? 12.92f * r : (1.0f + 0.055f) * Math.pow(r, (1.0f / 2.4f))
- 0.055f);
g =
(float) (g <= 0.0031308f ? 12.92f * g : (1.0f + 0.055f) * Math.pow(g, (1.0f / 2.4f))
- 0.055f);
b =
(float) (b <= 0.0031308f ? 12.92f * b : (1.0f + 0.055f) * Math.pow(b, (1.0f / 2.4f))
- 0.055f);
float max = Math.max(r, Math.max(g, b));
r = r / max;
g = g / max;
b = b / max;
r = Math.max(r, 0);
g = Math.max(g, 0);
b = Math.max(b, 0);
float[] hsv = new float[3];
Color.RGBToHSV((int) (r * 0xFF), (int) (g * 0xFF), (int) (b * 0xFF), hsv);
float h = hsv[0] / 360;
float s = hsv[1];
h = Math.max(0f, Math.min(h, 1f));
s = Math.max(0f, Math.min(s, 1f));
float[] result = {h, s};
// Log.e("colorspace", "h"+h+" s"+s+" from x"+x+" y"+y);
return result;
}
/**
* @param x CIE 1931 x ranging from 0 to 1
* @param y CIE 1931 y ranging from 0 to 1
* @return h, s each ranging 0 to 1 in the sRGB D65 space
*/
public static float[] xyTOsRGBhs(float[] input) {
float x = input[0];
float y = input[1];
float z = 1.0f - x - y;
float Y = 1f; // The given brightness value
float X = (Y / y) * x;
float Z = (Y / y) * z;
float r = X * 3.2404542f + Y * -1.5371385f + Z * -0.4985314f;
float g = X * -0.9692660f + Y * 1.8760108f + Z * 0.0415560f;
float b = X * 0.0556434f + Y * -0.2040259f + Z * 1.0572252f;
r =
(float) (r <= 0.0031308f ? 12.92f * r : (1.0f + 0.055f) * Math.pow(r, (1.0f / 2.4f))
- 0.055f);
g =
(float) (g <= 0.0031308f ? 12.92f * g : (1.0f + 0.055f) * Math.pow(g, (1.0f / 2.4f))
- 0.055f);
b =
(float) (b <= 0.0031308f ? 12.92f * b : (1.0f + 0.055f) * Math.pow(b, (1.0f / 2.4f))
- 0.055f);
float max = Math.max(r, Math.max(g, b));
r = r / max;
g = g / max;
b = b / max;
r = Math.max(r, 0);
g = Math.max(g, 0);
b = Math.max(b, 0);
float[] hsv = new float[3];
Color.RGBToHSV((int) (r * 0xFF), (int) (g * 0xFF), (int) (b * 0xFF), hsv);
float h = hsv[0] / 360;
float s = hsv[1];
h = Math.max(0f, Math.min(h, 1f));
s = Math.max(0f, Math.min(s, 1f));
float[] result = {h, s};
// Log.e("colorspace", "h"+h+" s"+s+" from x"+x+" y"+y);
return result;
}
/**
* Plankian locus cubic spline approximation by Kim et al inspired by
* http://en.wikipedia.org/wiki/Planckian_locus
*
* @param ct Planckian locus color temperature in Mirads
* @return x, y in CIE 1931 each ranging 0 to 1
*/
public static float[] ctTOxy(float ctMirads) {
double ct = 1000000 / ctMirads;
double xc = 0;
double yc = 0;
if (1667 <= ct && ct <= 4000) {
xc =
-0.2661239 * (Math.pow(10, 9) / Math.pow(ct, 3)) - 0.2343580
* (Math.pow(10, 6) / Math.pow(ct, 2))
+ 0.8776956 * (Math.pow(10, 3) / ct)
+ 0.179910d;
} else if (4000 < ct && ct < 25000) {
xc =
-3.0258469 * (Math.pow(10, 9) / Math.pow(ct, 3)) + 2.1070379
* (Math.pow(10, 6) / Math.pow(ct, 2))
+ 0.2226347 * (Math.pow(10, 3) / ct)
+ 0.240390d;
}
if (1667 <= ct && ct <= 2222) {
yc =
-1.1063814 * Math.pow(xc, 3) - 1.34811020 * Math.pow(xc, 2) + 2.18555832 * xc
- 0.20219683d;
} else if (2222 < ct && ct <= 4000) {
yc =
-0.9549476 * Math.pow(xc, 3) - 1.37418593 * Math.pow(xc, 2) + 2.09137015 * xc
- 0.16748867d;
} else if (4000 < ct && ct <= 25000) {
yc =
3.0817580 * Math.pow(xc, 3) - 5.87338670 * Math.pow(xc, 2) + 3.75112997 * xc
- 0.37001483d;
}
DeferredLog.e("ctConversion", "%f , %f , %f", ct, + xc, yc);
float[] result = {(float) xc, (float) yc};
return result;
}
/**
* @param gamutBounds list of xy coordinates of maximum reachable colors
* @param xy desired coordinates
* @return the desired coordinates, adjusted to be within bounds
*/
public static float[] toReachableXY(@Size(6) float[] gamutBounds, @Size(2) float[] xy) {
//TODO
return xy;
}
/**
* @return deciseconds
*/
public static int toDeciSeconds(long milliseconds) {
return (int) (milliseconds / 100l);
}
/**
* @return milliseconds
*/
public static long fromDeciSeconds(int deciseconds) {
return deciseconds * 100l;
}
public static int moodDailyTimeFromCalendarMillis(Calendar input) {
Calendar startOfDay = Calendar.getInstance();
startOfDay.set(Calendar.MILLISECOND, 0);
startOfDay.set(Calendar.SECOND, 0);
startOfDay.set(Calendar.MINUTE, 0);
startOfDay.set(Calendar.HOUR_OF_DAY, 0);
Calendar inputCopy = Calendar.getInstance();
inputCopy.setTimeInMillis(input.getTimeInMillis());
Long offsetWithinTheDayInMilis = inputCopy.getTimeInMillis() - startOfDay.getTimeInMillis();
return (int) (offsetWithinTheDayInMilis / 100);
}
public static Calendar calendarMillisFromMoodDailyTime(int dailyMoodDeciSeconds) {
Calendar startOfDay = Calendar.getInstance();
startOfDay.set(Calendar.MILLISECOND, 0);
startOfDay.set(Calendar.SECOND, 0);
startOfDay.set(Calendar.MINUTE, 0);
startOfDay.set(Calendar.HOUR_OF_DAY, 0);
startOfDay.getTime();
startOfDay.setTimeInMillis(startOfDay.getTimeInMillis() + (dailyMoodDeciSeconds * 100L));
return startOfDay;
}
/**
* @return the start of day measured in SystemClock.elapsedRealtime milliseconds (may be negative)
*/
public static long getDayStartElapsedRealTimeMillis() {
Calendar dayStart = Calendar.getInstance();
dayStart.set(Calendar.MILLISECOND, 0);
dayStart.set(Calendar.SECOND, 0);
dayStart.set(Calendar.MINUTE, 0);
dayStart.set(Calendar.HOUR_OF_DAY, 0);
dayStart.getTime();
Calendar current = Calendar.getInstance();
return SystemClock.elapsedRealtime() - (current.getTimeInMillis() - dayStart.getTimeInMillis());
}
}
| ekux44/LampShade | mobile/src/main/java/com/kuxhausen/huemore/persistence/Utils.java | Java | apache-2.0 | 9,945 |
/*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* Copyright 2012-2019 the original author or authors.
*/
package org.assertj.core.api.doublepredicate;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.error.ElementsShouldMatch.elementsShouldMatch;
import static org.assertj.core.util.FailureMessages.actualIsNull;
import static org.assertj.core.util.Lists.newArrayList;
import static org.mockito.Mockito.verify;
import java.util.function.DoublePredicate;
import org.assertj.core.api.DoublePredicateAssert;
import org.assertj.core.api.DoublePredicateAssertBaseTest;
import org.assertj.core.presentation.PredicateDescription;
import org.junit.jupiter.api.Test;
/**
* @author Filip Hrisafov
*/
public class DoublePredicateAssert_accepts_Test extends DoublePredicateAssertBaseTest {
@Test
public void should_fail_when_predicate_is_null() {
assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> assertThat((DoublePredicate) null).accepts(1.0, 2.0, 3.0))
.withMessage(actualIsNull());
}
@Test
public void should_fail_when_predicate_does_not_accept_all_values() {
DoublePredicate predicate = val -> val <= 2;
double[] matchValues = new double[] { 1.0, 2.0, 3.0 };
assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> assertThat(predicate).accepts(matchValues))
.withMessage(elementsShouldMatch(matchValues, 3D, PredicateDescription.GIVEN).create());
}
@Test
public void should_pass_when_predicate_accepts_all_values() {
DoublePredicate predicate = val -> val <= 2;
assertThat(predicate).accepts(1.0, 2.0);
}
@Override
protected DoublePredicateAssert invoke_api_method() {
return assertions.accepts(1.0, 2.0);
}
@Override
protected void verify_internal_effects() {
verify(iterables).assertAllMatch(getInfo(assertions), newArrayList(1.0D, 2.0D), wrapped, PredicateDescription.GIVEN);
}
}
| xasx/assertj-core | src/test/java/org/assertj/core/api/doublepredicate/DoublePredicateAssert_accepts_Test.java | Java | apache-2.0 | 2,592 |
/*
* Copyright 2017 MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.bson.json;
class LegacyExtendedJsonDateTimeConverter implements Converter<Long> {
@Override
public void convert(final Long value, final StrictJsonWriter writer) {
writer.writeStartObject();
writer.writeNumber("$date", Long.toString(value));
writer.writeEndObject();
}
}
| jsonking/mongo-java-driver | bson/src/main/org/bson/json/LegacyExtendedJsonDateTimeConverter.java | Java | apache-2.0 | 924 |
package io.demiseq.jetreader.adapters;
import android.app.Activity;
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import java.util.ArrayList;
import io.demiseq.jetreader.R;
import io.demiseq.jetreader.activities.ReadActivity;
import io.demiseq.jetreader.model.Page;
import io.demiseq.jetreader.widget.TouchImageView;
public class FullScreenImageAdapter extends PagerAdapter {
private Activity activity;
private ArrayList<Page> pages;
private LayoutInflater layoutInflater;
public FullScreenImageAdapter(Activity a, ArrayList<Page> p) {
activity = a;
pages = p;
}
@Override
public int getCount() {
return pages.size();
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
TouchImageView imageView;
layoutInflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = layoutInflater.inflate(R.layout.fullscreen_image_slider, container, false);
imageView = (TouchImageView) layout.findViewById(R.id.img);
layout.setTag(position);
imageView.resetZoom();
imageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
((ReadActivity) activity).onClick(view);
}
});
Glide.with(activity.getApplicationContext()).load(pages.get(position).getUrl()).placeholder(R.drawable.page_placeholder)
.error(R.drawable.page_error).listener(new RequestListener<String, GlideDrawable>() {
@Override
public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
return false;
}
@Override
public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
((ReadActivity) activity).updateProgress();
return false;
}
}).into(imageView);
imageView.resetZoom();
container.addView(layout);
return layout;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((LinearLayout) object);
}
}
| haint-fit12/jumpmanga | jetreader/src/main/java/io/demiseq/jetreader/adapters/FullScreenImageAdapter.java | Java | apache-2.0 | 2,825 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.taverna.workbench.file.events;
import org.apache.taverna.scufl2.api.container.WorkflowBundle;
/**
* {@link FileManagerEvent} that means a {@link WorkflowBundle} has been closed.
*
* @author Stian Soiland-Reyes
*/
public class ClosedDataflowEvent extends AbstractDataflowEvent {
public ClosedDataflowEvent(WorkflowBundle workflowBundle) {
super(workflowBundle);
}
}
| apache/incubator-taverna-workbench | taverna-file-api/src/main/java/org/apache/taverna/workbench/file/events/ClosedDataflowEvent.java | Java | apache-2.0 | 1,198 |
/*
* Copyright © 2019 Cask Data, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package io.cdap.wrangler.proto;
import java.net.HttpURLConnection;
/**
* Thrown when there is some conflict
*/
public class ConflictException extends StatusCodeException {
public ConflictException(String message) {
super(message, HttpURLConnection.HTTP_CONFLICT);
}
public ConflictException(String message, Throwable cause) {
super(message, cause, HttpURLConnection.HTTP_CONFLICT);
}
}
| hydrator/wrangler | wrangler-proto/src/main/java/io/cdap/wrangler/proto/ConflictException.java | Java | apache-2.0 | 1,007 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.skywalking.oap.server.core.analysis;
import org.junit.Assert;
import org.junit.Test;
public class IDManagerTest {
@Test
public void testServiceID() {
IDManager.ServiceID.ServiceIDDefinition define = new IDManager.ServiceID.ServiceIDDefinition(
"Service",
true
);
final IDManager.ServiceID.ServiceIDDefinition relationDefine = IDManager.ServiceID.analysisId(
IDManager.ServiceID.buildId(
"Service",
true
));
Assert.assertEquals(define, relationDefine);
}
@Test
public void testServiceRelationID() {
IDManager.ServiceID.ServiceRelationDefine define = new IDManager.ServiceID.ServiceRelationDefine(
IDManager.ServiceID.buildId("ServiceSource", true),
IDManager.ServiceID.buildId("ServiceDest", true)
);
final String relationId = IDManager.ServiceID.buildRelationId(define);
final IDManager.ServiceID.ServiceRelationDefine serviceRelationDefine = IDManager.ServiceID.analysisRelationId(
relationId);
Assert.assertEquals(define, serviceRelationDefine);
}
}
| apache/skywalking | oap-server/server-core/src/test/java/org/apache/skywalking/oap/server/core/analysis/IDManagerTest.java | Java | apache-2.0 | 1,994 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sun.jini.example.hello;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.rmi.Remote;
import java.rmi.server.ExportException;
import java.rmi.server.ServerNotActiveException;
import java.util.Collection;
import javax.swing.JOptionPane;
import net.jini.core.constraint.MethodConstraints;
import net.jini.export.ServerContext;
import net.jini.io.context.ClientHost;
import net.jini.jeri.BasicILFactory;
import net.jini.jeri.BasicInvocationDispatcher;
import net.jini.jeri.InvocationDispatcher;
import net.jini.jeri.ObjectEndpoint;
import net.jini.jeri.ServerCapabilities;
/**
* Defines an <code>InvocationLayerFactory</code> that uses pop-up dialog
* windows to confirm calls.
*
* @author Sun Microsystems, Inc.
*/
public class ConfirmingILFactory extends BasicILFactory {
/**
* Creates a <code>InvocationLayerFactory</code> that confirms calls, with
* no server constraints and no permission class.
*/
public ConfirmingILFactory() { }
/**
* Creates a <code>InvocationLayerFactory</code> that confirms calls, and
* uses the specified server constraints and permission class.
*/
public ConfirmingILFactory(MethodConstraints serverConstraints,
Class permissionClass)
{
super(serverConstraints, permissionClass);
}
/**
* Returns a confirming invocation handler for the object endpoint and
* interfaces.
*
* @param interfaces the interfaces
* @param impl the remote object
* @param oe the object endpoint
* @return a confirming invocation handler for the object endpoint and
* interfaces
*/
protected InvocationHandler createInvocationHandler(Class[] interfaces,
Remote impl,
ObjectEndpoint oe)
{
return new ConfirmingInvocationHandler(oe, getServerConstraints());
}
/**
* Returns a confirming invocation dispatcher for the remote object.
*
* @param methods a collection of {@link Method} instances for the
* remote methods
* @param impl a remote object that the dispatcher is being created for
* @param capabilities the transport capabilities of the server
* @return a confirming invocation dispatcher for the remote object
*/
protected InvocationDispatcher createInvocationDispatcher(
Collection methods, Remote impl, ServerCapabilities capabilities)
throws ExportException
{
if (impl == null) {
throw new NullPointerException("impl is null");
}
return new Dispatch(methods, capabilities, getServerConstraints(),
getPermissionClass());
}
/** Defines a subclass of BasicInvocationDispatcher that confirms calls. */
private static class Dispatch extends BasicInvocationDispatcher {
Dispatch(Collection methods,
ServerCapabilities capabilities,
MethodConstraints serverConstraints,
Class permissionClass)
throws ExportException
{
super(methods, capabilities,
serverConstraints, permissionClass, null);
}
/**
* Reads the call identifier and asks whether the call should be
* permitted before unmarshalling the arguments.
*/
protected Object[] unmarshalArguments(Remote obj,
Method method,
ObjectInputStream in,
Collection context)
throws IOException, ClassNotFoundException
{
long callId = in.readLong();
ClientHost client = null;
try {
client = (ClientHost)
ServerContext.getServerContextElement(ClientHost.class);
} catch (ServerNotActiveException e) {
}
int result = JOptionPane.showConfirmDialog(
null,
"Permit incoming remote call?" +
"\n Client: " + (client != null
? client.toString() : "not active") +
"\n Object: " + obj +
"\n Method: " + method.getName() +
"\n Call id: " + callId,
"Permit incoming remote call?",
JOptionPane.OK_CANCEL_OPTION);
if (result != JOptionPane.OK_OPTION) {
throw new SecurityException("Server denied call");
}
return super.unmarshalArguments(obj, method, in, context);
}
}
}
| MjAbuz/river | src/com/sun/jini/example/hello/ConfirmingILFactory.java | Java | apache-2.0 | 4,933 |
/*
*
* Autopsy Forensic Browser
*
* Copyright 2019-2021 Basis Technology Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.sleuthkit.autopsy.recentactivity;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import java.util.logging.Level;
import org.openide.util.NbBundle.Messages;
import org.sleuthkit.autopsy.coreutils.Logger;
import org.sleuthkit.autopsy.coreutils.NetworkUtils;
import org.sleuthkit.autopsy.ingest.DataSourceIngestModuleProgress;
import org.sleuthkit.autopsy.ingest.IngestJobContext;
import org.sleuthkit.datamodel.AbstractFile;
import org.sleuthkit.datamodel.BlackboardArtifact;
import static org.sleuthkit.datamodel.BlackboardArtifact.ARTIFACT_TYPE.TSK_ASSOCIATED_OBJECT;
import static org.sleuthkit.datamodel.BlackboardArtifact.ARTIFACT_TYPE.TSK_WEB_DOWNLOAD;
import org.sleuthkit.datamodel.BlackboardAttribute;
import static org.sleuthkit.datamodel.BlackboardAttribute.ATTRIBUTE_TYPE.TSK_PATH_ID;
import org.sleuthkit.datamodel.Content;
import org.sleuthkit.datamodel.ReadContentInputStream;
import org.sleuthkit.datamodel.TskCoreException;
/**
* Extract the <i>:Zone.Identifier<i> alternate data stream files. A file with a
* <i>:Zone.Identifier<i> extension contains information about the similarly
* named (with out zone identifier extension) downloaded file.
*/
final class ExtractZoneIdentifier extends Extract {
private static final Logger LOG = Logger.getLogger(ExtractEdge.class.getName());
private static final String ZONE_IDENTIFIER_FILE = "%:Zone.Identifier"; //NON-NLS
private static final String ZONE_IDENTIFIER = ":Zone.Identifier"; //NON-NLS
private Content dataSource;
private final IngestJobContext context;
@Messages({
"ExtractZone_displayName= Zone Identifier Analyzer",
"ExtractZone_process_errMsg_find=A failure occured while searching for :Zone.Indentifier files.",
"ExtractZone_process_errMsg=An error occured processing ':Zone.Indentifier' files.",
"ExtractZone_progress_Msg=Extracting :Zone.Identifer files"
})
ExtractZoneIdentifier(IngestJobContext context) {
super(Bundle.ExtractZone_displayName(), context);
this.context = context;
}
@Override
void process(Content dataSource, DataSourceIngestModuleProgress progressBar) {
this.dataSource = dataSource;
progressBar.progress(Bundle.ExtractZone_progress_Msg());
List<AbstractFile> zoneFiles = null;
try {
zoneFiles = currentCase.getServices().getFileManager().findFiles(dataSource, ZONE_IDENTIFIER_FILE);
} catch (TskCoreException ex) {
addErrorMessage(Bundle.ExtractZone_process_errMsg_find());
LOG.log(Level.SEVERE, "Unable to find zone identifier files, exception thrown. ", ex); // NON-NLS
}
if (zoneFiles == null || zoneFiles.isEmpty()) {
return;
}
Set<Long> knownPathIDs = null;
try {
knownPathIDs = getPathIDsForType(TSK_WEB_DOWNLOAD);
} catch (TskCoreException ex) {
addErrorMessage(Bundle.ExtractZone_process_errMsg());
LOG.log(Level.SEVERE, "Failed to build PathIDs List for TSK_WEB_DOWNLOAD", ex); // NON-NLS
}
if (knownPathIDs == null) {
return;
}
Collection<BlackboardArtifact> associatedObjectArtifacts = new ArrayList<>();
Collection<BlackboardArtifact> downloadArtifacts = new ArrayList<>();
for (AbstractFile zoneFile : zoneFiles) {
if (context.dataSourceIngestIsCancelled()) {
return;
}
try {
processZoneFile(zoneFile, associatedObjectArtifacts, downloadArtifacts, knownPathIDs);
} catch (TskCoreException ex) {
addErrorMessage(Bundle.ExtractZone_process_errMsg());
String message = String.format("Failed to process zone identifier file %s", zoneFile.getName()); //NON-NLS
LOG.log(Level.WARNING, message, ex);
}
}
if (!context.dataSourceIngestIsCancelled()) {
postArtifacts(associatedObjectArtifacts);
postArtifacts(downloadArtifacts);
}
}
/**
* Process a single Zone Identifier file.
*
* @param zoneFile Zone Identifier file
* @param associatedObjectArtifacts List for TSK_ASSOCIATED_OBJECT artifacts
* @param downloadArtifacts List for TSK_WEB_DOWNLOAD artifacts
*
* @throws TskCoreException
*/
private void processZoneFile(
AbstractFile zoneFile, Collection<BlackboardArtifact> associatedObjectArtifacts,
Collection<BlackboardArtifact> downloadArtifacts,
Set<Long> knownPathIDs) throws TskCoreException {
ZoneIdentifierInfo zoneInfo = null;
try {
zoneInfo = new ZoneIdentifierInfo(zoneFile);
} catch (IOException ex) {
String message = String.format("Unable to parse temporary File for %s", zoneFile.getName()); //NON-NLS
LOG.log(Level.WARNING, message, ex);
}
if (zoneInfo == null) {
return;
}
AbstractFile downloadFile = getDownloadFile(zoneFile);
if (downloadFile != null) {
// Only create a new TSK_WEB_DOWNLOAD artifact if one does not exist for downloadFile
if (!knownPathIDs.contains(downloadFile.getId())) {
// The zone identifier file is the parent of this artifact
// because it is the file we parsed to get the data
BlackboardArtifact downloadBba = createDownloadArtifact(zoneFile, zoneInfo, downloadFile);
downloadArtifacts.add(downloadBba);
// create a TSK_ASSOCIATED_OBJECT for the downloaded file, associating it with the TSK_WEB_DOWNLOAD artifact.
if (downloadFile.getArtifactsCount(TSK_ASSOCIATED_OBJECT) == 0) {
associatedObjectArtifacts.add(createAssociatedArtifact(downloadFile, downloadBba));
}
}
}
}
/**
* Find the file that the Zone.Identifier file was created alongside.
*
* @param zoneFile The zone identifier case file
*
* @return The downloaded file or null if a file was not found
*
* @throws TskCoreException
*/
private AbstractFile getDownloadFile(AbstractFile zoneFile) throws TskCoreException {
String downloadFileName = zoneFile.getName().replace(ZONE_IDENTIFIER, ""); //NON-NLS
// The downloaded file should have been added to the database just before the
// Zone.Identifier file, possibly with a slack file in between. We will load those files
// and test them first since loading files by ID will typically be much faster than
// the fallback method of searching by file name.
AbstractFile potentialDownloadFile = currentCase.getSleuthkitCase().getAbstractFileById(zoneFile.getId() - 1);
if (isZoneFileMatch(zoneFile, downloadFileName, potentialDownloadFile)) {
return potentialDownloadFile;
}
potentialDownloadFile = currentCase.getSleuthkitCase().getAbstractFileById(zoneFile.getId() - 2);
if (isZoneFileMatch(zoneFile, downloadFileName, potentialDownloadFile)) {
return potentialDownloadFile;
}
org.sleuthkit.autopsy.casemodule.services.FileManager fileManager = currentCase.getServices().getFileManager();
List<AbstractFile> fileList = fileManager.findFilesExactName(zoneFile.getParent().getId(), downloadFileName);
for (AbstractFile file : fileList) {
if (isZoneFileMatch(zoneFile, downloadFileName, file)) {
return file;
}
}
return null;
}
/**
* Test whether a given zoneFile is associated with another file. Criteria:
* Metadata addresses match Names match Parent paths match
*
* @param zoneFile The zone file.
* @param expectedDownloadFileName The expected name for the downloaded
* file.
* @param possibleDownloadFile The file to test against the zone file.
*
* @return true if possibleDownloadFile corresponds to zoneFile, false
* otherwise.
*/
private boolean isZoneFileMatch(AbstractFile zoneFile, String expectedDownloadFileName, AbstractFile possibleDownloadFile) {
if (zoneFile == null || possibleDownloadFile == null || expectedDownloadFileName == null) {
return false;
}
if (zoneFile.getMetaAddr() != possibleDownloadFile.getMetaAddr()) {
return false;
}
if (!expectedDownloadFileName.equals(possibleDownloadFile.getName())) {
return false;
}
if (!possibleDownloadFile.getParentPath().equals(zoneFile.getParentPath())) {
return false;
}
return true;
}
/**
* Create a TSK_WEB_DOWNLOAD Artifact for the given zone identifier file.
*
* @param zoneFile Zone identifier file
* @param zoneInfo ZoneIdentifierInfo file wrapper object
* @param downloadFile The file associated with the zone identifier
*
* @return BlackboardArifact for the given parameters
*/
private BlackboardArtifact createDownloadArtifact(AbstractFile zoneFile, ZoneIdentifierInfo zoneInfo, AbstractFile downloadFile) throws TskCoreException {
String downloadFilePath = downloadFile.getParentPath() + downloadFile.getName();
long pathID = Util.findID(dataSource, downloadFilePath);
Collection<BlackboardAttribute> bbattributes = createDownloadAttributes(
downloadFilePath, pathID,
zoneInfo.getURL(), null,
(zoneInfo.getURL() != null ? NetworkUtils.extractDomain(zoneInfo.getURL()) : ""),
null);
if (zoneInfo.getZoneIdAsString() != null) {
bbattributes.add(new BlackboardAttribute(BlackboardAttribute.ATTRIBUTE_TYPE.TSK_COMMENT,
RecentActivityExtracterModuleFactory.getModuleName(),
zoneInfo.getZoneIdAsString()));
}
return createArtifactWithAttributes(BlackboardArtifact.Type.TSK_WEB_DOWNLOAD, zoneFile, bbattributes);
}
/**
* Creates a list of PathIDs for the given Artifact type.
*
* @param type BlackboardArtifact.ARTIFACT_TYPE
*
* @return A list of PathIDs
*
* @throws TskCoreException
*/
private Set<Long> getPathIDsForType(BlackboardArtifact.ARTIFACT_TYPE type) throws TskCoreException {
Set<Long> idList = new HashSet<>();
for (BlackboardArtifact artifact : currentCase.getSleuthkitCase().getBlackboardArtifacts(type)) {
BlackboardAttribute pathIDAttribute = artifact.getAttribute(new BlackboardAttribute.Type(TSK_PATH_ID));
if (pathIDAttribute != null) {
long contentID = pathIDAttribute.getValueLong();
if (contentID != -1) {
idList.add(contentID);
}
}
}
return idList;
}
@Messages({
"ExtractZone_Local_Machine=Local Machine Zone",
"ExtractZone_Local_Intranet=Local Intranet Zone",
"ExtractZone_Trusted=Trusted Sites Zone",
"ExtractZone_Internet=Internet Zone",
"ExtractZone_Restricted=Restricted Sites Zone"
})
/**
* Wrapper class for information in the :ZoneIdentifier file. The
* Zone.Identifier file has a simple format of
* \<i\>key\<i\>=\<i\>value\<i\>. There are four known keys: ZoneId,
* ReferrerUrl, HostUrl, and LastWriterPackageFamilyName. Not all browsers
* will put all values in the file, in fact most will only supply the
* ZoneId. Only Edge supplies the LastWriterPackageFamilyName.
*/
private final static class ZoneIdentifierInfo {
private static final String ZONE_ID = "ZoneId"; //NON-NLS
private static final String REFERRER_URL = "ReferrerUrl"; //NON-NLS
private static final String HOST_URL = "HostUrl"; //NON-NLS
private static final String FAMILY_NAME = "LastWriterPackageFamilyName"; //NON-NLS
private static String fileName;
private final Properties properties = new Properties(null);
/**
* Opens the zone file, reading for the key\value pairs and puts them
* into a HashMap.
*
* @param zoneFile The ZoneIdentifier file
*
* @throws FileNotFoundException
* @throws IOException
*/
ZoneIdentifierInfo(AbstractFile zoneFile) throws IOException {
fileName = zoneFile.getName();
// properties.load will throw IllegalArgument if unicode characters are found in the zone file.
try {
properties.load(new ReadContentInputStream(zoneFile));
} catch (IllegalArgumentException ex) {
String message = String.format("Unable to parse Zone Id for File %s", fileName); //NON-NLS
LOG.log(Level.WARNING, message);
}
}
/**
* Get the integer zone id
*
* @return interger zone id or -1 if unknown
*/
private int getZoneId() {
int zoneValue = -1;
String value = properties.getProperty(ZONE_ID);
try {
if (value != null) {
zoneValue = Integer.parseInt(value);
}
} catch (NumberFormatException ex) {
String message = String.format("Unable to parse Zone Id for File %s", fileName); //NON-NLS
LOG.log(Level.WARNING, message);
}
return zoneValue;
}
/**
* Get the string description of the zone id.
*
* @return String description or null if a zone id was not found
*/
private String getZoneIdAsString() {
switch (getZoneId()) {
case 0:
return Bundle.ExtractZone_Local_Machine();
case 1:
return Bundle.ExtractZone_Local_Intranet();
case 2:
return Bundle.ExtractZone_Trusted();
case 3:
return Bundle.ExtractZone_Internet();
case 4:
return Bundle.ExtractZone_Restricted();
default:
return null;
}
}
/**
* Get the URL from which the file was downloaded.
*
* @return String url or null if a host url was not found
*/
private String getURL() {
return properties.getProperty(HOST_URL);
}
/**
* Get the referrer url.
*
* @return String url or null if a host url was not found
*/
private String getReferrer() {
return properties.getProperty(REFERRER_URL);
}
/**
* Gets the string value for the key LastWriterPackageFamilyName.
*
* @return String value or null if the value was not found
*/
private String getFamilyName() {
return properties.getProperty(FAMILY_NAME);
}
}
}
| sleuthkit/autopsy | RecentActivity/src/org/sleuthkit/autopsy/recentactivity/ExtractZoneIdentifier.java | Java | apache-2.0 | 16,071 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.imaging.common.bytesource;
import org.apache.commons.imaging.ImageFormat;
import org.apache.commons.imaging.ImageFormats;
import org.apache.commons.imaging.ImageInfo;
import org.apache.commons.imaging.ImageParser;
import org.apache.commons.imaging.ImageReadException;
import org.apache.commons.imaging.Imaging;
import org.apache.commons.imaging.ImagingParameters;
import org.apache.commons.imaging.formats.jpeg.JpegImagingParameters;
import org.apache.commons.imaging.formats.tiff.TiffImagingParameters;
import org.apache.commons.imaging.internal.Debug;
import org.apache.commons.imaging.internal.Util;
import org.apache.commons.io.FileUtils;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import java.awt.Dimension;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNotSame;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class ByteSourceImageTest extends ByteSourceTest {
public static Stream<File> data() throws Exception {
return getTestImages().stream();
}
@ParameterizedTest
@MethodSource("data")
public void test(final File imageFile) throws Exception {
Debug.debug("imageFile", imageFile);
assertNotNull(imageFile);
final byte[] imageFileBytes = FileUtils.readFileToByteArray(imageFile);
assertNotNull(imageFileBytes);
assertEquals(imageFileBytes.length, imageFile.length());
if (imageFile.getName().toLowerCase().endsWith(".ico")
|| imageFile.getName().toLowerCase().endsWith(".tga")
|| imageFile.getName().toLowerCase().endsWith(".jb2")
|| imageFile.getName().toLowerCase().endsWith(".pcx")
|| imageFile.getName().toLowerCase().endsWith(".dcx")
|| imageFile.getName().toLowerCase().endsWith(".psd")
|| imageFile.getName().toLowerCase().endsWith(".wbmp")
|| imageFile.getName().toLowerCase().endsWith(".xbm")
|| imageFile.getName().toLowerCase().endsWith(".xpm")) {
// these formats can't be parsed without a file name hint.
// they have ambiguous "magic number" signatures.
return;
}
checkGuessFormat(imageFile, imageFileBytes);
if (imageFile.getName().toLowerCase().endsWith(".png")
&& imageFile.getParentFile().getName().equalsIgnoreCase("pngsuite")
&& imageFile.getName().toLowerCase().startsWith("x")) {
return;
}
checkGetICCProfileBytes(imageFile, imageFileBytes);
if (!imageFile.getParentFile().getName().toLowerCase().equals("@broken")) {
checkGetImageInfo(imageFile, imageFileBytes);
}
checkGetImageSize(imageFile, imageFileBytes);
final ImageFormat imageFormat = Imaging.guessFormat(imageFile);
if (ImageFormats.JPEG != imageFormat
&& ImageFormats.UNKNOWN != imageFormat) {
checkGetBufferedImage(imageFile, imageFileBytes);
}
}
public void checkGetBufferedImage(final File file, final byte[] bytes) throws Exception {
final BufferedImage bufferedImage = Imaging.getBufferedImage(file);
assertNotNull(bufferedImage);
assertTrue(bufferedImage.getWidth() > 0);
assertTrue(bufferedImage.getHeight() > 0);
final int imageFileWidth = bufferedImage.getWidth();
final int imageFileHeight = bufferedImage.getHeight();
final BufferedImage imageBytes = Imaging.getBufferedImage(bytes);
assertNotNull(imageBytes);
assertEquals(imageFileWidth, imageBytes.getWidth());
assertEquals(imageFileHeight, imageBytes.getHeight());
}
public void checkGetImageSize(final File imageFile, final byte[] imageFileBytes)
throws Exception {
final Dimension imageSizeFile = Imaging.getImageSize(imageFile);
assertNotNull(imageSizeFile);
assertTrue(imageSizeFile.width > 0);
assertTrue(imageSizeFile.height > 0);
final Dimension imageSizeBytes = Imaging.getImageSize(imageFileBytes);
assertNotNull(imageSizeBytes);
assertEquals(imageSizeFile.width, imageSizeBytes.width);
assertEquals(imageSizeFile.height, imageSizeBytes.height);
}
public void checkGuessFormat(final File imageFile, final byte[] imageFileBytes)
throws Exception {
// check guessFormat()
final ImageFormat imageFormatFile = Imaging.guessFormat(imageFile);
assertNotNull(imageFormatFile);
assertNotSame(imageFormatFile, ImageFormats.UNKNOWN);
// Debug.debug("imageFormatFile", imageFormatFile);
final ImageFormat imageFormatBytes = Imaging.guessFormat(imageFileBytes);
assertNotNull(imageFormatBytes);
assertNotSame(imageFormatBytes, ImageFormats.UNKNOWN);
// Debug.debug("imageFormatBytes", imageFormatBytes);
assertSame(imageFormatBytes, imageFormatFile);
}
public void checkGetICCProfileBytes(final File imageFile, final byte[] imageFileBytes)
throws Exception {
// check guessFormat()
final byte[] iccBytesFile = Imaging.getICCProfileBytes(imageFile);
final byte[] iccBytesBytes = Imaging.getICCProfileBytes(imageFileBytes);
assertEquals((iccBytesFile != null), (iccBytesBytes != null));
if (iccBytesFile == null) {
return;
}
assertArrayEquals(iccBytesFile, iccBytesBytes);
}
public void checkGetImageInfo(final File imageFile, final byte[] imageFileBytes) throws IOException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, ImageReadException {
final boolean ignoreImageData = isPhilHarveyTestImage(imageFile);
final ImageFormat imageFormat = Imaging.guessFormat(imageFile);
ImagingParameters params = null;
if (imageFormat == ImageFormats.TIFF) {
params = new TiffImagingParameters();
((TiffImagingParameters) params).setReadThumbnails(!ignoreImageData);
}
if (imageFormat == ImageFormats.JPEG) {
params = new JpegImagingParameters();
}
ImageParser imageParser = Util.getImageParser(imageFormat);
final ImageInfo imageInfoFile = imageParser.getImageInfo(imageFile, params);
final ImageInfo imageInfoBytes = imageParser.getImageInfo(imageFileBytes, params);
assertNotNull(imageInfoFile);
assertNotNull(imageInfoBytes);
final Method[] methods = ImageInfo.class.getMethods();
for (final Method method2 : methods) {
if (!Modifier.isPublic(method2.getModifiers())) {
continue;
}
if (!method2.getName().startsWith("get")) {
continue;
}
if (method2.getName().equals("getClass"))
{
continue;
// if (method.getGenericParameterTypes().length > 0)
// continue;
}
final Object valueFile = method2.invoke(imageInfoFile, (Object[])null);
final Object valueBytes = method2.invoke(imageInfoBytes, (Object[])null);
assertEquals(valueFile, valueBytes);
}
// only have to test values from imageInfoFile; we already know values
// match.
assertTrue(imageInfoFile.getBitsPerPixel() > 0);
assertNotNull(imageInfoFile.getFormat());
assertNotSame(imageInfoFile.getFormat(), ImageFormats.UNKNOWN);
assertNotNull(imageInfoFile.getFormatName());
assertTrue(imageInfoFile.getWidth() > 0);
assertTrue(imageInfoFile.getHeight() > 0);
assertNotNull(imageInfoFile.getMimeType());
// TODO: not all adapters count images yet.
// assertTrue(imageInfoFile.getNumberOfImages() > 0);
}
}
| apache/commons-imaging | src/test/java/org/apache/commons/imaging/common/bytesource/ByteSourceImageTest.java | Java | apache-2.0 | 9,199 |
/*
* Copyright (C) 2010 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.ovirt.mobile.movirt.camera;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.BatteryManager;
import android.util.Log;
/**
* Finishes an activity after a period of inactivity if the device is on battery power.
*/
final public class InactivityTimer {
private static final String TAG = InactivityTimer.class.getSimpleName();
private static final long INACTIVITY_DELAY_MS = 5 * 60 * 1000L;
private final Activity activity;
private final BroadcastReceiver powerStatusReceiver;
private boolean registered;
private AsyncTask<Object, Object, Object> inactivityTask;
public InactivityTimer(Activity activity) {
this.activity = activity;
powerStatusReceiver = new PowerStatusReceiver();
registered = false;
onActivity();
}
public synchronized void onActivity() {
cancel();
inactivityTask = new InactivityAsyncTask();
inactivityTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
public synchronized void onPause() {
cancel();
if (registered) {
activity.unregisterReceiver(powerStatusReceiver);
registered = false;
} else {
Log.w(TAG, "PowerStatusReceiver was never registered?");
}
}
public synchronized void onResume() {
if (registered) {
Log.w(TAG, "PowerStatusReceiver was already registered?");
} else {
activity.registerReceiver(powerStatusReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
registered = true;
}
onActivity();
}
private synchronized void cancel() {
AsyncTask<?, ?, ?> task = inactivityTask;
if (task != null) {
task.cancel(true);
inactivityTask = null;
}
}
public void shutdown() {
cancel();
}
private final class PowerStatusReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (Intent.ACTION_BATTERY_CHANGED.equals(intent.getAction())) {
// 0 indicates that we're on battery
boolean onBatteryNow = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1) <= 0;
if (onBatteryNow) {
InactivityTimer.this.onActivity();
} else {
InactivityTimer.this.cancel();
}
}
}
}
private final class InactivityAsyncTask extends AsyncTask<Object, Object, Object> {
@Override
protected Object doInBackground(Object... objects) {
try {
Thread.sleep(INACTIVITY_DELAY_MS);
Log.i(TAG, "Finishing activity due to inactivity");
activity.finish();
} catch (InterruptedException e) {
// continue without killing
}
return null;
}
}
}
| nextLane/moVirt | moVirt/src/main/java/org/ovirt/mobile/movirt/camera/InactivityTimer.java | Java | apache-2.0 | 3,723 |
package org.jboss.resteasy.test.nextgen.wadl.resources.locator;
import javax.ws.rs.Path;
/**
* @author <a href="mailto:[email protected]">Weinan Li</a>
*/
@Path("/parent")
public class Parent {
@Path("/child")
public Child child() {
return new Child();
}
}
| psakar/Resteasy | resteasy-jaxrs-testsuite/src/test/java/org/jboss/resteasy/test/nextgen/wadl/resources/locator/Parent.java | Java | apache-2.0 | 282 |
/*
* XSD Validator.
*
* Copyright 2013 Adrian Mouat
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package xsdvalidator;
import java.io.File;
import java.io.IOException;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
public class validate {
//This should really come from the script or arg
private final static String PROGRAM_NAME = "xsdv";
// Would rather this was autogenerated
private final static String VERSION = "1.1";
private final static int VALIDATION_FAIL = 1;
private final static int ERROR_READING_SCHEMA = 2;
private final static int ERROR_READING_XML = 3;
private static String mXSDFileName;
private static String mXMLFileName;
/**
* @param args
*/
public static void main(String[] args) {
parseArgs(args);
SchemaFactory factory = SchemaFactory.newInstance(
"http://www.w3.org/2001/XMLSchema");
File XSDFile = new File(mXSDFileName);
File XMLFile = new File(mXMLFileName);
try {
Schema schema = factory.newSchema(XSDFile);
Validator validator = schema.newValidator();
Source source = new StreamSource(XMLFile);
try {
validator.validate(source);
System.out.println(mXMLFileName + " validates");
}
catch (SAXParseException ex) {
System.out.println(mXMLFileName + " fails to validate because: \n");
System.out.println(ex.getMessage());
System.out.println("At: " + ex.getLineNumber()
+ ":" + ex.getColumnNumber());
System.out.println();
System.exit(VALIDATION_FAIL);
}
catch (SAXException ex) {
System.out.println(mXMLFileName + " fails to validate because: \n");
System.out.println(ex.getMessage());
System.out.println();
System.exit(VALIDATION_FAIL);
}
catch (IOException io) {
System.err.println("Error reading XML source: " + mXMLFileName);
System.err.println(io.getMessage());
System.exit(ERROR_READING_XML);
}
} catch (SAXException sch) {
System.err.println("Error reading XML Schema: " + mXSDFileName);
System.err.println(sch.getMessage());
System.exit(ERROR_READING_SCHEMA);
}
}
/**
* Checks and interprets the command line arguments.
*
* Code is based on Sun standard code for handling arguments.
*
* @param args An array of the command line arguments
*/
private static void parseArgs(final String[] args) {
int argNo = 0;
String currentArg;
char flag;
while (argNo < args.length && args[argNo].startsWith("-")) {
currentArg = args[argNo++];
//"wordy" arguments
if (currentArg.equals("--version")) {
printVersionAndExit();
} else if (currentArg.equals("--help")) {
printHelpAndExit();
} else {
//(series of) flag arguments
for (int charNo = 1; charNo < currentArg.length(); charNo++) {
flag = currentArg.charAt(charNo);
switch (flag) {
case 'V':
printVersionAndExit();
break;
case 'h':
printHelpAndExit();
break;
default:
System.err.println("Illegal option " + flag);
printUsageAndExit();
break;
}
}
}
}
if ((argNo + 2) != args.length) {
//Not given 2 files on input
printUsageAndExit();
}
mXSDFileName = args[argNo];
mXMLFileName = args[++argNo];
}
/**
* Outputs usage message to standard error.
*/
public static void printUsageAndExit() {
System.err.println(
"Usage: " + PROGRAM_NAME + " [OPTION]... XSDFILE XMLFILE");
System.exit(2); //2 indicates incorrect usage
}
public static void printHelpAndExit() {
System.out.print(
"\nUsage: " + PROGRAM_NAME + " [OPTION]... XSDFILE XMLFILE\n\n " +
"Validates the XML document at XMLFILE against the XML Schema at" +
" XSDFILE.\n\n" +
"--version -V Output version number.\n" +
"--help -h Output this help.\n");
System.exit(0);
}
/**
* Outputs the current version of diffxml to standard out.
*/
public static void printVersionAndExit() {
System.out.println(PROGRAM_NAME + " Version " + VERSION + "\n");
System.exit(0);
}
}
| kit-data-manager/base | src/resources/metadata/schema/dataorganization/test/validator/src/xsdvalidator/validate.java | Java | apache-2.0 | 5,827 |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.lucene.gdata.gom;
/**
* Atom e.g. feed element can contain text, html and xhtml content as character
* values
*
* @author Simon Willnauer
*
*/
public enum ContentType {
/**
* GOM content type text
*/
TEXT,
/**
* GOM content type XHTML
*/
XHTML,
/**
* GOM content type HTML
*/
HTML,
/**
* GOM atom media type
* @see AtomMediaType
*/
ATOM_MEDIA_TYPE
}
| adichad/lucene-new | contrib/gdata-server/src/gom/src/java/org/apache/lucene/gdata/gom/ContentType.java | Java | apache-2.0 | 1,208 |
package ca.uhn.fhir.rest.server.interceptor;
/*
* #%L
* HAPI FHIR - Core Library
* %%
* Copyright (C) 2014 - 2015 University Health Network
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map.Entry;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;
import org.apache.commons.lang3.text.StrLookup;
import org.apache.commons.lang3.text.StrSubstitutor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ca.uhn.fhir.rest.method.RequestDetails;
import ca.uhn.fhir.rest.server.EncodingEnum;
import ca.uhn.fhir.rest.server.RestfulServerUtils;
import ca.uhn.fhir.rest.server.exceptions.AuthenticationException;
/**
* Server interceptor which logs each request using a defined format
* <p>
* The following substitution variables are supported:
* </p>
* <table summary="Substitution variables supported by this class">
* <tr>
* <td>${id}</td>
* <td>The resource ID associated with this request (or "" if none)</td>
* </tr>
* <tr>
* <td>${idOrResourceName}</td>
* <td>The resource ID associated with this request, or the resource name if the request applies to a type but not an instance, or "" otherwise</td>
* </tr>
* <tr>
* <td>${operationName}</td>
* <td>If the request is an extended operation (e.g. "$validate") this value will be the operation name, or "" otherwise</td>
* </tr>
* <tr>
* <td>${operationType}</td>
* <td>A code indicating the operation type for this request, e.g. "read", "history-instance", "extended-operation-instance", etc.)</td>
* </tr>
* <tr>
* <td>${remoteAddr}</td>
* <td>The originaring IP of the request</td>
* </tr>
* <tr>
* <td>${requestHeader.XXXX}</td>
* <td>The value of the HTTP request header named XXXX. For example, a substitution variable named
* "${requestHeader.x-forwarded-for} will yield the value of the first header named "x-forwarded-for", or "" if none.</td>
* </tr>
* <tr>
* <td>${requestParameters}</td>
* <td>The HTTP request parameters (or "")</td>
* </tr>
* <tr>
* <td>${responseEncodingNoDefault}</td>
* <td>The encoding format requested by the client via the _format parameter or the Accept header. Value will be "json" or "xml", or "" if the client did not explicitly request a format</td>
* </tr>
* <tr>
* <td>${servletPath}</td>
* <td>The part of thre requesting URL that corresponds to the particular Servlet being called (see {@link HttpServletRequest#getServletPath()})</td>
* </tr>
* </table>
*/
public class LoggingInterceptor extends InterceptorAdapter {
private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(LoggingInterceptor.class);
private Logger myLogger = ourLog;
private String myMessageFormat = "${operationType} - ${idOrResourceName}";
@Override
public boolean incomingRequestPostProcessed(final RequestDetails theRequestDetails, final HttpServletRequest theRequest, HttpServletResponse theResponse) throws AuthenticationException {
// Perform any string substitutions from the message format
StrLookup<?> lookup = new MyLookup(theRequest, theRequestDetails);
StrSubstitutor subs = new StrSubstitutor(lookup, "${", "}", '\\');
// Actuall log the line
String line = subs.replace(myMessageFormat);
myLogger.info(line);
return true;
}
public void setLogger(Logger theLogger) {
Validate.notNull(theLogger, "Logger can not be null");
myLogger = theLogger;
}
public void setLoggerName(String theLoggerName) {
Validate.notBlank(theLoggerName, "Logger name can not be null/empty");
myLogger = LoggerFactory.getLogger(theLoggerName);
}
/**
* Sets the message format itself. See the {@link LoggingInterceptor class documentation} for information on the format
*/
public void setMessageFormat(String theMessageFormat) {
Validate.notBlank(theMessageFormat, "Message format can not be null/empty");
myMessageFormat = theMessageFormat;
}
private static final class MyLookup extends StrLookup<String> {
private final HttpServletRequest myRequest;
private final RequestDetails myRequestDetails;
private MyLookup(HttpServletRequest theRequest, RequestDetails theRequestDetails) {
myRequest = theRequest;
myRequestDetails = theRequestDetails;
}
@Override
public String lookup(String theKey) {
/*
* TODO: this method could be made more efficient through some sort of lookup map
*/
if ("operationType".equals(theKey)) {
if (myRequestDetails.getResourceOperationType() != null) {
return myRequestDetails.getResourceOperationType().getCode();
}
if (myRequestDetails.getSystemOperationType() != null) {
return myRequestDetails.getSystemOperationType().getCode();
}
if (myRequestDetails.getOtherOperationType() != null) {
return myRequestDetails.getOtherOperationType().getCode();
}
return "";
} else if ("operationName".equals(theKey)) {
if (myRequestDetails.getOtherOperationType() != null) {
switch (myRequestDetails.getOtherOperationType()) {
case EXTENDED_OPERATION_INSTANCE:
case EXTENDED_OPERATION_SERVER:
case EXTENDED_OPERATION_TYPE:
return myRequestDetails.getOperation();
default:
return "";
}
} else {
return "";
}
} else if ("id".equals(theKey)) {
if (myRequestDetails.getId() != null) {
return myRequestDetails.getId().getValue();
}
return "";
} else if ("servletPath".equals(theKey)) {
return StringUtils.defaultString(myRequest.getServletPath());
} else if ("idOrResourceName".equals(theKey)) {
if (myRequestDetails.getId() != null) {
return myRequestDetails.getId().getValue();
}
if (myRequestDetails.getResourceName() != null) {
return myRequestDetails.getResourceName();
}
return "";
} else if (theKey.equals("requestParameters")) {
StringBuilder b = new StringBuilder();
for (Entry<String, String[]> next : myRequestDetails.getParameters().entrySet()) {
for (String nextValue : next.getValue()) {
if (b.length() == 0) {
b.append('?');
} else {
b.append('&');
}
try {
b.append(URLEncoder.encode(next.getKey(), "UTF-8"));
b.append('=');
b.append(URLEncoder.encode(nextValue, "UTF-8"));
} catch (UnsupportedEncodingException e) {
throw new ca.uhn.fhir.context.ConfigurationException("UTF-8 not supported", e);
}
}
}
return b.toString();
} else if (theKey.startsWith("requestHeader.")) {
String val = myRequest.getHeader(theKey.substring("requestHeader.".length()));
return StringUtils.defaultString(val);
} else if (theKey.startsWith("remoteAddr")) {
return StringUtils.defaultString(myRequest.getRemoteAddr());
} else if (theKey.equals("responseEncodingNoDefault")) {
EncodingEnum encoding = RestfulServerUtils.determineResponseEncodingNoDefault(myRequest);
if (encoding != null) {
return encoding.name();
} else {
return "";
}
}
return "!VAL!";
}
}
}
| lcamilo15/hapi-fhir | hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/server/interceptor/LoggingInterceptor.java | Java | apache-2.0 | 7,674 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.