code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
require "kontena/cli/services/link_command" describe Kontena::Cli::Services::LinkCommand do include ClientHelpers describe '#execute' do it 'aborts if service is already linked' do expect(client).to receive(:get).with('services/test-grid/null/service-a').and_return({ 'links' => [ {'alias' => 'service-b', 'id' => "grid/null/service-b"} ] }) expect { subject.run(['service-a', 'service-b']) }.to exit_with_error end it 'sends link to master' do expect(client).to receive(:get).with('services/test-grid/null/service-a').and_return({ 'links' => [] }) expect(client).to receive(:put).with( 'services/test-grid/null/service-a', {links: [{name: 'null/service-b', alias: 'service-b'}]} ) subject.run(['service-a', 'service-b']) end end end
mikkopiu/kontena
cli/spec/kontena/cli/services/link_command_spec.rb
Ruby
apache-2.0
864
/** * Copyright 2017 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; namespace ApiAiSDK.Util { public static class ActionExtensions { public static void InvokeSafely(this Action action) { if (action != null) { action(); } } public static void InvokeSafely<T>(this Action<T> action, T arg) { if (action != null) { action(arg); } } } }
dialogflow/dialogflow-dotnet-client
ApiAiSDK/Util/ActionExtensions.cs
C#
apache-2.0
1,068
<?php /* * Copyright 2014 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ namespace Google\Service\Compute; class FirewallListWarning extends \Google\Collection { protected $collection_key = 'data'; /** * @var string */ public $code; protected $dataType = FirewallListWarningData::class; protected $dataDataType = 'array'; /** * @var string */ public $message; /** * @param string */ public function setCode($code) { $this->code = $code; } /** * @return string */ public function getCode() { return $this->code; } /** * @param FirewallListWarningData[] */ public function setData($data) { $this->data = $data; } /** * @return FirewallListWarningData[] */ public function getData() { return $this->data; } /** * @param string */ public function setMessage($message) { $this->message = $message; } /** * @return string */ public function getMessage() { return $this->message; } } // Adding a class alias for backwards compatibility with the previous class name. class_alias(FirewallListWarning::class, 'Google_Service_Compute_FirewallListWarning');
googleapis/google-api-php-client-services
src/Compute/FirewallListWarning.php
PHP
apache-2.0
1,708
package edu.pdx.cs410J.dmitriev; import edu.pdx.cs410J.AirlineParser; import edu.pdx.cs410J.ParserException; import javax.imageio.IIOException; import java.io.*; /** * TextParser get the name of the file along with the name of the Airline being read. * It supposed to correctly read the data about the Airline on a specific file along with the flights. * It should also check that flights data is correct by using the same method that were used to check * program line arguments. * If the file does not exist, the class should create it with an empty Airline being added * It also handles IO and Parser exceptions */ public class TextParser implements AirlineParser<Airline> { private String fileName; private String airlineToRead; /** * Constructor for TextParser * @param newName * the name of the file being read/ created with empty Airline * @param newAirlineToRead * the name of Airline to read/ add to an empty file */ TextParser(String newName, String newAirlineToRead) { this.fileName = newName; this.airlineToRead = newAirlineToRead; } /** * call the readFile() method which will give the complete Airline object. * The method catches IOException and then throws ParserException with an * error message, if anything wrong with IO * @return * the airline with a given name and/or flights * @throws ParserException */ @Override public Airline parse() throws ParserException { //Read text file to object Airline Airline airline = null; try { if(checkFileExistence()) airline = readFile(); else airline = createNewFile(); } catch (IOException e) { throw new ParserException("Error while parsing the Airline: "+ e.getMessage()); } return airline; } /** * Check that the file exists * @return * true if exists, false otherwise */ private boolean checkFileExistence() { File f = new File(fileName); if (f.exists()) return true; else return false; } /** * Create a new file with an Airline added * @return * an airline being added * @throws IOException * if IO error found */ private Airline createNewFile() throws IOException { Writer writer = new BufferedWriter(new FileWriter(new File(fileName))); writer.write(airlineToRead+"\n"); Airline airline = new Airline(airlineToRead); writer.close(); return airline; } /** * read the file with given name, create Airline object and add all of the * Flight objects found in file * @return * Airline with flights from file * @throws IOException * IF anny IO/Parsing error found */ private Airline readFile() throws IOException { Airline returnAirline = null; boolean resultCheck; //File f = new File("src\\main\\java\\edu\\pdx\\cs410J\\dmitriev\\"+fileName+".txt"); File f = new File(fileName); if (!f.exists()) { throw new IOException("File not found"); } BufferedReader b = new BufferedReader(new FileReader(f)); String readLine = ""; String fileAirlineName = b.readLine(); if(!airlineToRead.equals(fileAirlineName)) { b.close(); System.gc(); throw new IOException("The name of the airline you looking for does not match the airline found in the file"); } Airline airline = new Airline(fileAirlineName); while ((readLine = b.readLine()) != null) { String[] split = readLine.split(";|\n"); resultCheck = checkFlightArguments(split); if(!resultCheck) { b.close(); System.gc(); throw new IOException("Unable to parse one of the flights, malformated data"); } Flight newFlight = new Flight(split[0], split[1], split[2], split[3], split[4], split[5], split[6], split[7], split[8]); airline.addFlight(newFlight); readLine = null; } b.close(); System.gc(); returnAirline = airline; return returnAirline; } /** * Use ArgumentChecker methods to make sure flights data is formatted correctly. * Jsut as with program line arguments * @param array * a list of flight data * @return * true if passes. False if fails. */ private boolean checkFlightArguments(String[] array) { if (!ArgumentChecker.checkFlightNumber(array[0]) || !ArgumentChecker.checkSrc(array[1]) || !ArgumentChecker.checkDate(array[2]) || !ArgumentChecker.checkTime(array[3]) || !ArgumentChecker.check_am_pm(array[4]) || !ArgumentChecker.checkDest(array[5]) || !ArgumentChecker.checkDate(array[6]) || !ArgumentChecker.checkTime(array[7]) || !ArgumentChecker.check_am_pm(array[8]) || !ArgumentChecker.checkNoOtherArgs(array,0)) { return false; } else return true; } }
alexander94dmitriev/PortlandStateJavaSummer2017
airline/src/main/java/edu/pdx/cs410J/dmitriev/TextParser.java
Java
apache-2.0
5,551
/* * JBoss, Home of Professional Open Source * Copyright 2011 Red Hat Inc. and/or its affiliates and other contributors * as indicated by the @authors tag. All rights reserved. * See the copyright.txt in the distribution for a * full listing of individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.arquillian.integration.persistence.datasource.postgresql; import org.jboss.arquillian.container.test.spi.client.deployment.AuxiliaryArchiveAppender; import org.jboss.arquillian.core.spi.LoadableExtension; public class PostgreSqlDataSourceExtension implements LoadableExtension { @Override public void register(ExtensionBuilder builder) { builder.service(AuxiliaryArchiveAppender.class, PostgreSqlDataSourceArchiveCreator.class); builder.service(AuxiliaryArchiveAppender.class, PostgreSqlDriverArchiveAppender.class); } }
arquillian/arquillian-extension-persistence
int-tests/src/test/java/org/jboss/arquillian/integration/persistence/datasource/postgresql/PostgreSqlDataSourceExtension.java
Java
apache-2.0
1,398
<?php /* * Copyright 2014 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ namespace Google\Service\SQLAdmin; class BackupConfiguration extends \Google\Model { protected $backupRetentionSettingsType = BackupRetentionSettings::class; protected $backupRetentionSettingsDataType = ''; /** * @var bool */ public $binaryLogEnabled; /** * @var bool */ public $enabled; /** * @var string */ public $kind; /** * @var string */ public $location; /** * @var bool */ public $pointInTimeRecoveryEnabled; /** * @var bool */ public $replicationLogArchivingEnabled; /** * @var string */ public $startTime; /** * @var int */ public $transactionLogRetentionDays; /** * @param BackupRetentionSettings */ public function setBackupRetentionSettings(BackupRetentionSettings $backupRetentionSettings) { $this->backupRetentionSettings = $backupRetentionSettings; } /** * @return BackupRetentionSettings */ public function getBackupRetentionSettings() { return $this->backupRetentionSettings; } /** * @param bool */ public function setBinaryLogEnabled($binaryLogEnabled) { $this->binaryLogEnabled = $binaryLogEnabled; } /** * @return bool */ public function getBinaryLogEnabled() { return $this->binaryLogEnabled; } /** * @param bool */ public function setEnabled($enabled) { $this->enabled = $enabled; } /** * @return bool */ public function getEnabled() { return $this->enabled; } /** * @param string */ public function setKind($kind) { $this->kind = $kind; } /** * @return string */ public function getKind() { return $this->kind; } /** * @param string */ public function setLocation($location) { $this->location = $location; } /** * @return string */ public function getLocation() { return $this->location; } /** * @param bool */ public function setPointInTimeRecoveryEnabled($pointInTimeRecoveryEnabled) { $this->pointInTimeRecoveryEnabled = $pointInTimeRecoveryEnabled; } /** * @return bool */ public function getPointInTimeRecoveryEnabled() { return $this->pointInTimeRecoveryEnabled; } /** * @param bool */ public function setReplicationLogArchivingEnabled($replicationLogArchivingEnabled) { $this->replicationLogArchivingEnabled = $replicationLogArchivingEnabled; } /** * @return bool */ public function getReplicationLogArchivingEnabled() { return $this->replicationLogArchivingEnabled; } /** * @param string */ public function setStartTime($startTime) { $this->startTime = $startTime; } /** * @return string */ public function getStartTime() { return $this->startTime; } /** * @param int */ public function setTransactionLogRetentionDays($transactionLogRetentionDays) { $this->transactionLogRetentionDays = $transactionLogRetentionDays; } /** * @return int */ public function getTransactionLogRetentionDays() { return $this->transactionLogRetentionDays; } } // Adding a class alias for backwards compatibility with the previous class name. class_alias(BackupConfiguration::class, 'Google_Service_SQLAdmin_BackupConfiguration');
googleapis/google-api-php-client-services
src/SQLAdmin/BackupConfiguration.php
PHP
apache-2.0
3,849
/* * Copyright 2019 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.server.newsecurity.controllers; import com.thoughtworks.go.server.newsecurity.models.AccessToken; import com.thoughtworks.go.server.newsecurity.models.AuthenticationToken; import com.thoughtworks.go.server.newsecurity.models.UsernamePassword; import com.thoughtworks.go.server.newsecurity.providers.PasswordBasedPluginAuthenticationProvider; import com.thoughtworks.go.server.newsecurity.providers.WebBasedPluginAuthenticationProvider; import com.thoughtworks.go.server.newsecurity.utils.SessionUtils; import com.thoughtworks.go.server.service.SecurityService; import com.thoughtworks.go.util.Clock; import com.thoughtworks.go.util.SystemEnvironment; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.savedrequest.SavedRequest; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.view.RedirectView; import javax.servlet.http.HttpServletRequest; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import static com.thoughtworks.go.server.newsecurity.utils.SessionUtils.isAnonymousAuthenticationToken; @Controller public class AuthenticationController { public static final String BAD_CREDENTIALS_MSG = "Invalid credentials. Either your username and password are incorrect, or there is a problem with your browser cookies. Please check with your administrator."; private static final Logger LOGGER = LoggerFactory.getLogger(AuthenticationController.class); private static final RedirectView REDIRECT_TO_LOGIN_PAGE = new RedirectView("/auth/login", true); private static final String UNKNOWN_ERROR_WHILE_AUTHENTICATION = "There was an unknown error authenticating you. Please try again after some time, and contact the administrator if the problem persists."; private final SecurityService securityService; private final SystemEnvironment systemEnvironment; private final Clock clock; private final PasswordBasedPluginAuthenticationProvider passwordBasedPluginAuthenticationProvider; private final WebBasedPluginAuthenticationProvider webBasedPluginAuthenticationProvider; @Autowired public AuthenticationController(SecurityService securityService, SystemEnvironment systemEnvironment, Clock clock, PasswordBasedPluginAuthenticationProvider passwordBasedPluginAuthenticationProvider, WebBasedPluginAuthenticationProvider webBasedPluginAuthenticationProvider) { this.securityService = securityService; this.systemEnvironment = systemEnvironment; this.clock = clock; this.passwordBasedPluginAuthenticationProvider = passwordBasedPluginAuthenticationProvider; this.webBasedPluginAuthenticationProvider = webBasedPluginAuthenticationProvider; } @RequestMapping(value = "/auth/security_check", method = RequestMethod.POST) public RedirectView performLogin(@RequestParam("j_username") String username, @RequestParam("j_password") String password, HttpServletRequest request) { if (securityIsDisabledOrAlreadyLoggedIn(request)) { return new RedirectView("/pipelines", true); } LOGGER.debug("Requesting authentication for form auth."); try { SavedRequest savedRequest = SessionUtils.savedRequest(request); final AuthenticationToken<UsernamePassword> authenticationToken = passwordBasedPluginAuthenticationProvider.authenticate(new UsernamePassword(username, password), null); if (authenticationToken == null) { return badAuthentication(request, BAD_CREDENTIALS_MSG); } else { SessionUtils.setAuthenticationTokenAfterRecreatingSession(authenticationToken, request); } String redirectUrl = savedRequest == null ? "/go/pipelines" : savedRequest.getRedirectUrl(); return new RedirectView(redirectUrl, false); } catch (AuthenticationException e) { LOGGER.error("Failed to authenticate user: {} ", username, e); return badAuthentication(request, e.getMessage()); } catch (Exception e) { return unknownAuthenticationError(request); } } @RequestMapping(value = "/plugin/{pluginId}/login", method = RequestMethod.GET) public RedirectView redirectToThirdPartyLoginPage(@PathVariable("pluginId") String pluginId, HttpServletRequest request) { if (securityIsDisabledOrAlreadyLoggedIn(request)) { return new RedirectView("/pipelines", true); } final StringBuffer requestURL = request.getRequestURL(); requestURL.setLength(requestURL.length() - request.getRequestURI().length()); return new RedirectView(webBasedPluginAuthenticationProvider.getAuthorizationServerUrl(pluginId, requestURL.toString()), false); } @RequestMapping(value = "/plugin/{pluginId}/authenticate") public RedirectView authenticateWithWebBasedPlugin(@PathVariable("pluginId") String pluginId, HttpServletRequest request) { if (securityIsDisabledOrAlreadyLoggedIn(request)) { return new RedirectView("/pipelines", true); } LOGGER.debug("Requesting authentication for form auth."); SavedRequest savedRequest = SessionUtils.savedRequest(request); try { final AccessToken accessToken = webBasedPluginAuthenticationProvider.fetchAccessToken(pluginId, getRequestHeaders(request), getParameterMap(request)); AuthenticationToken<AccessToken> authenticationToken = webBasedPluginAuthenticationProvider.authenticate(accessToken, pluginId); if (authenticationToken == null) { return unknownAuthenticationError(request); } SessionUtils.setAuthenticationTokenAfterRecreatingSession(authenticationToken, request); } catch (AuthenticationException e) { LOGGER.error("Failed to authenticate user.", e); return badAuthentication(request, e.getMessage()); } catch (Exception e) { return unknownAuthenticationError(request); } SessionUtils.removeAuthenticationError(request); String redirectUrl = savedRequest == null ? "/go/pipelines" : savedRequest.getRedirectUrl(); return new RedirectView(redirectUrl, false); } private boolean securityIsDisabledOrAlreadyLoggedIn(HttpServletRequest request) { return !securityService.isSecurityEnabled() || (!isAnonymousAuthenticationToken(request) && SessionUtils.isAuthenticated(request, clock, systemEnvironment)); } private RedirectView badAuthentication(HttpServletRequest request, String message) { SessionUtils.setAuthenticationError(message, request); return REDIRECT_TO_LOGIN_PAGE; } private RedirectView unknownAuthenticationError(HttpServletRequest request) { return badAuthentication(request, UNKNOWN_ERROR_WHILE_AUTHENTICATION); } private HashMap<String, String> getRequestHeaders(HttpServletRequest request) { HashMap<String, String> headers = new HashMap<>(); Enumeration headerNames = request.getHeaderNames(); while (headerNames.hasMoreElements()) { String header = (String) headerNames.nextElement(); String value = request.getHeader(header); headers.put(header, value); } return headers; } private Map<String, String> getParameterMap(HttpServletRequest request) { Map<String, String[]> springParameterMap = request.getParameterMap(); Map<String, String> pluginParameterMap = new HashMap<>(); for (String parameterName : springParameterMap.keySet()) { String[] values = springParameterMap.get(parameterName); if (values != null && values.length > 0) { pluginParameterMap.put(parameterName, values[0]); } else { pluginParameterMap.put(parameterName, null); } } return pluginParameterMap; } }
kierarad/gocd
server/src/main/java/com/thoughtworks/go/server/newsecurity/controllers/AuthenticationController.java
Java
apache-2.0
9,321
/* // Licensed to DynamoBI Corporation (DynamoBI) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. DynamoBI 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.eigenbase.test; import java.util.*; import java.util.regex.*; import junit.framework.*; import org.eigenbase.runtime.*; public abstract class EigenbaseTestCase extends TestCase { //~ Static fields/initializers --------------------------------------------- protected static final String nl = System.getProperty("line.separator"); protected static final String [] emptyStringArray = new String[0]; //~ Constructors ----------------------------------------------------------- protected EigenbaseTestCase(String s) throws Exception { super(s); } //~ Methods ---------------------------------------------------------------- protected static void assertEqualsDeep( Object o, Object o2) { if ((o instanceof Object []) && (o2 instanceof Object [])) { Object [] a = (Object []) o; Object [] a2 = (Object []) o2; assertEquals(a.length, a2.length); for (int i = 0; i < a.length; i++) { assertEqualsDeep(a[i], a2[i]); } return; } if ((o != null) && (o2 != null) && o.getClass().isArray() && (o.getClass() == o2.getClass())) { boolean eq; if (o instanceof boolean []) { eq = Arrays.equals((boolean []) o, (boolean []) o2); } else if (o instanceof byte []) { eq = Arrays.equals((byte []) o, (byte []) o2); } else if (o instanceof char []) { eq = Arrays.equals((char []) o, (char []) o2); } else if (o instanceof short []) { eq = Arrays.equals((short []) o, (short []) o2); } else if (o instanceof int []) { eq = Arrays.equals((int []) o, (int []) o2); } else if (o instanceof long []) { eq = Arrays.equals((long []) o, (long []) o2); } else if (o instanceof float []) { eq = Arrays.equals((float []) o, (float []) o2); } else if (o instanceof double []) { eq = Arrays.equals((double []) o, (double []) o2); } else { eq = false; } if (!eq) { fail("arrays not equal"); } } else { // will handle the case 'o instanceof int[]' ok, because // shallow comparison is ok for ints assertEquals(o, o2); } } /** * Fails if <code>throwable</code> is null, or if its message does not * contain the string <code>pattern</code>. */ protected void assertThrowableContains( Throwable throwable, String pattern) { if (throwable == null) { fail( "expected exception containing pattern <" + pattern + "> but got none"); } String message = throwable.getMessage(); if ((message == null) || (message.indexOf(pattern) < 0)) { fail( "expected pattern <" + pattern + "> in exception <" + throwable + ">"); } } /** * Returns an iterator over the elements of an array. */ public static Iterator makeIterator(Object [] a) { return Arrays.asList(a).iterator(); } /** * Returns a TupleIter over the elements of an array. */ public static TupleIter makeTupleIter(final Object [] a) { return new AbstractTupleIter() { private List data = Arrays.asList(a); private Iterator iter = data.iterator(); public Object fetchNext() { if (iter.hasNext()) { return iter.next(); } return NoDataReason.END_OF_DATA; } public void restart() { iter = data.iterator(); } public void closeAllocation() { iter = null; data = null; } }; } /** * Converts an iterator to a list. */ protected static List toList(Iterator iterator) { ArrayList list = new ArrayList(); while (iterator.hasNext()) { list.add(iterator.next()); } return list; } /** * Converts a TupleIter to a list. */ protected static List toList(TupleIter tupleIter) { ArrayList list = new ArrayList(); while (true) { Object o = tupleIter.fetchNext(); if (o == TupleIter.NoDataReason.END_OF_DATA) { return list; } else if (o == TupleIter.NoDataReason.UNDERFLOW) { // Busy loops. continue; } list.add(o); } } /** * Converts an enumeration to a list. */ protected static List toList(Enumeration enumeration) { ArrayList list = new ArrayList(); while (enumeration.hasMoreElements()) { list.add(enumeration.nextElement()); } return list; } /** * Checks that an iterator returns the same objects as the contents of an * array. */ protected void assertEquals( Iterator iterator, Object [] a) { ArrayList list = new ArrayList(); while (iterator.hasNext()) { list.add(iterator.next()); } assertEquals(list, a); } /** * Checks that a TupleIter returns the same objects as the contents of an * array. */ protected void assertEquals( TupleIter iterator, Object [] a) { ArrayList list = new ArrayList(); while (true) { Object next = iterator.fetchNext(); if (next == TupleIter.NoDataReason.END_OF_DATA) { break; } list.add(next); } assertEquals(list, a); } /** * Checks that a list has the same contents as an array. */ protected void assertEquals( List list, Object [] a) { Object [] b = list.toArray(); assertEquals(a, b); } /** * Checks that two arrays are equal. */ protected void assertEquals( Object [] expected, Object [] actual) { assertTrue(expected.length == actual.length); for (int i = 0; i < expected.length; i++) { assertEquals(expected[i], actual[i]); } } protected void assertEquals( Object [] expected, Object actual) { if (actual instanceof Object []) { assertEquals(expected, (Object []) actual); } else { // They're different. Let assertEquals(Object,Object) give the // error. assertEquals((Object) expected, actual); } } /** * Copies all of the tests in a suite whose names match a given pattern. */ public static TestSuite copySuite( TestSuite suite, Pattern testPattern) { TestSuite newSuite = new TestSuite(); Enumeration tests = suite.tests(); while (tests.hasMoreElements()) { Test test = (Test) tests.nextElement(); if (test instanceof TestCase) { TestCase testCase = (TestCase) test; final String testName = testCase.getName(); if (testPattern.matcher(testName).matches()) { newSuite.addTest(test); } } else if (test instanceof TestSuite) { TestSuite subSuite = copySuite((TestSuite) test, testPattern); if (subSuite.countTestCases() > 0) { newSuite.addTest(subSuite); } } else { // some other kind of test newSuite.addTest(test); } } return newSuite; } } // End EigenbaseTestCase.java
LucidDB/luciddb
farrago/src/org/eigenbase/test/EigenbaseTestCase.java
Java
apache-2.0
8,833
/* * 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.pluto; import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import org.apache.pluto.container.PortletContainer; import org.apache.pluto.container.PortletContainerException; import org.apache.pluto.driver.AttributeKeys; import org.apache.pluto.driver.config.AdminConfiguration; import org.apache.pluto.driver.config.DriverConfiguration; import org.apache.pluto.driver.config.DriverConfigurationException; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceReference; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Listener used to start up / shut down the Pluto Portal Driver upon startup / * showdown of the servlet context in which it resides. * <p/> * Startup Includes: * <ol> * <li>Instantiation of the DriverConfiguration</li> * <li>Registration of the DriverConfiguration</li> * <li>Instantiation of the PortalContext</li> * <li>Registration of the PortalContext</li> * <li>Instantiation of the ContainerServices</li> * <li>Registration of the ContainerServices</li> * </ol> * * @version $Revision$ $Date$ * @since Sep 22, 2004 */ public class PortalStartupListener implements ServletContextListener { /** * Internal logger. */ private static final Logger LOG = LoggerFactory.getLogger( PortalStartupListener.class); /** * The KEY with which the container is bound to the context. */ private static final String CONTAINER_KEY = AttributeKeys.PORTLET_CONTAINER; /** * The KEY with which the driver configuration is bound to the context. */ private static final String DRIVER_CONFIG_KEY = AttributeKeys.DRIVER_CONFIG; /** * The KEY with which the admin configuration is bound to the context. */ private static final String ADMIN_CONFIG_KEY = AttributeKeys.DRIVER_ADMIN_CONFIG; // ServletContextListener Impl --------------------------------------------- /** * Receives the startup notification and subsequently starts up the portal * driver. The following are done in this order: * <ol> * <li>Retrieve the ResourceConfig File</li> * <li>Parse the ResourceConfig File into ResourceConfig Objects</li> * <li>Create a Portal Context</li> * <li>Create the ContainerServices implementation</li> * <li>Create the Portlet Container</li> * <li>Initialize the Container</li> * <li>Bind the configuration to the ServletContext</li> * <li>Bind the container to the ServletContext</li> * <ol> * * @param event the servlet context event. */ public void contextInitialized(ServletContextEvent event) { LOG.info("Starting up Pluto Portal Driver. . ."); final ServletContext servletContext = event.getServletContext(); BundleContext bundleContext = (BundleContext) servletContext.getAttribute("osgi-bundlecontext"); LOG.debug(" [1a] Loading DriverConfiguration. . . "); ServiceReference serviceReference = bundleContext.getServiceReference(DriverConfiguration.class.getName()); DriverConfiguration driverConfiguration = (DriverConfiguration) bundleContext.getService(serviceReference); // driverConfiguration.init(new ResourceSource() { // public InputStream getResourceAsStream(String resourceName) { // return servletContext.getResourceAsStream(resourceName); // } // }); LOG.debug(" [1b] Registering DriverConfiguration. . ."); servletContext.setAttribute(DRIVER_CONFIG_KEY, driverConfiguration); LOG.debug(" [2a] Loading Optional AdminConfiguration. . ."); serviceReference = bundleContext.getServiceReference(AdminConfiguration.class.getName()); AdminConfiguration adminConfiguration = (AdminConfiguration) bundleContext.getService(serviceReference); if (adminConfiguration != null) { LOG.debug(" [2b] Registering Optional AdminConfiguration"); servletContext.setAttribute(ADMIN_CONFIG_KEY, adminConfiguration); } else { LOG.info("Optional AdminConfiguration not found. Ignoring."); } // Retrieve the driver configuration from servlet context. DriverConfiguration driverConfig = (DriverConfiguration) servletContext.getAttribute(DRIVER_CONFIG_KEY); LOG.info("Initializing Portlet Container. . ."); // Create portlet container. LOG.debug(" [1] Creating portlet container..."); serviceReference = bundleContext.getServiceReference(PortletContainer.class.getName()); PortletContainer container = (PortletContainer) bundleContext.getService(serviceReference); // Save portlet container to the servlet context scope. servletContext.setAttribute(CONTAINER_KEY, container); LOG.info("Pluto portlet container started."); LOG.info("********** Pluto Portal Driver Started **********\n\n"); } /** * Receive notification that the context is being shut down and subsequently * destroy the container. * * @param event the destrubtion event. */ public void contextDestroyed(ServletContextEvent event) { ServletContext servletContext = event.getServletContext(); if (LOG.isInfoEnabled()) { LOG.info("Shutting down Pluto Portal Driver..."); } destroyContainer(servletContext); destroyAdminConfiguration(servletContext); destroyDriverConfiguration(servletContext); if (LOG.isInfoEnabled()) { LOG.info("********** Pluto Portal Driver Shut Down **********\n\n"); } } // Private Destruction Methods --------------------------------------------- /** * Destroyes the portlet container and removes it from servlet context. * * @param servletContext the servlet context. */ private void destroyContainer(ServletContext servletContext) { if (LOG.isInfoEnabled()) { LOG.info("Shutting down Pluto Portal Driver..."); } PortletContainer container = (PortletContainer) servletContext.getAttribute(CONTAINER_KEY); if (container != null) { servletContext.removeAttribute(CONTAINER_KEY); } } /** * Destroyes the portal driver config and removes it from servlet context. * * @param servletContext the servlet context. */ private void destroyDriverConfiguration(ServletContext servletContext) { DriverConfiguration driverConfig = (DriverConfiguration) servletContext.getAttribute(DRIVER_CONFIG_KEY); if (driverConfig != null) { // try { // driverConfig.destroy(); // if (LOG.isInfoEnabled()) { // LOG.info("Pluto Portal Driver Config destroyed."); // } // } catch (DriverConfigurationException ex) { // LOG.error("Unable to destroy portal driver config: " // + ex.getMessage(), ex); // } finally { servletContext.removeAttribute(DRIVER_CONFIG_KEY); // } } } /** * Destroyes the portal admin config and removes it from servlet context. * * @param servletContext the servlet context. */ private void destroyAdminConfiguration(ServletContext servletContext) { AdminConfiguration adminConfig = (AdminConfiguration) servletContext.getAttribute(ADMIN_CONFIG_KEY); if (adminConfig != null) { // try { // adminConfig.destroy(); // if (LOG.isInfoEnabled()) { // LOG.info("Pluto Portal Admin Config destroyed."); // } // } catch (DriverConfigurationException ex) { // LOG.error("Unable to destroy portal admin config: " // + ex.getMessage(), ex); // } finally { servletContext.removeAttribute(ADMIN_CONFIG_KEY); // } } } }
apache/geronimo
plugins/pluto/geronimo-pluto/src/main/java/org/apache/geronimo/pluto/PortalStartupListener.java
Java
apache-2.0
8,945
/* * Copyright 2021 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. */ import Stream from "mithril/stream"; import {Origin, OriginJSON} from "models/origin"; export interface EnvironmentAgentJSON { uuid: string; hostname: string; origin: OriginJSON; } export class AgentWithOrigin { uuid: Stream<string>; hostname: Stream<string>; readonly origin: Stream<Origin>; constructor(uuid: string, hostname: string, origin: Origin) { this.uuid = Stream(uuid); this.hostname = Stream(hostname); this.origin = Stream(origin); } static fromJSON(data: EnvironmentAgentJSON) { return new AgentWithOrigin(data.uuid, data.hostname, Origin.fromJSON(data.origin)); } clone() { return new AgentWithOrigin(this.uuid(), this.hostname(), this.origin().clone()); } } export class Agents extends Array<AgentWithOrigin> { constructor(...agents: AgentWithOrigin[]) { super(...agents); Object.setPrototypeOf(this, Object.create(Agents.prototype)); } static fromJSON(agents: EnvironmentAgentJSON[]) { if (agents) { return new Agents(...agents.map(AgentWithOrigin.fromJSON)); } else { return new Agents(); } } }
GaneshSPatil/gocd
server/src/main/webapp/WEB-INF/rails/webpack/models/new-environments/environment_agents.ts
TypeScript
apache-2.0
1,713
/* * Copyright 2016 WSO2 Inc. (http://wso2.org) * * 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.wso2.carbon.metrics.core; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import org.wso2.carbon.metrics.core.config.model.CsvReporterConfig; import org.wso2.carbon.metrics.core.jmx.MetricsMXBean; import org.wso2.carbon.metrics.core.reporter.ReporterBuildException; import org.wso2.carbon.metrics.core.utils.Utils; import java.io.File; import javax.management.JMX; import javax.management.MalformedObjectNameException; import javax.management.ObjectName; /** * Test cases for {@link MetricsMXBean}. */ public class MetricsMXBeanTest extends BaseReporterTest { private static final Logger logger = LoggerFactory.getLogger(MetricManagementServiceTest.class); private static final String MBEAN_NAME = "org.wso2.carbon:type=MetricsTest"; private MetricsMXBean metricsMXBean; @BeforeClass private void createMXBeanProxy() { ObjectName n; try { n = new ObjectName(MBEAN_NAME); metricsMXBean = JMX.newMXBeanProxy(mBeanServer, n, MetricsMXBean.class); } catch (MalformedObjectNameException e) { Assert.fail(e.getMessage()); } } @BeforeMethod private void setRootLevel() { if (logger.isInfoEnabled()) { logger.info("Resetting Root Level to {}", Level.INFO); } metricsMXBean.setRootLevel(Level.INFO.name()); } @Test public void testEnableDisable() { Assert.assertTrue(metricsMXBean.isEnabled(), "Metric Service should be enabled"); Meter meter = metricService.meter(MetricService.name(this.getClass(), "test-enabled"), Level.INFO); meter.mark(); Assert.assertEquals(meter.getCount(), 1); metricsMXBean.disable(); Assert.assertFalse(metricsMXBean.isEnabled(), "Metric Service should be disabled"); meter.mark(); Assert.assertEquals(meter.getCount(), 1); metricsMXBean.enable(); meter.mark(); Assert.assertEquals(meter.getCount(), 2); } @Test public void testMetricSetLevel() { String name = MetricService.name(this.getClass(), "test-metric-level"); Meter meter = metricService.meter(name, Level.INFO); Assert.assertNull(metricsMXBean.getMetricLevel(name), "There should be no configured level"); meter.mark(); Assert.assertEquals(meter.getCount(), 1); metricsMXBean.setMetricLevel(name, Level.INFO.name()); Assert.assertEquals(metricsMXBean.getMetricLevel(name), Level.INFO.name(), "Configured level should be INFO"); meter.mark(); Assert.assertEquals(meter.getCount(), 2); metricsMXBean.setMetricLevel(name, Level.OFF.name()); Assert.assertEquals(metricsMXBean.getMetricLevel(name), Level.OFF.name(), "Configured level should be OFF"); meter.mark(); Assert.assertEquals(meter.getCount(), 2); } @Test public void testMetricServiceLevels() { Meter meter = metricService.meter(MetricService.name(this.getClass(), "test-levels"), Level.INFO); meter.mark(); Assert.assertEquals(meter.getCount(), 1); metricsMXBean.setRootLevel(Level.TRACE.name()); Assert.assertEquals(metricsMXBean.getRootLevel(), Level.TRACE.name()); meter.mark(); Assert.assertEquals(meter.getCount(), 2); metricsMXBean.setRootLevel(Level.OFF.name()); Assert.assertEquals(metricsMXBean.getRootLevel(), Level.OFF.name()); meter.mark(); Assert.assertEquals(meter.getCount(), 2); } @Test public void testMetricsCount() { Assert.assertTrue(metricsMXBean.getMetricsCount() > 0); Assert.assertTrue(metricsMXBean.getEnabledMetricsCount() > 0); Assert.assertTrue(metricsMXBean.getEnabledMetricsCount() <= metricsMXBean.getMetricsCount()); Assert.assertTrue(metricsMXBean.getMetricCollectionsCount() >= 0); } @Test public void testDefaultSource() { Assert.assertEquals(metricsMXBean.getDefaultSource(), Utils.getDefaultSource()); } @Test public void testReporterJMXOperations() throws ReporterBuildException { CsvReporterConfig csvReporterConfig = new CsvReporterConfig(); csvReporterConfig.setName("CSV"); csvReporterConfig.setEnabled(true); csvReporterConfig.setLocation("target/metrics"); csvReporterConfig.setPollingPeriod(600); metricManagementService.addReporter(csvReporterConfig); // Test start/stop reporters metricsMXBean.startReporters(); Assert.assertTrue(metricsMXBean.isReporterRunning("CSV")); metricsMXBean.stopReporters(); Assert.assertFalse(metricsMXBean.isReporterRunning("CSV")); metricsMXBean.startReporter("CSV"); Assert.assertTrue(metricsMXBean.isReporterRunning("CSV")); String meterName1 = MetricService.name(this.getClass(), "test-jmx-report-meter1"); Meter meter1 = metricService.meter(meterName1, Level.INFO); meter1.mark(); Assert.assertEquals(meter1.getCount(), 1); metricsMXBean.report("CSV"); Assert.assertTrue(new File("target/metrics", meterName1 + ".csv").exists(), "Meter CSV file should be created"); String meterName2 = MetricService.name(this.getClass(), "test-jmx-report-meter2"); Meter meter2 = metricService.meter(meterName2, Level.INFO); meter2.mark(); Assert.assertEquals(meter2.getCount(), 1); metricsMXBean.report(); Assert.assertTrue(new File("target/metrics", meterName2 + ".csv").exists(), "Meter CSV file should be created"); metricsMXBean.stopReporter("CSV"); Assert.assertFalse(metricsMXBean.isReporterRunning("CSV")); } }
wso2/carbon-metrics
components/org.wso2.carbon.metrics.core/src/test/java/org/wso2/carbon/metrics/core/MetricsMXBeanTest.java
Java
apache-2.0
6,480
/** * */ package com.fjnu.fund.domain; /** * @author Administrator * */ public class Fund { private Integer fundNo; private String fundName; private Float fundPrice; private String fundDes; private String fundStatus; private String fundDate; public Integer getFundNo() { return fundNo; } public void setFundNo(Integer fundNo) { this.fundNo = fundNo; } public String getFundName() { return fundName; } public void setFundName(String fundName) { this.fundName = fundName; } public Float getFundPrice() { return fundPrice; } public void setFundPrice(Float fundPrice) { this.fundPrice = fundPrice; } public String getFundDes() { return fundDes; } public void setFundDes(String fundDes) { this.fundDes = fundDes; } public String getFundDate() { return fundDate; } public void setFundDate(String fundDate) { this.fundDate = fundDate; } public String getFundStatus() { return fundStatus; } public void setFundStatus(String fundStatus) { this.fundStatus = fundStatus; } }
WebbWangPrivate/JavaSystem
FundSystem/src/com/fjnu/fund/domain/Fund.java
Java
apache-2.0
1,040
/* * Copyright (C) 2009-2011 Texas Instruments, 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. */ /*! \file * \brief This is a complex example of how to use DVP to do vision processing * into a series of display buffers previewed on the dvp_display subsystem. * \author Erik Rainey <erik.rainey@ti.com> */ #if defined(DVP_USE_IMGLIB) #include <imglib/dvp_kl_imglib.h> #endif #if defined(DVP_USE_VLIB) #include <vlib/dvp_kl_vlib.h> #endif #include <dvp/VisionCam.h> #include <dvp/dvp_display.h> #if defined(PC) #define DVP_DEMO_MAX_TIMEOUTS (10000) #else #define DVP_DEMO_MAX_TIMEOUTS (10) #endif typedef struct _dvp_demo_t { #ifdef VCAM_AS_SHARED module_t mod; #endif uint32_t numDisplayImages; VisionCamFactory_f factory; VisionCam *pCam; queue_t *frameq; dvp_display_t *dvpd; DVP_Image_t *displays; /**< Buffers from the DVP Display */ DVP_Image_t *subImages; /**< Subsections of the Display Image */ DVP_Image_t *camImages; /**< GCam Images */ DVP_Image_t *images; /**< DVP Graph Images */ DVP_Handle dvp; DVP_KernelNode_t *nodes; /**< The Kernel Graph Nodes */ DVP_KernelGraph_t *graph; uint32_t numNodes; } DVP_Demo_t; void DVPCallback(void *cookie, DVP_KernelGraph_t *graph, DVP_U32 sectionIndex, DVP_U32 numNodesExecuted) { cookie = cookie; // warnings graph = graph; // warnings sectionIndex = sectionIndex; // warnings numNodesExecuted = numNodesExecuted; // warnings DVP_PRINT(DVP_ZONE_ALWAYS, "Cookie %p Graph %p Graph Section %u Completed %u nodes\n", cookie, graph, sectionIndex, numNodesExecuted); } void VisionCamCallback(VisionCamFrame * cameraFrame) { DVP_Image_t *pImage = (DVP_Image_t *)cameraFrame->mFrameBuff; queue_t *frameq = (queue_t *)cameraFrame->mCookie; DVP_PRINT(DVP_ZONE_CAM, "Writing Frame %p into Queue %p\n", cameraFrame, frameq); DVP_PrintImage(DVP_ZONE_CAM, pImage); if (queue_write(frameq, true_e, &cameraFrame) == false_e) { DVP_PRINT(DVP_ZONE_ERROR, "Failed to write frame to queue\n"); } } bool_e VisionCamInit(DVP_Demo_t *demo, VisionCam_e camType, uint32_t width, uint32_t height, uint32_t fps, uint32_t rotation, uint32_t color) { int32_t ret = 0; #ifdef VCAM_AS_SHARED demo->mod = module_load(CAMERA_NAME); if (demo->mod) { demo->factory = (VisionCamFactory_f)module_symbol(demo->mod, "VisionCamFactory"); if (demo->factory) { demo->pCam = demo->factory(VISIONCAM_OMX); if (demo->pCam) { #else demo->pCam = VisionCamFactory(camType); if (demo->pCam) { #endif VisionCamSensorSelection sensorIndex = VCAM_SENSOR_SECONDARY; #if defined(DUCATI_1_5) || defined(DUCATI_2_0) VisionCamCaptureMode capmode = VCAM_GESTURE_MODE; #else VisionCamCaptureMode capmode = VCAM_VIDEO_NORMAL; #endif VisionCamFlickerType flicker = FLICKER_60Hz; VisionCamFocusMode focus = VCAM_FOCUS_CONTROL_AUTO; VisionCamWhiteBalType white = VCAM_WHITE_BAL_CONTROL_AUTO; int32_t brightness = 50; // initialize the VisionCam VCAM_COMPLAIN_IF_FAILED(ret, demo->pCam->init(demo->frameq)); // configure the parameters VCAM_COMPLAIN_IF_FAILED(ret, demo->pCam->setParameter(VCAM_PARAM_WIDTH, &width, sizeof(width))); VCAM_COMPLAIN_IF_FAILED(ret, demo->pCam->setParameter(VCAM_PARAM_HEIGHT, &height, sizeof(height))); VCAM_COMPLAIN_IF_FAILED(ret, demo->pCam->setParameter(VCAM_PARAM_COLOR_SPACE_FOURCC, &color, sizeof(color))); VCAM_COMPLAIN_IF_FAILED(ret, demo->pCam->setParameter(VCAM_PARAM_CAP_MODE, &capmode, sizeof(capmode))); VCAM_COMPLAIN_IF_FAILED(ret, demo->pCam->setParameter(VCAM_PARAM_SENSOR_SELECT, &sensorIndex, sizeof(sensorIndex))); VCAM_COMPLAIN_IF_FAILED(ret, demo->pCam->setParameter(VCAM_PARAM_FPS_FIXED, &fps, sizeof(fps))); VCAM_COMPLAIN_IF_FAILED(ret, demo->pCam->setParameter(VCAM_PARAM_FLICKER, &flicker, sizeof(flicker))); VCAM_COMPLAIN_IF_FAILED(ret, demo->pCam->setParameter(VCAM_PARAM_BRIGHTNESS, &brightness, sizeof(brightness))); VCAM_COMPLAIN_IF_FAILED(ret, demo->pCam->setParameter(VCAM_PARAM_AWB_MODE, &white, sizeof(white))); // configure the buffers (the first X images are for the camera) VCAM_COMPLAIN_IF_FAILED(ret, demo->pCam->useBuffers(demo->camImages, demo->numDisplayImages)); // @todo BUG: Can't set rotation until after useBuffers VCAM_COMPLAIN_IF_FAILED(ret, demo->pCam->setParameter(VCAM_PARAM_ROTATION, &rotation, sizeof(rotation))); // register the callback VCAM_COMPLAIN_IF_FAILED(ret, demo->pCam->enablePreviewCbk(VisionCamCallback)); // start the preview VCAM_COMPLAIN_IF_FAILED(ret, demo->pCam->sendCommand(VCAM_CMD_PREVIEW_START)); // do the autofocus VCAM_COMPLAIN_IF_FAILED(ret, demo->pCam->setParameter(VCAM_PARAM_DO_AUTOFOCUS, &focus, sizeof(focus))); return true_e; } #ifdef VCAM_AS_SHARED } } } #endif return false_e; } bool_e VisionCamDeinit(DVP_Demo_t *demo) { int32_t ret = 0; if (demo->pCam) { // destroy the camera VCAM_COMPLAIN_IF_FAILED(ret, demo->pCam->sendCommand(VCAM_CMD_PREVIEW_STOP)); VCAM_COMPLAIN_IF_FAILED(ret, demo->pCam->disablePreviewCbk(VisionCamCallback)); VCAM_COMPLAIN_IF_FAILED(ret, demo->pCam->releaseBuffers()); VCAM_COMPLAIN_IF_FAILED(ret, demo->pCam->deinit()); delete demo->pCam; demo->pCam = NULL; } #ifdef VCAM_AS_SHARED module_unload(demo->mod); #endif if (ret != 0) return false_e; else return true_e; } bool_e SubsectionImage(DVP_Image_t *dispFrame, DVP_Image_t *image, uint32_t index) { if (dispFrame->planes == image->planes && dispFrame->color == image->color) { uint32_t limit_i = dispFrame->width / image->width; uint32_t limit_j = dispFrame->height / image->height; uint32_t i = index % limit_i; uint32_t j = index / limit_i; DVP_PRINT(DVP_ZONE_ALWAYS, "Requested Index %u in Image of {%u,%u} (%ux%u => %ux%u)\n",index, i,j, dispFrame->width, dispFrame->height, image->width, image->height); DVP_PrintImage(DVP_ZONE_ALWAYS, dispFrame); if (j > limit_j) return false_e; else { uint32_t p = 0; // make sure th strides are transfered. image->y_stride = dispFrame->y_stride; // create each subimage plane from the display frame. for (p = 0; p < dispFrame->planes; p++) { uint32_t k = (j * (image->height * dispFrame->y_stride)) + (i * (image->width * dispFrame->x_stride)); image->pData[p] = &dispFrame->pData[p][k]; image->pBuffer[p] = &dispFrame->pData[p][k]; DVP_PrintImage(DVP_ZONE_ALWAYS, image); } return true_e; } } else return false_e; } int main(int argc, char *argv[]) { int ret = 0; #if (defined(DVP_USE_VLIB) || defined(DVP_USE_YUV)) && defined(DVP_USE_IMGLIB) DVP_Demo_t *demo = (DVP_Demo_t *)calloc(1, sizeof(DVP_Demo_t)); #if defined(SOSAL_RUNTIME_DEBUG) debug_get_zone_mask("SOSAL_ZONE_MASK", &sosal_zone_mask); #endif #if defined(DVP_RUNTIME_DEBUG) debug_get_zone_mask("DVP_ZONE_MASK", &dvp_zone_mask); #endif if (demo && argc >= 1) { uint32_t i,j,k,n; uint32_t display_width = (argc > 1?atoi(argv[1]):640); uint32_t display_height = (argc > 2?atoi(argv[2]):480); uint32_t width = (argc > 3?atoi(argv[3]):160); uint32_t height = (argc > 4?atoi(argv[4]):120); uint32_t fps = 30; uint32_t numFrames = (argc > 5?atoi(argv[5]):100); // how many frames to display before quitting uint32_t numSubImages = (display_width/width) * (display_height/height); uint32_t numGraphImages = 20; /// @note make sure this matches the numbers used below int32_t focusDepth = 10; int32_t frameLock = 100; demo->numDisplayImages = DVP_DISPLAY_NUM_BUFFERS - 1; uint32_t numImages = numSubImages * demo->numDisplayImages; VisionCam_e camType = VISIONCAM_OMX; #if defined(PC) camType = VISIONCAM_USB; #endif demo->frameq = queue_create(demo->numDisplayImages * VCAM_PORT_MAX, sizeof(VisionCamFrame *)); demo->dvpd = DVP_Display_Create(display_width, display_height, display_width, display_height, DVP_DISPLAY_WIDTH, DVP_DISPLAY_HEIGHT, display_width, display_height, 0, 0, FOURCC_UYVY, 0, DVP_DISPLAY_NUM_BUFFERS); demo->subImages = (DVP_Image_t *)calloc(numImages, sizeof(DVP_Image_t)); demo->displays = (DVP_Image_t *)calloc(demo->numDisplayImages, sizeof(DVP_Image_t)); demo->camImages = (DVP_Image_t *)calloc(demo->numDisplayImages, sizeof(DVP_Image_t)); demo->images = (DVP_Image_t *)calloc(numGraphImages, sizeof(DVP_Image_t)); demo->dvp = DVP_KernelGraph_Init(); if (demo->frameq && demo->dvpd && demo->subImages && demo->displays && demo->camImages && demo->dvp && demo->images) { // initialize the display buffers for (n = 0; n < demo->numDisplayImages; n++) { DVP_Image_Init(&demo->displays[n], display_width, display_height, FOURCC_UYVY); DVP_Display_Alloc(demo->dvpd, &demo->displays[n]); DVP_Image_Alloc(demo->dvp, &demo->displays[n], (DVP_MemType_e)demo->displays[n].memType); DVP_Image_Init(&demo->camImages[n], width, height, FOURCC_UYVY); // Blank the Images for (i = 0; i < demo->displays[n].planes; i++) for (j = 0; j < demo->displays[n].height; j++) memset(DVP_Image_Addressing(&demo->displays[n], 0, j, i), 0x80, DVP_Image_LineSize(&demo->displays[n], i)); // initialize images which are the subsections of the display buffers for (i = 0; i < numSubImages; i++) { uint32_t k = (n * numSubImages) + i; DVP_Image_Init(&demo->subImages[k], width, height, FOURCC_UYVY); SubsectionImage(&demo->displays[n], &demo->subImages[k], i); if (i == 0) { // if this is the first index of the subsections, // use this as the camera buffer memcpy(&demo->camImages[n], &demo->subImages[k],sizeof(DVP_Image_t)); } } } // initialize the DVP Nodes and Graphs i = 0; uint32_t idx_a9, len_a9; uint32_t idx_dsp, len_dsp; uint32_t idx_m3, len_m3; uint32_t idx_conv, len_conv; uint32_t idx_mask_x, idx_scratch, idx_mask_y, idx_scratch2; // A9 idx_a9 = i; DVP_Image_Init(&demo->images[i++], width, height, FOURCC_Y800); // LUMA DVP_Image_Init(&demo->images[i++], width, height, FOURCC_Y800); // EDGE SOBEL DVP_Image_Init(&demo->images[i++], width, height, FOURCC_Y800); // EDGE PREWITT DVP_Image_Init(&demo->images[i++], width, height, FOURCC_Y800); // EDGE SCHARR len_a9 = i - idx_a9; for (j = 0; j < len_a9; j++) { if (DVP_Image_Alloc(demo->dvp, &demo->images[idx_a9+j], DVP_MTYPE_MPUCACHED_VIRTUAL) == DVP_FALSE) { DVP_PRINT(DVP_ZONE_ERROR, "ERROR: Failed to allocate A9 image\n"); } } // DSP idx_dsp = i; DVP_Image_Init(&demo->images[i++], width, height, FOURCC_Y800); // LUMA DVP_Image_Init(&demo->images[i++], width, height, FOURCC_Y800); // CONV 3x3 Gx DVP_Image_Init(&demo->images[i++], width, height, FOURCC_Y800); // CONV 3x3 Gy DVP_Image_Init(&demo->images[i++], width, height, FOURCC_Y800); // DILATE DVP_Image_Init(&demo->images[i++], width, height, FOURCC_Y800); // IIR H DVP_Image_Init(&demo->images[i++], width, height, FOURCC_Y800); // IIR V len_dsp = i - idx_dsp; for (j = 0; j < len_dsp; j++) { #if defined(DVP_USE_TILER) if (DVP_Image_Alloc(demo->dvp, &demo->images[idx_dsp+j], DVP_MTYPE_MPUCACHED_1DTILED) == DVP_FALSE) { DVP_PRINT(DVP_ZONE_ERROR, "ERROR: Failed to allocate DSP image\n"); } #else if (DVP_Image_Alloc(demo->dvp, &demo->images[idx_dsp+j], DVP_MTYPE_DEFAULT) == DVP_FALSE) { DVP_PRINT(DVP_ZONE_ERROR, "ERROR: Failed to allocate DSP image\n"); } #endif } // SIMCOP idx_m3 = i; DVP_Image_Init(&demo->images[i++], width, height, FOURCC_Y800); // LUMA DVP_Image_Init(&demo->images[i++], width, height, FOURCC_Y800); // SOBEL Gx DVP_Image_Init(&demo->images[i++], width, height, FOURCC_Y800); // SOBEL Gy DVP_Image_Init(&demo->images[i++], width, height, FOURCC_Y800); // IIR H DVP_Image_Init(&demo->images[i++], width, height, FOURCC_Y800); // IIR V len_m3 = i - idx_m3; for (j = 0; j < len_m3; j++) { #if defined(DVP_USE_TILER) if (DVP_Image_Alloc(demo->dvp, &demo->images[idx_m3+j], DVP_MTYPE_MPUNONCACHED_2DTILED) == DVP_FALSE) { DVP_PRINT(DVP_ZONE_ERROR, "ERROR: Failed to allocate M3 image\n"); } #else if (DVP_Image_Alloc(demo->dvp, &demo->images[idx_m3+j], DVP_MTYPE_DEFAULT) == DVP_FALSE) { DVP_PRINT(DVP_ZONE_ERROR, "ERROR: Failed to allocate M3 image\n"); } #endif } idx_conv = i; // the display conversion images start here len_conv = i; // we want to convert all these images; // Mask & Scratch idx_mask_x = i; DVP_Image_Init(&demo->images[i++], 3, 3, FOURCC_Y800); DVP_Image_Alloc(demo->dvp, &demo->images[idx_mask_x], DVP_MTYPE_MPUCACHED_VIRTUAL); idx_mask_y = i; DVP_Image_Init(&demo->images[i++], 3, 3, FOURCC_Y800); DVP_Image_Alloc(demo->dvp, &demo->images[idx_mask_y], DVP_MTYPE_MPUCACHED_VIRTUAL); idx_scratch = i; DVP_Image_Init(&demo->images[i++], width, height, FOURCC_Y800); DVP_Image_Alloc(demo->dvp, &demo->images[idx_scratch], DVP_MTYPE_MPUCACHED_VIRTUAL); idx_scratch2 = i; DVP_Image_Init(&demo->images[i++], width, height, FOURCC_Y800); DVP_Image_Alloc(demo->dvp, &demo->images[idx_scratch2], DVP_MTYPE_MPUCACHED_VIRTUAL); // fill in the mask with the SOBEL X Gradient edge filter demo->images[idx_mask_x].pData[0][0] = (uint8_t)-1; demo->images[idx_mask_x].pData[0][1] = (uint8_t) 0; demo->images[idx_mask_x].pData[0][2] = (uint8_t) 1; demo->images[idx_mask_x].pData[0][3] = (uint8_t)-2; demo->images[idx_mask_x].pData[0][4] = (uint8_t) 0; demo->images[idx_mask_x].pData[0][5] = (uint8_t) 2; demo->images[idx_mask_x].pData[0][6] = (uint8_t)-1; demo->images[idx_mask_x].pData[0][7] = (uint8_t) 0; demo->images[idx_mask_x].pData[0][8] = (uint8_t) 1; // fill in the mask with the SOBEL Y Gradient edge filter demo->images[idx_mask_y].pData[0][0] = (uint8_t)-1; demo->images[idx_mask_y].pData[0][1] = (uint8_t)-2; demo->images[idx_mask_y].pData[0][2] = (uint8_t)-1; demo->images[idx_mask_y].pData[0][3] = (uint8_t) 0; demo->images[idx_mask_y].pData[0][4] = (uint8_t) 0; demo->images[idx_mask_y].pData[0][5] = (uint8_t) 0; demo->images[idx_mask_y].pData[0][6] = (uint8_t) 1; demo->images[idx_mask_y].pData[0][7] = (uint8_t) 2; demo->images[idx_mask_y].pData[0][8] = (uint8_t) 1; demo->numNodes = len_a9 + len_dsp + len_m3 + len_conv; DVP_PRINT(DVP_ZONE_ALWAYS, "Allocating %u %ux%u images\n", demo->numNodes, width, height); // Allocate the Nodes demo->nodes = DVP_KernelNode_Alloc(demo->dvp, demo->numNodes); if (demo->nodes == NULL) return STATUS_NOT_ENOUGH_MEMORY; DVP_KernelGraphSection_t sections[] = { {&demo->nodes[idx_a9], len_a9, DVP_PERF_INIT, DVP_CORE_LOAD_INIT, DVP_FALSE}, {&demo->nodes[idx_dsp], len_dsp, DVP_PERF_INIT, DVP_CORE_LOAD_INIT, DVP_FALSE}, {&demo->nodes[idx_m3], len_m3, DVP_PERF_INIT, DVP_CORE_LOAD_INIT, DVP_FALSE}, {&demo->nodes[idx_conv], len_conv, DVP_PERF_INIT, DVP_CORE_LOAD_INIT, DVP_FALSE}, }; DVP_U32 order[] = {0,0,0,1}; // 3 parallel then 1 series DVP_KernelGraph_t graph = { sections, dimof(sections), order, DVP_PERF_INIT, DVP_FALSE, }; DVP_Transform_t *io = NULL; DVP_Morphology_t *morph = NULL; DVP_ImageConvolution_t *img = NULL; DVP_IIR_t *iir = NULL; demo->graph = &graph; i = 0; // Now initialize the node structures for exactly what we want // A9 Section demo->nodes[i].header.kernel = DVP_KN_XYXY_TO_Y800; demo->nodes[i].header.affinity = DVP_CORE_CPU; io = dvp_knode_to(&demo->nodes[i], DVP_Transform_t); io->input = demo->camImages[0]; io->output = demo->images[idx_a9]; i++; demo->nodes[i].header.kernel = DVP_KN_SOBEL_8; demo->nodes[i].header.affinity = DVP_CORE_CPU; io = dvp_knode_to(&demo->nodes[i], DVP_Transform_t); io->input = demo->images[idx_a9]; io->output = demo->images[idx_a9+1]; i++; demo->nodes[i].header.kernel = DVP_KN_PREWITT_8; demo->nodes[i].header.affinity = DVP_CORE_CPU; io = dvp_knode_to(&demo->nodes[i], DVP_Transform_t); io->input = demo->images[idx_a9]; io->output = demo->images[idx_a9+2]; i++; demo->nodes[i].header.kernel = DVP_KN_SCHARR_8; demo->nodes[i].header.affinity = DVP_CORE_CPU; io = dvp_knode_to(&demo->nodes[i], DVP_Transform_t); io->input = demo->images[idx_a9]; io->output = demo->images[idx_a9+3]; i++; // DSP Section demo->nodes[i].header.kernel = DVP_KN_XYXY_TO_Y800; demo->nodes[i].header.affinity = DVP_CORE_DSP; io = dvp_knode_to(&demo->nodes[i], DVP_Transform_t); io->input = demo->camImages[0]; io->output = demo->images[idx_dsp]; i++; demo->nodes[i].header.kernel = DVP_KN_IMG_CONV_3x3; demo->nodes[i].header.affinity = DVP_CORE_DSP; img = dvp_knode_to(&demo->nodes[i], DVP_ImageConvolution_t); img->input = demo->images[idx_dsp]; img->output = demo->images[idx_dsp+1]; img->mask = demo->images[idx_mask_x]; i++; demo->nodes[i].header.kernel = DVP_KN_IMG_CONV_3x3; demo->nodes[i].header.affinity = DVP_CORE_DSP; img = dvp_knode_to(&demo->nodes[i], DVP_ImageConvolution_t); img->input = demo->images[idx_dsp+1]; img->output = demo->images[idx_dsp+2]; img->mask = demo->images[idx_mask_y]; i++; demo->nodes[i].header.kernel = DVP_KN_DILATE_CROSS; demo->nodes[i].header.affinity = DVP_CORE_DSP; morph = dvp_knode_to(&demo->nodes[i], DVP_Morphology_t); morph->input = demo->images[idx_dsp+2]; morph->output = demo->images[idx_dsp+3]; i++; demo->nodes[i].header.kernel = DVP_KN_IIR_HORZ; demo->nodes[i].header.affinity = DVP_CORE_DSP; iir = dvp_knode_to(&demo->nodes[i], DVP_IIR_t); iir->input = demo->images[idx_dsp]; iir->output = demo->images[idx_dsp+4]; iir->scratch = demo->images[idx_scratch]; iir->weight = 2000; i++; demo->nodes[i].header.kernel = DVP_KN_IIR_VERT; demo->nodes[i].header.affinity = DVP_CORE_DSP; iir = dvp_knode_to(&demo->nodes[i], DVP_IIR_t); iir->input = demo->images[idx_dsp]; iir->output = demo->images[idx_dsp+5]; iir->scratch = demo->images[idx_scratch]; iir->weight = 2000; i++; // SIMCOP Section demo->nodes[i].header.kernel = DVP_KN_XYXY_TO_Y800; demo->nodes[i].header.affinity = DVP_CORE_SIMCOP; io = dvp_knode_to(&demo->nodes[i], DVP_Transform_t); io->input = demo->camImages[0]; io->output = demo->images[idx_m3]; i++; demo->nodes[i].header.kernel = DVP_KN_IMG_CONV_3x3; demo->nodes[i].header.affinity = DVP_CORE_SIMCOP; img = dvp_knode_to(&demo->nodes[i], DVP_ImageConvolution_t); img->input = demo->images[idx_m3]; img->output = demo->images[idx_m3+1]; img->mask = demo->images[idx_mask_x]; i++; demo->nodes[i].header.kernel = DVP_KN_IMG_CONV_3x3; demo->nodes[i].header.affinity = DVP_CORE_SIMCOP; img = dvp_knode_to(&demo->nodes[i], DVP_ImageConvolution_t); img->input = demo->images[idx_m3+1]; img->output = demo->images[idx_m3+2]; img->mask = demo->images[idx_mask_x]; i++; demo->nodes[i].header.kernel = DVP_KN_IIR_HORZ; demo->nodes[i].header.affinity = DVP_CORE_SIMCOP; iir = dvp_knode_to(&demo->nodes[i], DVP_IIR_t); iir->input = demo->images[idx_m3]; iir->output = demo->images[idx_m3+3]; iir->scratch = demo->images[idx_scratch2]; iir->weight = 2000; i++; demo->nodes[i].header.kernel = DVP_KN_IIR_VERT; demo->nodes[i].header.affinity = DVP_CORE_SIMCOP; iir = dvp_knode_to(&demo->nodes[i], DVP_IIR_t); iir->input = demo->images[idx_m3]; iir->output = demo->images[idx_m3+4]; iir->scratch = demo->images[idx_scratch2]; iir->weight = 2000; i++; // CONVERSION for Display Graph for (j = i, k = 0; j < demo->numNodes; j++, k++) { demo->nodes[j].header.kernel = DVP_KN_Y800_TO_XYXY; demo->nodes[j].header.affinity = DVP_CORE_CPU; io = dvp_knode_to(&demo->nodes[i], DVP_Transform_t); io->input = demo->images[k]; //io->output = demo->subImages[k]; // this will get replaced as soon as a buffer is returned } // initialize the camera if (VisionCamInit(demo, camType, width, height, fps, 0, FOURCC_UYVY)) { VisionCamFrame *cameraFrame = NULL; DVP_Image_t *pImage = NULL; uint32_t recvFrames = 0; uint32_t timeouts = 0; thread_msleep(1000/fps); // wait 1 frame period. DVP_PRINT(DVP_ZONE_ALWAYS, "VisionCam is initialized, entering queue read loop!\n"); // read from the queue and display the images do { bool_e ret = queue_read(demo->frameq, false_e, &cameraFrame); if (ret == true_e && cameraFrame != NULL) { uint32_t idx_disp = 0; pImage = (DVP_Image_t *)cameraFrame->mFrameBuff; timeouts = 0; DVP_PRINT(DVP_ZONE_ALWAYS, "Received Frame %p (%p) from camera\n", pImage, pImage->pData[0]); // match the pImage with a displays for (idx_disp = 0; idx_disp < demo->numDisplayImages; idx_disp++) if (pImage->pData[0] == demo->camImages[idx_disp].pData[0]) break; DVP_PRINT(DVP_ZONE_ALWAYS, "Image Correlates to Display Buffer %u (%p->%p)\n", idx_disp, &demo->displays[idx_disp], demo->displays[idx_disp].pData[0]); // update the DVP Graphs with the new camera image dvp_knode_to(&demo->nodes[idx_a9], DVP_Transform_t)->input = *pImage; dvp_knode_to(&demo->nodes[idx_dsp], DVP_Transform_t)->input = *pImage; dvp_knode_to(&demo->nodes[idx_m3], DVP_Transform_t)->input = *pImage; // update the conversion array for (i = 0; i < len_conv; i++) { // add one to the subImages index to skip the camera preview in that // frame. dvp_knode_to(&demo->nodes[idx_conv+i], DVP_Transform_t)->output = demo->subImages[(idx_disp * numSubImages) + i + 1]; } // run the DVP Kernel Graph DVP_KernelGraph_Process(demo->dvp, demo->graph, demo, DVPCallback); // update the display DVP_Display_Render(demo->dvpd, &demo->displays[idx_disp]); demo->pCam->returnFrame(cameraFrame); recvFrames++; if (recvFrames > numFrames) break; if (focusDepth >= 0) { if (recvFrames == fps) { // after 1 second demo->pCam->setParameter(VCAM_PARAM_DO_MANUALFOCUS, &focusDepth, sizeof(focusDepth)); } } if (frameLock > 0) { if (recvFrames == (uint32_t)frameLock) { bool_e lock = true_e; demo->pCam->sendCommand(VCAM_CMD_LOCK_AE, &lock, sizeof(lock)); demo->pCam->sendCommand(VCAM_CMD_LOCK_AWB, &lock, sizeof(lock)); } } } else { DVP_PRINT(DVP_ZONE_ERROR, "Timedout waiting for buffer from Camera!\n"); timeouts++; thread_msleep(1000/fps); } } while (timeouts < DVP_DEMO_MAX_TIMEOUTS); } else { DVP_PRINT(DVP_ZONE_ERROR, "DVP_DEMO Failed during camera initialization\n"); ret = STATUS_NO_RESOURCES; } DVP_PrintPerformanceGraph(demo->dvp, demo->graph); DVP_KernelNode_Free(demo->dvp, demo->nodes, demo->numNodes); VisionCamDeinit(demo); } else { DVP_PRINT(DVP_ZONE_ERROR, "DVP_DEMO Failed during data structure initialization\n"); } if (demo->dvp) { DVP_KernelGraph_Deinit(demo->dvp); } if (demo->camImages) free(demo->camImages); if (demo->displays) { for (n = 0; n < demo->numDisplayImages; n++) { DVP_Display_Free(demo->dvpd, &demo->displays[n]); } free(demo->displays); } if (demo->subImages) free(demo->subImages); if (demo->images) free(demo->images); if (demo->dvpd) DVP_Display_Destroy(&demo->dvpd); if (demo->frameq) queue_destroy(demo->frameq); } #else DVP_PRINT(DVP_ZONE_ERROR, "Required libraries are not present!\n"); argc |= 1; argv[0] = argv[0]; ret = -1; #endif return ret; }
emrainey/DVP
source/dvp/dvp_demo/dvp_demo.cpp
C++
apache-2.0
28,924
/* Copyright 2012-2015 SAP SE * * 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 eu.aniketos.securebpmn.xacml.support; import java.net.URI; import java.util.HashSet; import java.util.Set; import org.apache.log4j.Logger; import eu.aniketos.securebpmn.xacml.support.finder.IPDPStateEvaluationContext; import com.sun.xacml.Constants; import com.sun.xacml.EvaluationCtx; import com.sun.xacml.attr.AttributeValue; import com.sun.xacml.attr.BagAttribute; import com.sun.xacml.attr.IntegerAttribute; import com.sun.xacml.attr.StringAttribute; import com.sun.xacml.attr.TypeIdentifierConstants; import com.sun.xacml.cond.EvaluationResult; public class AttributeResolver { private static final Logger logger = Logger.getLogger(AttributeResolver.class); public static long getPDPStatePolicyVersion(EvaluationCtx ctx) { EvaluationResult evalResult = ctx.getAttribute(IPDPStateEvaluationContext.PDPSTATE_CATEGORY, IPDPStateEvaluationContext.PDPSTATE_ATTRIBUTETYPE, IPDPStateEvaluationContext.PDPSTATE_URI, IPDPStateEvaluationContext.PDPSTATE_ISSUER); if ( ((BagAttribute) evalResult.getAttributeValue()).size() > 1 ) { logger.error("Did not retreive a bag with one (" +((BagAttribute) evalResult.getAttributeValue()).size() + ") entry after attribute search for current svn policy version number; " + "PDP Dtate requires exactly one attribute to be defined"); return -1; } else if ( ((BagAttribute) evalResult.getAttributeValue()).size() == 1 ) { IntegerAttribute attrVal = (IntegerAttribute) ((BagAttribute) evalResult.getAttributeValue()).iterator().next(); if ( logger.isDebugEnabled() && ctx instanceof EvaluationIdContext) logger.debug("Request " + ((EvaluationIdContext) ctx).getCurrentEvaluationId() + " is executed under policy " + attrVal.getValue()); return attrVal.getValue(); } else { logger.debug("Could not resolve current policy version"); return -1; } } public static final URI ACTIVEPOLICY_CATEGORY = Constants.ENVIRONMENT_CAT; public static final URI ACTIVEPOLICY_ATTRIBUTETYPE = TypeIdentifierConstants.STRING_URI; public static final String ACTIVEPOLICY = "urn:activePolicies"; public static final URI ACTIVEPOLICY_URI = URI.create(ACTIVEPOLICY); public static final URI ACTIVEPOLICY_ISSUER = null; public static Set<String> getActivePolicies(EvaluationCtx ctx) { EvaluationResult evalResult = ctx.getAttribute(ACTIVEPOLICY_CATEGORY, ACTIVEPOLICY_ATTRIBUTETYPE, ACTIVEPOLICY_URI, ACTIVEPOLICY_ISSUER); Set<String> policies = new HashSet<String>(); for (AttributeValue value : ((BagAttribute) evalResult.getAttributeValue()).iterable()) { policies.add( ((StringAttribute)value).getValue()); } return policies; } }
GenericBreakGlass/GenericBreakGlass-XACML
src/eu.aniketos.securebpmn.xacml.support/src/main/java/eu/aniketos/securebpmn/xacml/support/AttributeResolver.java
Java
apache-2.0
3,664
/* * 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.ode.bpel.memdao; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.ode.bpel.common.BpelEventFilter; import org.apache.ode.bpel.common.Filter; import org.apache.ode.bpel.common.InstanceFilter; import org.apache.ode.bpel.common.ProcessFilter; import org.apache.ode.bpel.dao.BpelDAOConnection; import org.apache.ode.bpel.dao.MessageExchangeDAO; import org.apache.ode.bpel.dao.ProcessDAO; import org.apache.ode.bpel.dao.ProcessInstanceDAO; import org.apache.ode.bpel.dao.ScopeDAO; import org.apache.ode.bpel.evt.BpelEvent; import org.apache.ode.bpel.iapi.Scheduler; import org.apache.ode.utils.ISO8601DateParser; import org.apache.ode.utils.stl.CollectionsX; import org.apache.ode.utils.stl.UnaryFunction; import javax.xml.namespace.QName; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.ConcurrentHashMap; /** * A very simple, in-memory implementation of the {@link BpelDAOConnection} interface. */ class BpelDAOConnectionImpl implements BpelDAOConnection { private static final Log __log = LogFactory.getLog(BpelDAOConnectionImpl.class); private Scheduler _scheduler; private Map<QName, ProcessDaoImpl> _store; private List<BpelEvent> _events = new LinkedList<BpelEvent>(); long _mexTtl; private static Map<String,MessageExchangeDAO> _mexStore = Collections.synchronizedMap(new HashMap<String,MessageExchangeDAO>()); protected static Map<String, Long> _mexAge = new ConcurrentHashMap<String, Long>(); private static AtomicLong counter = new AtomicLong(Long.MAX_VALUE / 2); private static volatile long _lastRemoval = 0; BpelDAOConnectionImpl(Map<QName, ProcessDaoImpl> store, Scheduler scheduler, long mexTtl) { _store = store; _scheduler = scheduler; _mexTtl = mexTtl; } public ProcessDAO getProcess(QName processId) { return _store.get(processId); } public ProcessDAO createProcess(QName pid, QName type, String guid, long version) { ProcessDaoImpl process = new ProcessDaoImpl(this,_store,pid,type, guid,version); _store.put(pid,process); return process; } public ProcessInstanceDAO getInstance(Long iid) { for (ProcessDaoImpl proc : _store.values()) { ProcessInstanceDAO instance = proc._instances.get(iid); if (instance != null) return instance; } return null; } public Collection<ProcessInstanceDAO> instanceQuery(InstanceFilter filter) { if(filter.getLimit()==0) { return Collections.EMPTY_LIST; } List<ProcessInstanceDAO> matched = new ArrayList<ProcessInstanceDAO>(); // Selecting selectionCompleted: for (ProcessDaoImpl proc : _store.values()) { boolean pmatch = true; if (filter.getNameFilter() != null && !equalsOrWildcardMatch(filter.getNameFilter(), proc.getProcessId().getLocalPart())) pmatch = false; if (filter.getNamespaceFilter() != null && !equalsOrWildcardMatch(filter.getNamespaceFilter(), proc.getProcessId().getNamespaceURI())) pmatch = false; if (pmatch) { for (ProcessInstanceDAO inst : proc._instances.values()) { boolean match = true; if (filter.getStatusFilter() != null) { boolean statusMatch = false; for (Short status : filter.convertFilterState()) { if (inst.getState() == status.byteValue()) statusMatch = true; } if (!statusMatch) match = false; } if (filter.getStartedDateFilter() != null && !dateMatch(filter.getStartedDateFilter(), inst.getCreateTime(), filter)) match = false; if (filter.getLastActiveDateFilter() != null && !dateMatch(filter.getLastActiveDateFilter(), inst.getLastActiveTime(), filter)) match = false; // if (filter.getPropertyValuesFilter() != null) { // for (Map.Entry propEntry : filter.getPropertyValuesFilter().entrySet()) { // boolean entryMatched = false; // for (ProcessPropertyDAO prop : proc.getProperties()) { // if (prop.getName().equals(propEntry.getKey()) // && (propEntry.getValue().equals(prop.getMixedContent()) // || propEntry.getValue().equals(prop.getSimpleContent()))) { // entryMatched = true; // } // } // if (!entryMatched) { // match = false; // } // } // } if (match) { matched.add(inst); if(matched.size()==filter.getLimit()) { break selectionCompleted; } } } } } // And ordering if (filter.getOrders() != null) { final List<String> orders = filter.getOrders(); Collections.sort(matched, new Comparator<ProcessInstanceDAO>() { public int compare(ProcessInstanceDAO o1, ProcessInstanceDAO o2) { for (String orderKey: orders) { int result = compareInstanceUsingKey(orderKey, o1, o2); if (result != 0) return result; } return 0; } }); } return matched; } /** * Close this DAO connection. */ public void close() { } public Collection<ProcessDAO> processQuery(ProcessFilter filter) { throw new UnsupportedOperationException("Can't query process configuration using a transient DAO."); } public MessageExchangeDAO createMessageExchange(char dir) { final String id = Long.toString(counter.getAndIncrement()); MessageExchangeDAO mex = new MessageExchangeDAOImpl(dir,id); long now = System.currentTimeMillis(); _mexStore.put(id,mex); _mexAge.put(id, now); if (now > _lastRemoval + (_mexTtl / 10)) { _lastRemoval = now; Object[] oldMexs = _mexAge.keySet().toArray(); for (int i=oldMexs.length-1; i>0; i--) { String oldMex = (String) oldMexs[i]; Long age = _mexAge.get(oldMex); if (age != null && now-age > _mexTtl) { removeMessageExchange(oldMex); _mexAge.remove(oldMex); } } } // Removing right away on rollback onRollback(new Runnable() { public void run() { removeMessageExchange(id); _mexAge.remove(id); } }); return mex; } public MessageExchangeDAO getMessageExchange(String mexid) { return _mexStore.get(mexid); } private int compareInstanceUsingKey(String key, ProcessInstanceDAO instanceDAO1, ProcessInstanceDAO instanceDAO2) { String s1 = null; String s2 = null; boolean ascending = true; String orderKey = key; if (key.startsWith("+") || key.startsWith("-")) { orderKey = key.substring(1, key.length()); if (key.startsWith("-")) ascending = false; } ProcessDAO process1 = getProcess(instanceDAO1.getProcess().getProcessId()); ProcessDAO process2 = getProcess(instanceDAO2.getProcess().getProcessId()); if ("pid".equals(orderKey)) { s1 = process1.getProcessId().toString(); s2 = process2.getProcessId().toString(); } else if ("name".equals(orderKey)) { s1 = process1.getProcessId().getLocalPart(); s2 = process2.getProcessId().getLocalPart(); } else if ("namespace".equals(orderKey)) { s1 = process1.getProcessId().getNamespaceURI(); s2 = process2.getProcessId().getNamespaceURI(); } else if ("version".equals(orderKey)) { s1 = ""+process1.getVersion(); s2 = ""+process2.getVersion(); } else if ("status".equals(orderKey)) { s1 = ""+instanceDAO1.getState(); s2 = ""+instanceDAO2.getState(); } else if ("started".equals(orderKey)) { s1 = ISO8601DateParser.format(instanceDAO1.getCreateTime()); s2 = ISO8601DateParser.format(instanceDAO2.getCreateTime()); } else if ("last-active".equals(orderKey)) { s1 = ISO8601DateParser.format(instanceDAO1.getLastActiveTime()); s2 = ISO8601DateParser.format(instanceDAO2.getLastActiveTime()); } if (ascending) return s1.compareTo(s2); else return s2.compareTo(s1); } private boolean equalsOrWildcardMatch(String s1, String s2) { if (s1 == null || s2 == null) return false; if (s1.equals(s2)) return true; if (s1.endsWith("*")) { if (s2.startsWith(s1.substring(0, s1.length() - 1))) return true; } if (s2.endsWith("*")) { if (s1.startsWith(s2.substring(0, s2.length() - 1))) return true; } return false; } public boolean dateMatch(List<String> dateFilters, Date instanceDate, InstanceFilter filter) { boolean match = true; for (String ddf : dateFilters) { String isoDate = ISO8601DateParser.format(instanceDate); String critDate = Filter.getDateWithoutOp(ddf); if (ddf.startsWith("=")) { if (!isoDate.startsWith(critDate)) match = false; } else if (ddf.startsWith("<=")) { if (!isoDate.startsWith(critDate) && isoDate.compareTo(critDate) > 0) match = false; } else if (ddf.startsWith(">=")) { if (!isoDate.startsWith(critDate) && isoDate.compareTo(critDate) < 0) match = false; } else if (ddf.startsWith("<")) { if (isoDate.compareTo(critDate) > 0) match = false; } else if (ddf.startsWith(">")) { if (isoDate.compareTo(critDate) < 0) match = false; } } return match; } public ScopeDAO getScope(Long siidl) { for (ProcessDaoImpl process : _store.values()) { for (ProcessInstanceDAO instance : process._instances.values()) { if (instance.getScope(siidl) != null) return instance.getScope(siidl); } } return null; } public void insertBpelEvent(BpelEvent event, ProcessDAO processConfiguration, ProcessInstanceDAO instance) { _events.add(event); } public List<Date> bpelEventTimelineQuery(InstanceFilter ifilter, BpelEventFilter efilter) { // TODO : Provide more correct implementation: ArrayList<Date> dates = new ArrayList<Date>(); CollectionsX.transform(dates, _events, new UnaryFunction<BpelEvent,Date>() { public Date apply(BpelEvent x) { return x.getTimestamp(); } }); return dates; } public List<BpelEvent> bpelEventQuery(InstanceFilter ifilter, BpelEventFilter efilter) { // TODO : Provide a more correct (filtering) implementation: return _events; } /** * @see org.apache.ode.bpel.dao.BpelDAOConnection#instanceQuery(String) */ public Collection<ProcessInstanceDAO> instanceQuery(String expression) { //TODO throw new UnsupportedOperationException(); } static void removeMessageExchange(String mexId) { // Cleaning up mex if (__log.isDebugEnabled()) __log.debug("Removing mex " + mexId + " from memory store."); MessageExchangeDAO mex = _mexStore.remove(mexId); if (mex == null) __log.warn("Couldn't find mex " + mexId + " for cleanup."); _mexAge.remove(mexId); } public void defer(final Runnable runnable) { _scheduler.registerSynchronizer(new Scheduler.Synchronizer() { public void afterCompletion(boolean success) { } public void beforeCompletion() { runnable.run(); } }); } public void onRollback(final Runnable runnable) { _scheduler.registerSynchronizer(new Scheduler.Synchronizer() { public void afterCompletion(boolean success) { if (!success) runnable.run(); } public void beforeCompletion() { } }); } }
dinkelaker/hbs4ode
bpel-runtime/src/main/java/org/apache/ode/bpel/memdao/BpelDAOConnectionImpl.java
Java
apache-2.0
14,032
<?php /* * Copyright 2014 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ namespace Google\Service\PagespeedInsights; class Environment extends \Google\Model { public $benchmarkIndex; /** * @var string */ public $hostUserAgent; /** * @var string */ public $networkUserAgent; public function setBenchmarkIndex($benchmarkIndex) { $this->benchmarkIndex = $benchmarkIndex; } public function getBenchmarkIndex() { return $this->benchmarkIndex; } /** * @param string */ public function setHostUserAgent($hostUserAgent) { $this->hostUserAgent = $hostUserAgent; } /** * @return string */ public function getHostUserAgent() { return $this->hostUserAgent; } /** * @param string */ public function setNetworkUserAgent($networkUserAgent) { $this->networkUserAgent = $networkUserAgent; } /** * @return string */ public function getNetworkUserAgent() { return $this->networkUserAgent; } } // Adding a class alias for backwards compatibility with the previous class name. class_alias(Environment::class, 'Google_Service_PagespeedInsights_Environment');
googleapis/google-api-php-client-services
src/PagespeedInsights/Environment.php
PHP
apache-2.0
1,679
/* * 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.ode.daohib.bpel; import org.apache.ode.bpel.dao.ScopeDAO; import org.apache.ode.bpel.dao.XmlDataDAO; import org.apache.ode.daohib.SessionManager; import org.apache.ode.daohib.bpel.hobj.HLargeData; import org.apache.ode.daohib.bpel.hobj.HVariableProperty; import org.apache.ode.daohib.bpel.hobj.HXmlData; import org.apache.ode.utils.DOMUtils; import java.util.Iterator; import org.hibernate.Query; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.Text; /** * Hibernate-based {@link XmlDataDAO} implementation. */ class XmlDataDaoImpl extends HibernateDao implements XmlDataDAO { private static final String QUERY_PROPERTY = "from " + HVariableProperty.class.getName() + " as p where p.xmlData.id = ? and p.name = ?"; private HXmlData _data; private Node _node; /** * @param hobj */ public XmlDataDaoImpl(SessionManager sm, HXmlData hobj) { super(sm, hobj); _data = hobj; } /** * @see org.apache.ode.bpel.dao.XmlDataDAO#isNull() */ public boolean isNull() { return _data.getData() == null; } /** * @see org.apache.ode.bpel.dao.XmlDataDAO#get() */ public Node get() { if(_node == null){ _node = prepare(); } return _node; } /** * @see org.apache.ode.bpel.dao.XmlDataDAO#remove() */ public void remove() { } /** * @see org.apache.ode.bpel.dao.XmlDataDAO#set(org.w3c.dom.Node) */ public void set(Node val) { _node = val; _data.setSimpleType(!(val instanceof Element)); if (_data.getData() != null) _sm.getSession().delete(_data.getData()); HLargeData ld = new HLargeData(); if(_data.isSimpleType()) { ld.setBinary(_node.getNodeValue().getBytes()); _data.setData(ld); } else { ld.setBinary(DOMUtils.domToString(_node).getBytes()); _data.setData(ld); } getSession().save(ld); getSession().saveOrUpdate(_data); } /** * @see org.apache.ode.bpel.dao.XmlDataDAO#getProperty(java.lang.String) */ public String getProperty(String propertyName) { HVariableProperty p = _getProperty(propertyName); return p == null ? null : p.getValue(); } /** * @see org.apache.ode.bpel.dao.XmlDataDAO#setProperty(java.lang.String, java.lang.String) */ public void setProperty(String pname, String pvalue) { HVariableProperty p = _getProperty(pname); if(p == null){ p = new HVariableProperty(_data, pname, pvalue); getSession().save(p); // _data.addProperty(p); }else{ p.setValue(pvalue); getSession().update(p); } } /** * @see org.apache.ode.bpel.dao.XmlDataDAO#getScopeDAO() */ public ScopeDAO getScopeDAO() { return new ScopeDaoImpl(_sm,_data.getScope()); } private HVariableProperty _getProperty(String propertyName){ Iterator iter; Query qry = getSession().createQuery(QUERY_PROPERTY); qry.setLong(0, _data.getId()); qry.setString(1, propertyName); iter = qry.iterate(); return iter.hasNext() ? (HVariableProperty)iter.next() : null; } private Node prepare(){ if(_data.getData() == null) return null; String data = _data.getData().getText(); if(_data.isSimpleType()){ Document d = DOMUtils.newDocument(); // we create a dummy wrapper element // prevents some apps from complaining // when text node is not actual child of document Element e = d.createElement("text-node-wrapper"); Text tnode = d.createTextNode(data); d.appendChild(e); e.appendChild(tnode); return tnode; }else{ try{ return DOMUtils.stringToDOM(data); }catch(Exception e){ throw new RuntimeException(e); } } } public String getName() { return _data.getName(); } }
dinkelaker/hbs4ode
dao-hibernate/src/main/java/org/apache/ode/daohib/bpel/XmlDataDaoImpl.java
Java
apache-2.0
5,098
package com.github.vedenin.rus.arrays; import java.util.Arrays; import java.util.stream.DoubleStream; import java.util.stream.IntStream; /** * Тестирование превращения массива в строку для печати * * Created by vedenin on 04.02.16. */ public class ConvertArrayToStringAndPrintTest { public static void main(String[] s) throws Exception { /* (JDK 5) Использование Arrays.toString и Arrays.deepToString */ // simple array String[] array = new String[]{"John", "Mary", "Bob"}; System.out.println(Arrays.toString(array)); // Напечатает: [John, Mary, Bob] // nested array String[][] deepArray = new String[][]{{"John", "Mary"}, {"Alice", "Bob"}}; System.out.println(Arrays.toString(deepArray)); // Напечатает: [[Ljava.lang.String;@106d69c, [Ljava.lang.String;@52e922] System.out.println(Arrays.deepToString(deepArray)); // Напечатает: [[John, Mary], [Alice, Bob]] //double Array double[] arrayGiven = {7.0, 9.0, 5.0, 1.0, 3.0}; System.out.println(Arrays.toString(arrayGiven)); // Напечатает: [7.0, 9.0, 5.0, 1.0, 3.0 ] //int Array int[] arrayInt = {7, 9, 5, 1, 3}; System.out.println(Arrays.toString(arrayInt)); // Напечатает: [7, 9, 5, 1, 3 ] /* (JDK 8) Использование Stream API */ Arrays.asList(array).stream().forEach(System.out::print); // Напечатает: JohnMaryBob System.out.println(); Arrays.asList(deepArray).stream().forEach(s1 -> Arrays.asList(s1).stream().forEach(System.out::print)); System.out.println(); DoubleStream.of(arrayGiven).forEach((d) -> System.out.print(d + " ")); // Напечатает: 7.0 9.0 5.0 1.0 3.0 System.out.println(); IntStream.of(arrayInt).forEach(System.out::print); // Напечатает: 79513 } }
Vedenin/java_in_examples
other/src/main/java/com/github/vedenin/rus/arrays/ConvertArrayToStringAndPrintTest.java
Java
apache-2.0
1,973
/* * 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.language; import java.util.List; import org.apache.camel.Exchange; import org.apache.camel.ExchangeTestSupport; import org.apache.camel.Expression; import org.apache.camel.language.tokenizer.TokenizeLanguage; import org.apache.camel.model.language.TokenizerExpression; import org.junit.Test; public class TokenizerTest extends ExchangeTestSupport { @Override protected void populateExchange(Exchange exchange) { super.populateExchange(exchange); exchange.getIn().setHeader("names", "Claus,James,Willem"); } @Test public void testTokenizeHeaderWithStringContructor() throws Exception { TokenizerExpression definition = new TokenizerExpression(","); definition.setHeaderName("names"); List<?> names = definition.createExpression(exchange.getContext()).evaluate(exchange, List.class); assertEquals(3, names.size()); assertEquals("Claus", names.get(0)); assertEquals("James", names.get(1)); assertEquals("Willem", names.get(2)); } @Test public void testTokenizeHeader() throws Exception { Expression exp = TokenizeLanguage.tokenize("names", ","); List<?> names = exp.evaluate(exchange, List.class); assertEquals(3, names.size()); assertEquals("Claus", names.get(0)); assertEquals("James", names.get(1)); assertEquals("Willem", names.get(2)); } @Test public void testTokenizeBody() throws Exception { Expression exp = TokenizeLanguage.tokenize(","); exchange.getIn().setBody("Hadrian,Charles"); List<?> names = exp.evaluate(exchange, List.class); assertEquals(2, names.size()); assertEquals("Hadrian", names.get(0)); assertEquals("Charles", names.get(1)); } @Test public void testTokenizeBodyRegEx() throws Exception { Expression exp = TokenizeLanguage.tokenize("(\\W+)\\s*", true); exchange.getIn().setBody("The little fox"); List<?> names = exp.evaluate(exchange, List.class); assertEquals(3, names.size()); assertEquals("The", names.get(0)); assertEquals("little", names.get(1)); assertEquals("fox", names.get(2)); } @Test public void testTokenizeHeaderRegEx() throws Exception { Expression exp = TokenizeLanguage.tokenize("quote", "(\\W+)\\s*", true); exchange.getIn().setHeader("quote", "Camel rocks"); List<?> names = exp.evaluate(exchange, List.class); assertEquals(2, names.size()); assertEquals("Camel", names.get(0)); assertEquals("rocks", names.get(1)); } @Test public void testTokenizeManualConfiguration() throws Exception { TokenizeLanguage lan = new TokenizeLanguage(); lan.setHeaderName("names"); lan.setRegex(false); lan.setToken(","); Expression exp = lan.createExpression(); List<?> names = exp.evaluate(exchange, List.class); assertEquals(3, names.size()); assertEquals("Claus", names.get(0)); assertEquals("James", names.get(1)); assertEquals("Willem", names.get(2)); assertEquals("names", lan.getHeaderName()); assertEquals(",", lan.getToken()); assertEquals(false, lan.isRegex()); assertEquals(false, lan.isSingleton()); } @Test public void testTokenizePairSpecial() throws Exception { Expression exp = TokenizeLanguage.tokenizePair("!", "@", false); exchange.getIn().setBody("2011-11-11\n!James@!Claus@\n2 records"); List<?> names = exp.evaluate(exchange, List.class); assertEquals(2, names.size()); assertEquals("James", names.get(0)); assertEquals("Claus", names.get(1)); } @Test public void testTokenizePair() throws Exception { Expression exp = TokenizeLanguage.tokenizePair("[START]", "[END]", false); exchange.getIn().setBody("2011-11-11\n[START]James[END]\n[START]Claus[END]\n2 records"); List<?> names = exp.evaluate(exchange, List.class); assertEquals(2, names.size()); assertEquals("James", names.get(0)); assertEquals("Claus", names.get(1)); } @Test public void testTokenizePairSimple() throws Exception { Expression exp = TokenizeLanguage.tokenizePair("${header.foo}", "${header.bar}", false); exchange.getIn().setHeader("foo", "[START]"); exchange.getIn().setHeader("bar", "[END]"); exchange.getIn().setBody("2011-11-11\n[START]James[END]\n[START]Claus[END]\n2 records"); List<?> names = exp.evaluate(exchange, List.class); assertEquals(2, names.size()); assertEquals("James", names.get(0)); assertEquals("Claus", names.get(1)); } @Test public void testTokenizePairIncludeTokens() throws Exception { Expression exp = TokenizeLanguage.tokenizePair("[START]", "[END]", true); exchange.getIn().setBody("2011-11-11\n[START]James[END]\n[START]Claus[END]\n2 records"); List<?> names = exp.evaluate(exchange, List.class); assertEquals(2, names.size()); assertEquals("[START]James[END]", names.get(0)); assertEquals("[START]Claus[END]", names.get(1)); } @Test public void testTokenizeXMLPair() throws Exception { Expression exp = TokenizeLanguage.tokenizeXML("<person>", null); exchange.getIn().setBody("<persons><person>James</person><person>Claus</person><person>Jonathan</person><person>Hadrian</person></persons>"); List<?> names = exp.evaluate(exchange, List.class); assertEquals(4, names.size()); assertEquals("<person>James</person>", names.get(0)); assertEquals("<person>Claus</person>", names.get(1)); assertEquals("<person>Jonathan</person>", names.get(2)); assertEquals("<person>Hadrian</person>", names.get(3)); } @Test public void testTokenizeXMLPairSimple() throws Exception { Expression exp = TokenizeLanguage.tokenizeXML("${header.foo}", null); exchange.getIn().setHeader("foo", "<person>"); exchange.getIn().setBody("<persons><person>James</person><person>Claus</person><person>Jonathan</person><person>Hadrian</person></persons>"); List<?> names = exp.evaluate(exchange, List.class); assertEquals(4, names.size()); assertEquals("<person>James</person>", names.get(0)); assertEquals("<person>Claus</person>", names.get(1)); assertEquals("<person>Jonathan</person>", names.get(2)); assertEquals("<person>Hadrian</person>", names.get(3)); } @Test public void testTokenizeXMLPairNoXMLTag() throws Exception { Expression exp = TokenizeLanguage.tokenizeXML("person", null); exchange.getIn().setBody("<persons><person>James</person><person>Claus</person><person>Jonathan</person><person>Hadrian</person></persons>"); List<?> names = exp.evaluate(exchange, List.class); assertEquals(4, names.size()); assertEquals("<person>James</person>", names.get(0)); assertEquals("<person>Claus</person>", names.get(1)); assertEquals("<person>Jonathan</person>", names.get(2)); assertEquals("<person>Hadrian</person>", names.get(3)); } @Test public void testTokenizeXMLPairWithNoise() throws Exception { Expression exp = TokenizeLanguage.tokenizeXML("<person>", null); exchange.getIn().setBody("<?xml version=\"1.0\"?><!-- bla bla --><persons>\n<person>James</person>\n<person>Claus</person>\n" + "<!-- more bla bla --><person>Jonathan</person>\n<person>Hadrian</person>\n</persons> "); List<?> names = exp.evaluate(exchange, List.class); assertEquals(4, names.size()); assertEquals("<person>James</person>", names.get(0)); assertEquals("<person>Claus</person>", names.get(1)); assertEquals("<person>Jonathan</person>", names.get(2)); assertEquals("<person>Hadrian</person>", names.get(3)); } @Test public void testTokenizeXMLPairEmpty() throws Exception { Expression exp = TokenizeLanguage.tokenizeXML("<person>", null); exchange.getIn().setBody("<?xml version=\"1.0\"?><!-- bla bla --><persons></persons> "); List<?> names = exp.evaluate(exchange, List.class); assertEquals(0, names.size()); } @Test public void testTokenizeXMLPairNoData() throws Exception { Expression exp = TokenizeLanguage.tokenizeXML("<person>", null); exchange.getIn().setBody(""); List<?> names = exp.evaluate(exchange, List.class); assertEquals(0, names.size()); } @Test public void testTokenizeXMLPairNullData() throws Exception { Expression exp = TokenizeLanguage.tokenizeXML("<person>", null); exchange.getIn().setBody(null); List<?> names = exp.evaluate(exchange, List.class); assertNull(names); } @Test public void testTokenizeXMLPairWithSimilarChildNames() throws Exception { Expression exp = TokenizeLanguage.tokenizeXML("Trip", "Trips"); exchange.getIn().setBody("<?xml version='1.0' encoding='UTF-8'?>\n<Trips>\n<Trip>\n<TripType>\n</TripType>\n</Trip>\n</Trips>"); List<?> names = exp.evaluate(exchange, List.class); assertEquals(1, names.size()); } @Test public void testTokenizeXMLPairWithDefaultNamespace() throws Exception { Expression exp = TokenizeLanguage.tokenizeXML("<person>", "<persons>"); exchange.getIn().setBody("<?xml version=\"1.0\"?><persons xmlns=\"http:acme.com/persons\">\n<person>James</person>\n<person>Claus</person>\n" + "<person>Jonathan</person>\n<person>Hadrian</person>\n</persons>\n"); List<?> names = exp.evaluate(exchange, List.class); assertEquals(4, names.size()); assertEquals("<person xmlns=\"http:acme.com/persons\">James</person>", names.get(0)); assertEquals("<person xmlns=\"http:acme.com/persons\">Claus</person>", names.get(1)); assertEquals("<person xmlns=\"http:acme.com/persons\">Jonathan</person>", names.get(2)); assertEquals("<person xmlns=\"http:acme.com/persons\">Hadrian</person>", names.get(3)); } @Test public void testTokenizeXMLPairWithDefaultNamespaceNotInherit() throws Exception { Expression exp = TokenizeLanguage.tokenizeXML("<person>", null); exchange.getIn().setBody("<?xml version=\"1.0\"?><persons xmlns=\"http:acme.com/persons\">\n<person>James</person>\n<person>Claus</person>\n" + "<person>Jonathan</person>\n<person>Hadrian</person>\n</persons>\n"); List<?> names = exp.evaluate(exchange, List.class); assertEquals(4, names.size()); assertEquals("<person>James</person>", names.get(0)); assertEquals("<person>Claus</person>", names.get(1)); assertEquals("<person>Jonathan</person>", names.get(2)); assertEquals("<person>Hadrian</person>", names.get(3)); } @Test public void testTokenizeXMLPairWithDefaultAndFooNamespace() throws Exception { Expression exp = TokenizeLanguage.tokenizeXML("<person>", "<persons>"); exchange.getIn().setBody("<?xml version=\"1.0\"?><persons xmlns=\"http:acme.com/persons\" xmlns:foo=\"http:foo.com\">\n<person>James</person>\n<person>Claus</person>\n" + "<person>Jonathan</person>\n<person>Hadrian</person>\n</persons>\n"); List<?> names = exp.evaluate(exchange, List.class); assertEquals(4, names.size()); assertEquals("<person xmlns=\"http:acme.com/persons\" xmlns:foo=\"http:foo.com\">James</person>", names.get(0)); assertEquals("<person xmlns=\"http:acme.com/persons\" xmlns:foo=\"http:foo.com\">Claus</person>", names.get(1)); assertEquals("<person xmlns=\"http:acme.com/persons\" xmlns:foo=\"http:foo.com\">Jonathan</person>", names.get(2)); assertEquals("<person xmlns=\"http:acme.com/persons\" xmlns:foo=\"http:foo.com\">Hadrian</person>", names.get(3)); } @Test public void testTokenizeXMLPairWithLocalNamespace() throws Exception { Expression exp = TokenizeLanguage.tokenizeXML("<person>", null); exchange.getIn().setBody("<?xml version=\"1.0\"?><persons>\n<person xmlns=\"http:acme.com/persons\">James</person>\n<person xmlns=\"http:acme.com/persons\">Claus</person>\n" + "<person xmlns=\"http:acme.com/persons\">Jonathan</person>\n<person xmlns=\"http:acme.com/persons\">Hadrian</person>\n</persons>\n"); List<?> names = exp.evaluate(exchange, List.class); assertEquals(4, names.size()); assertEquals("<person xmlns=\"http:acme.com/persons\">James</person>", names.get(0)); assertEquals("<person xmlns=\"http:acme.com/persons\">Claus</person>", names.get(1)); assertEquals("<person xmlns=\"http:acme.com/persons\">Jonathan</person>", names.get(2)); assertEquals("<person xmlns=\"http:acme.com/persons\">Hadrian</person>", names.get(3)); } @Test public void testTokenizeXMLPairWithLocalAndInheritedNamespace() throws Exception { Expression exp = TokenizeLanguage.tokenizeXML("<person>", "<persons>"); exchange.getIn().setBody("<?xml version=\"1.0\"?><persons xmlns=\"http:acme.com/persons\">\n<person xmlns:foo=\"http:foo.com\">James</person>\n<person>Claus</person>\n" + "<person>Jonathan</person>\n<person xmlns:bar=\"http:bar.com\">Hadrian</person>\n</persons>\n"); List<?> names = exp.evaluate(exchange, List.class); assertEquals(4, names.size()); assertEquals("<person xmlns:foo=\"http:foo.com\" xmlns=\"http:acme.com/persons\">James</person>", names.get(0)); assertEquals("<person xmlns=\"http:acme.com/persons\">Claus</person>", names.get(1)); assertEquals("<person xmlns=\"http:acme.com/persons\">Jonathan</person>", names.get(2)); assertEquals("<person xmlns:bar=\"http:bar.com\" xmlns=\"http:acme.com/persons\">Hadrian</person>", names.get(3)); } @Test public void testTokenizeXMLPairWithLocalAndNotInheritedNamespace() throws Exception { Expression exp = TokenizeLanguage.tokenizeXML("<person>", null); exchange.getIn().setBody("<?xml version=\"1.0\"?><persons xmlns=\"http:acme.com/persons\">\n<person xmlns:foo=\"http:foo.com\">James</person>\n" + "<person>Claus</person>\n<person>Jonathan</person>\n<person xmlns:bar=\"http:bar.com\">Hadrian</person>\n</persons>\n"); List<?> names = exp.evaluate(exchange, List.class); assertEquals(4, names.size()); assertEquals("<person xmlns:foo=\"http:foo.com\">James</person>", names.get(0)); assertEquals("<person>Claus</person>", names.get(1)); assertEquals("<person>Jonathan</person>", names.get(2)); assertEquals("<person xmlns:bar=\"http:bar.com\">Hadrian</person>", names.get(3)); } @Test public void testTokenizeXMLPairWithAttributes() throws Exception { Expression exp = TokenizeLanguage.tokenizeXML("<person>", null); exchange.getIn().setBody("<persons><person id=\"1\">James</person><person id=\"2\">Claus</person><person id=\"3\">Jonathan</person>" + "<person id=\"4\">Hadrian</person></persons>"); List<?> names = exp.evaluate(exchange, List.class); assertEquals(4, names.size()); assertEquals("<person id=\"1\">James</person>", names.get(0)); assertEquals("<person id=\"2\">Claus</person>", names.get(1)); assertEquals("<person id=\"3\">Jonathan</person>", names.get(2)); assertEquals("<person id=\"4\">Hadrian</person>", names.get(3)); } @Test public void testTokenizeXMLPairWithAttributesInheritNamespace() throws Exception { Expression exp = TokenizeLanguage.tokenizeXML("<person>", "<persons>"); exchange.getIn().setBody("<persons xmlns=\"http:acme.com/persons\"><person id=\"1\">James</person><person id=\"2\">Claus</person>" + "<person id=\"3\">Jonathan</person><person id=\"4\">Hadrian</person></persons>"); List<?> names = exp.evaluate(exchange, List.class); assertEquals(4, names.size()); assertEquals("<person id=\"1\" xmlns=\"http:acme.com/persons\">James</person>", names.get(0)); assertEquals("<person id=\"2\" xmlns=\"http:acme.com/persons\">Claus</person>", names.get(1)); assertEquals("<person id=\"3\" xmlns=\"http:acme.com/persons\">Jonathan</person>", names.get(2)); assertEquals("<person id=\"4\" xmlns=\"http:acme.com/persons\">Hadrian</person>", names.get(3)); } @Test public void testTokenizeXMLPairWithAttributes2InheritNamespace() throws Exception { Expression exp = TokenizeLanguage.tokenizeXML("<person>", "<persons>"); exchange.getIn().setBody("<persons riders=\"true\" xmlns=\"http:acme.com/persons\"><person id=\"1\">James</person><person id=\"2\">Claus</person>" + "<person id=\"3\">Jonathan</person><person id=\"4\">Hadrian</person></persons>"); List<?> names = exp.evaluate(exchange, List.class); assertEquals(4, names.size()); assertEquals("<person id=\"1\" xmlns=\"http:acme.com/persons\">James</person>", names.get(0)); assertEquals("<person id=\"2\" xmlns=\"http:acme.com/persons\">Claus</person>", names.get(1)); assertEquals("<person id=\"3\" xmlns=\"http:acme.com/persons\">Jonathan</person>", names.get(2)); assertEquals("<person id=\"4\" xmlns=\"http:acme.com/persons\">Hadrian</person>", names.get(3)); } }
Fabryprog/camel
core/camel-core/src/test/java/org/apache/camel/language/TokenizerTest.java
Java
apache-2.0
18,428
using System; using Nest; using Tests.Framework.Integration; using Tests.Framework.MockData; using static Nest.Infer; namespace Tests.Aggregations.Bucket.Children { /** * A special single bucket aggregation that enables aggregating from buckets on parent document types to * buckets on child documents. * * Be sure to read the Elasticsearch documentation on {ref_current}/search-aggregations-bucket-children-aggregation.html[Children Aggregation] */ public class ChildrenAggregationUsageTests : AggregationUsageTestBase { public ChildrenAggregationUsageTests(ReadOnlyCluster i, EndpointUsage usage) : base(i, usage) { } protected override object ExpectJson => new { aggs = new { name_of_child_agg = new { children = new { type = "commits" }, aggs = new { average_per_child = new { avg = new { field = "confidenceFactor" } }, max_per_child = new { max = new { field = "confidenceFactor" } } } } } }; protected override Func<SearchDescriptor<Project>, ISearchRequest> Fluent => s => s .Aggregations(aggs => aggs .Children<CommitActivity>("name_of_child_agg", child => child .Aggregations(childAggs => childAggs .Average("average_per_child", avg => avg.Field(p => p.ConfidenceFactor)) .Max("max_per_child", avg => avg.Field(p => p.ConfidenceFactor)) ) ) ); protected override SearchRequest<Project> Initializer => new SearchRequest<Project> { Aggregations = new ChildrenAggregation("name_of_child_agg", typeof(CommitActivity)) { Aggregations = new AverageAggregation("average_per_child", "confidenceFactor") && new MaxAggregation("max_per_child", "confidenceFactor") } }; } }
UdiBen/elasticsearch-net
src/Tests/Aggregations/Bucket/Children/ChildrenAggregationUsageTests.cs
C#
apache-2.0
1,771
/* * Copyright 2018 LINE Corporation * * LINE Corporation licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.linecorp.armeria.server; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.collect.ImmutableMap.toImmutableMap; import static com.linecorp.armeria.common.HttpParameters.EMPTY_PARAMETERS; import static com.linecorp.armeria.internal.DefaultValues.getSpecifiedValue; import static com.linecorp.armeria.server.AnnotatedElementNameUtil.findName; import static com.linecorp.armeria.server.AnnotatedHttpServiceTypeUtil.normalizeContainerType; import static com.linecorp.armeria.server.AnnotatedHttpServiceTypeUtil.stringToType; import static com.linecorp.armeria.server.AnnotatedHttpServiceTypeUtil.validateElementType; import static java.util.Objects.requireNonNull; import java.lang.annotation.Annotation; import java.lang.reflect.AnnotatedElement; import java.lang.reflect.Constructor; import java.lang.reflect.Executable; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Parameter; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.nio.charset.StandardCharsets; import java.util.AbstractMap.SimpleImmutableEntry; import java.util.Arrays; import java.util.Collection; import java.util.EnumSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Optional; import java.util.Set; import java.util.concurrent.ConcurrentMap; import java.util.function.BiFunction; import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Collectors; import javax.annotation.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Ascii; import com.google.common.base.MoreObjects; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.MapMaker; import com.linecorp.armeria.common.AggregatedHttpMessage; import com.linecorp.armeria.common.HttpHeaderNames; import com.linecorp.armeria.common.HttpParameters; import com.linecorp.armeria.common.HttpRequest; import com.linecorp.armeria.common.MediaType; import com.linecorp.armeria.common.Request; import com.linecorp.armeria.common.RequestContext; import com.linecorp.armeria.common.util.Exceptions; import com.linecorp.armeria.internal.FallthroughException; import com.linecorp.armeria.server.AnnotatedBeanFactory.BeanFactoryId; import com.linecorp.armeria.server.annotation.ByteArrayRequestConverterFunction; import com.linecorp.armeria.server.annotation.Cookies; import com.linecorp.armeria.server.annotation.Default; import com.linecorp.armeria.server.annotation.Header; import com.linecorp.armeria.server.annotation.JacksonRequestConverterFunction; import com.linecorp.armeria.server.annotation.Param; import com.linecorp.armeria.server.annotation.RequestConverterFunction; import com.linecorp.armeria.server.annotation.RequestObject; import com.linecorp.armeria.server.annotation.StringRequestConverterFunction; import io.netty.handler.codec.http.HttpConstants; import io.netty.handler.codec.http.QueryStringDecoder; import io.netty.handler.codec.http.cookie.Cookie; import io.netty.handler.codec.http.cookie.ServerCookieDecoder; import io.netty.util.AsciiString; final class AnnotatedValueResolver { private static final Logger logger = LoggerFactory.getLogger(AnnotatedValueResolver.class); private static final List<RequestObjectResolver> defaultRequestConverters = ImmutableList.of((resolverContext, expectedResultType, beanFactoryId) -> AnnotatedBeanFactory.find(beanFactoryId) .orElseThrow(RequestConverterFunction::fallthrough) .apply(resolverContext), RequestObjectResolver.of(new JacksonRequestConverterFunction()), RequestObjectResolver.of(new StringRequestConverterFunction()), RequestObjectResolver.of(new ByteArrayRequestConverterFunction())); private static final Object[] emptyArguments = new Object[0]; /** * Returns an array of arguments which are resolved by each {@link AnnotatedValueResolver} of the * specified {@code resolvers}. */ static Object[] toArguments(List<AnnotatedValueResolver> resolvers, ResolverContext resolverContext) { requireNonNull(resolvers, "resolvers"); requireNonNull(resolverContext, "resolverContext"); if (resolvers.isEmpty()) { return emptyArguments; } return resolvers.stream().map(resolver -> resolver.resolve(resolverContext)).toArray(); } /** * Returns a list of {@link RequestObjectResolver} that default request converters are added. */ static List<RequestObjectResolver> toRequestObjectResolvers(List<RequestConverterFunction> converters) { final ImmutableList.Builder<RequestObjectResolver> builder = ImmutableList.builder(); // Wrap every converters received from a user with a default object resolver. converters.stream().map(RequestObjectResolver::of).forEach(builder::add); builder.addAll(defaultRequestConverters); return builder.build(); } /** * Returns a list of {@link AnnotatedValueResolver} which is constructed with the specified * {@link Executable}, {@code pathParams} and {@code objectResolvers}. The {@link Executable} can be * one of {@link Constructor} or {@link Method}. */ static List<AnnotatedValueResolver> of(Executable constructorOrMethod, Set<String> pathParams, List<RequestObjectResolver> objectResolvers) { final Parameter[] parameters = constructorOrMethod.getParameters(); if (parameters.length == 0) { throw new NoParameterException(constructorOrMethod.toGenericString()); } // // Try to check whether it is an annotated constructor or method first. e.g. // // @Param // void setter(String name) { ... } // // In this case, we need to retrieve the value of @Param annotation from 'name' parameter, // not the constructor or method. Also 'String' type is used for the parameter. // final Optional<AnnotatedValueResolver> resolver; if (isAnnotationPresent(constructorOrMethod)) { // // Only allow a single parameter on an annotated method. The followings cause an error: // // @Param // void setter(String name, int id, String address) { ... } // // @Param // void setter() { ... } // if (parameters.length != 1) { throw new IllegalArgumentException("Only one parameter is allowed to an annotated method: " + constructorOrMethod.toGenericString()); } // // Filter out like the following case: // // @Param // void setter(@Header String name) { ... } // if (isAnnotationPresent(parameters[0])) { throw new IllegalArgumentException("Both a method and parameter are annotated: " + constructorOrMethod.toGenericString()); } resolver = of(constructorOrMethod, parameters[0], parameters[0].getType(), pathParams, objectResolvers); } else { // // There's no annotation. So there should be no @Default annotation, too. // e.g. // @Default("a") // void method1(ServiceRequestContext) { ... } // if (constructorOrMethod.isAnnotationPresent(Default.class)) { throw new IllegalArgumentException( '@' + Default.class.getSimpleName() + " is not supported for: " + constructorOrMethod.toGenericString()); } resolver = Optional.empty(); } // // If there is no annotation on the constructor or method, try to check whether it has // annotated parameters. e.g. // // void setter1(@Param String name) { ... } // void setter2(@Param String name, @Header List<String> xForwardedFor) { ... } // final List<AnnotatedValueResolver> list = resolver.<List<AnnotatedValueResolver>>map(ImmutableList::of).orElseGet( () -> Arrays.stream(parameters) .map(p -> of(p, pathParams, objectResolvers)) .filter(Optional::isPresent) .map(Optional::get) .collect(Collectors.toList())); if (list.isEmpty()) { throw new NoAnnotatedParameterException(constructorOrMethod.toGenericString()); } if (list.size() != parameters.length) { throw new IllegalArgumentException("Unsupported parameter exists: " + constructorOrMethod.toGenericString()); } return list; } /** * Returns a list of {@link AnnotatedValueResolver} which is constructed with the specified * {@link Parameter}, {@code pathParams} and {@code objectResolvers}. */ static Optional<AnnotatedValueResolver> of(Parameter parameter, Set<String> pathParams, List<RequestObjectResolver> objectResolvers) { return of(parameter, parameter, parameter.getType(), pathParams, objectResolvers); } /** * Returns a list of {@link AnnotatedValueResolver} which is constructed with the specified * {@link Field}, {@code pathParams} and {@code objectResolvers}. */ static Optional<AnnotatedValueResolver> of(Field field, Set<String> pathParams, List<RequestObjectResolver> objectResolvers) { return of(field, field, field.getType(), pathParams, objectResolvers); } /** * Creates a new {@link AnnotatedValueResolver} instance if the specified {@code annotatedElement} is * a component of {@link AnnotatedHttpService}. * * @param annotatedElement an element which is annotated with a value specifier such as {@link Param} and * {@link Header}. * @param typeElement an element which is used for retrieving its type and name. * @param type a type of the given {@link Parameter} or {@link Field}. It is a type of * the specified {@code typeElement} parameter. * @param pathParams a set of path variables. * @param objectResolvers a list of {@link RequestObjectResolver} to be evaluated for the objects which * are annotated with {@link RequestObject} annotation. */ private static Optional<AnnotatedValueResolver> of(AnnotatedElement annotatedElement, AnnotatedElement typeElement, Class<?> type, Set<String> pathParams, List<RequestObjectResolver> objectResolvers) { requireNonNull(annotatedElement, "annotatedElement"); requireNonNull(typeElement, "typeElement"); requireNonNull(type, "type"); requireNonNull(pathParams, "pathParams"); requireNonNull(objectResolvers, "objectResolvers"); final Param param = annotatedElement.getAnnotation(Param.class); if (param != null) { final String name = findName(param, typeElement); if (pathParams.contains(name)) { return Optional.of(ofPathVariable(param, name, annotatedElement, typeElement, type)); } else { return Optional.of(ofHttpParameter(param, name, annotatedElement, typeElement, type)); } } final Header header = annotatedElement.getAnnotation(Header.class); if (header != null) { return Optional.of(ofHeader(header, annotatedElement, typeElement, type)); } final RequestObject requestObject = annotatedElement.getAnnotation(RequestObject.class); if (requestObject != null) { return Optional.of(ofRequestObject(requestObject, annotatedElement, type, pathParams, objectResolvers)); } // There should be no '@Default' annotation on 'annotatedElement' if 'annotatedElement' is // different from 'typeElement', because it was checked before calling this method. // So, 'typeElement' should be used when finding an injectable type because we need to check // syntactic errors like below: // // void method1(@Default("a") ServiceRequestContext) { ... } // return Optional.ofNullable(ofInjectableTypes(typeElement, type)); } private static boolean isAnnotationPresent(AnnotatedElement element) { return element.isAnnotationPresent(Param.class) || element.isAnnotationPresent(Header.class) || element.isAnnotationPresent(RequestObject.class); } private static AnnotatedValueResolver ofPathVariable(Param param, String name, AnnotatedElement annotatedElement, AnnotatedElement typeElement, Class<?> type) { return builder(annotatedElement, type) .annotation(param) .httpElementName(name) .typeElement(typeElement) .pathVariable(true) .resolver(resolver(ctx -> ctx.context().pathParam(name))) .build(); } private static AnnotatedValueResolver ofHttpParameter(Param param, String name, AnnotatedElement annotatedElement, AnnotatedElement typeElement, Class<?> type) { return builder(annotatedElement, type) .annotation(param) .httpElementName(name) .typeElement(typeElement) .supportOptional(true) .supportDefault(true) .supportContainer(true) .aggregation(AggregationStrategy.FOR_FORM_DATA) .resolver(resolver(ctx -> ctx.httpParameters().getAll(name), () -> "Cannot resolve a value from HTTP parameter: " + name)) .build(); } private static AnnotatedValueResolver ofHeader(Header header, AnnotatedElement annotatedElement, AnnotatedElement typeElement, Class<?> type) { final String name = findName(header, typeElement); return builder(annotatedElement, type) .annotation(header) .httpElementName(name) .typeElement(typeElement) .supportOptional(true) .supportDefault(true) .supportContainer(true) .resolver(resolver( ctx -> ctx.request().headers().getAll(AsciiString.of(name)), () -> "Cannot resolve a value from HTTP header: " + name)) .build(); } private static AnnotatedValueResolver ofRequestObject(RequestObject requestObject, AnnotatedElement annotatedElement, Class<?> type, Set<String> pathParams, List<RequestObjectResolver> objectResolvers) { final List<RequestObjectResolver> newObjectResolvers; if (requestObject.value() != RequestConverterFunction.class) { // There is a converter which is specified by a user. final RequestConverterFunction requestConverterFunction = AnnotatedHttpServiceFactory.getInstance(requestObject, RequestConverterFunction.class); newObjectResolvers = ImmutableList.<RequestObjectResolver>builder() .add(RequestObjectResolver.of(requestConverterFunction)) .addAll(objectResolvers) .build(); } else { newObjectResolvers = objectResolvers; } // To do recursive resolution like a bean inside another bean, the original object resolvers should // be passed into the AnnotatedBeanFactory#register. final BeanFactoryId beanFactoryId = AnnotatedBeanFactory.register(type, pathParams, objectResolvers); return builder(annotatedElement, type) .annotation(requestObject) .aggregation(AggregationStrategy.ALWAYS) .resolver(resolver(newObjectResolvers, beanFactoryId)) .build(); } @Nullable private static AnnotatedValueResolver ofInjectableTypes(AnnotatedElement annotatedElement, Class<?> type) { if (type == RequestContext.class || type == ServiceRequestContext.class) { return builder(annotatedElement, type) .resolver((unused, ctx) -> ctx.context()) .build(); } if (type == Request.class || type == HttpRequest.class) { return builder(annotatedElement, type) .resolver((unused, ctx) -> ctx.request()) .build(); } if (type == AggregatedHttpMessage.class) { return builder(annotatedElement, AggregatedHttpMessage.class) .resolver((unused, ctx) -> ctx.message()) .aggregation(AggregationStrategy.ALWAYS) .build(); } if (type == HttpParameters.class) { return builder(annotatedElement, HttpParameters.class) .resolver((unused, ctx) -> ctx.httpParameters()) .aggregation(AggregationStrategy.FOR_FORM_DATA) .build(); } if (type == Cookies.class) { return builder(annotatedElement, Cookies.class) .resolver((unused, ctx) -> { final List<String> values = ctx.request().headers().getAll(HttpHeaderNames.COOKIE); if (values.isEmpty()) { return Cookies.copyOf(ImmutableSet.of()); } final ImmutableSet.Builder<Cookie> cookies = ImmutableSet.builder(); values.stream() .map(ServerCookieDecoder.STRICT::decode) .forEach(cookies::addAll); return Cookies.copyOf(cookies.build()); }) .build(); } // Unsupported type. return null; } /** * Returns a single value resolver which retrieves a value from the specified {@code getter} * and converts it. */ private static BiFunction<AnnotatedValueResolver, ResolverContext, Object> resolver(Function<ResolverContext, String> getter) { return (resolver, ctx) -> resolver.convert(getter.apply(ctx)); } /** * Returns a collection value resolver which retrieves a list of string from the specified {@code getter} * and adds them to the specified collection data type. */ private static BiFunction<AnnotatedValueResolver, ResolverContext, Object> resolver(Function<ResolverContext, List<String>> getter, Supplier<String> failureMessageSupplier) { return (resolver, ctx) -> { final List<String> values = getter.apply(ctx); if (!resolver.hasContainer()) { if (values != null && !values.isEmpty()) { return resolver.convert(values.get(0)); } return resolver.defaultOrException(); } try { assert resolver.containerType() != null; @SuppressWarnings("unchecked") final Collection<Object> resolvedValues = (Collection<Object>) resolver.containerType().newInstance(); // Do not convert value here because the element type is String. if (values != null && !values.isEmpty()) { values.stream().map(resolver::convert).forEach(resolvedValues::add); } else { final Object defaultValue = resolver.defaultOrException(); if (defaultValue != null) { resolvedValues.add(defaultValue); } } return resolvedValues; } catch (Throwable cause) { throw new IllegalArgumentException(failureMessageSupplier.get(), cause); } }; } /** * Returns a bean resolver which retrieves a value using request converters. If the target element * is an annotated bean, a bean factory of the specified {@link BeanFactoryId} will be used for creating an * instance. */ private static BiFunction<AnnotatedValueResolver, ResolverContext, Object> resolver(List<RequestObjectResolver> objectResolvers, BeanFactoryId beanFactoryId) { return (resolver, ctx) -> { Object value = null; for (final RequestObjectResolver objectResolver : objectResolvers) { try { value = objectResolver.convert(ctx, resolver.elementType(), beanFactoryId); break; } catch (FallthroughException ignore) { // Do nothing. } catch (Throwable cause) { Exceptions.throwUnsafely(cause); } } if (value != null) { return value; } throw new IllegalArgumentException("No suitable request converter found for a @" + RequestObject.class.getSimpleName() + " '" + resolver.elementType().getSimpleName() + '\''); }; } @Nullable private final Annotation annotation; @Nullable private final String httpElementName; private final boolean isPathVariable; private final boolean shouldExist; private final boolean shouldWrapValueAsOptional; @Nullable private final Class<?> containerType; private final Class<?> elementType; @Nullable private final Object defaultValue; private final BiFunction<AnnotatedValueResolver, ResolverContext, Object> resolver; @Nullable private final EnumConverter<?> enumConverter; private final AggregationStrategy aggregationStrategy; private static final ConcurrentMap<Class<?>, EnumConverter<?>> enumConverters = new MapMaker().makeMap(); private AnnotatedValueResolver(@Nullable Annotation annotation, @Nullable String httpElementName, boolean isPathVariable, boolean shouldExist, boolean shouldWrapValueAsOptional, @Nullable Class<?> containerType, Class<?> elementType, @Nullable String defaultValue, BiFunction<AnnotatedValueResolver, ResolverContext, Object> resolver, AggregationStrategy aggregationStrategy) { this.annotation = annotation; this.httpElementName = httpElementName; this.isPathVariable = isPathVariable; this.shouldExist = shouldExist; this.shouldWrapValueAsOptional = shouldWrapValueAsOptional; this.elementType = requireNonNull(elementType, "elementType"); this.containerType = containerType; this.resolver = requireNonNull(resolver, "resolver"); this.aggregationStrategy = requireNonNull(aggregationStrategy, "aggregationStrategy"); enumConverter = enumConverter(elementType); // Must be called after initializing 'enumConverter'. this.defaultValue = defaultValue != null ? convert(defaultValue, elementType, enumConverter) : null; } @Nullable private static EnumConverter<?> enumConverter(Class<?> elementType) { if (!elementType.isEnum()) { return null; } return enumConverters.computeIfAbsent(elementType, newElementType -> { logger.debug("Registered an Enum {}", newElementType); return new EnumConverter<>(newElementType.asSubclass(Enum.class)); }); } @VisibleForTesting @Nullable Annotation annotation() { return annotation; } boolean isAnnotationType(Class<? extends Annotation> target) { return annotation != null && annotation.annotationType() == target; } @Nullable String httpElementName() { // Currently, this is non-null only if the element is one of the HTTP path variable, // parameter or header. return httpElementName; } boolean isPathVariable() { return isPathVariable; } @VisibleForTesting public boolean shouldExist() { return shouldExist; } @VisibleForTesting @Nullable Class<?> containerType() { // 'List' or 'Set' return containerType; } @VisibleForTesting Class<?> elementType() { return elementType; } @VisibleForTesting @Nullable Object defaultValue() { return defaultValue; } AggregationStrategy aggregationStrategy() { return aggregationStrategy; } boolean hasContainer() { return containerType != null && (List.class.isAssignableFrom(containerType) || Set.class.isAssignableFrom(containerType)); } Object resolve(ResolverContext ctx) { final Object resolved = resolver.apply(this, ctx); return shouldWrapValueAsOptional ? Optional.ofNullable(resolved) : resolved; } private static Object convert(String value, Class<?> elementType, @Nullable EnumConverter<?> enumConverter) { return enumConverter != null ? enumConverter.toEnum(value) : stringToType(value, elementType); } @Nullable private Object convert(@Nullable String value) { if (value == null) { return defaultOrException(); } return convert(value, elementType, enumConverter); } @Nullable private Object defaultOrException() { if (!shouldExist) { // May return 'null' if no default value is specified. return defaultValue; } throw new IllegalArgumentException("Mandatory parameter is missing: " + httpElementName); } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("annotation", annotation != null ? annotation.annotationType().getSimpleName() : "(none)") .add("httpElementName", httpElementName) .add("pathVariable", isPathVariable) .add("shouldExist", shouldExist) .add("shouldWrapValueAsOptional", shouldWrapValueAsOptional) .add("elementType", elementType.getSimpleName()) .add("containerType", containerType != null ? containerType.getSimpleName() : "(none)") .add("defaultValue", defaultValue) .add("defaultValueType", defaultValue != null ? defaultValue.getClass().getSimpleName() : "(none)") .add("resolver", resolver) .add("enumConverter", enumConverter) .toString(); } private static Builder builder(AnnotatedElement annotatedElement, Type type) { return new Builder(annotatedElement, type); } private static final class Builder { private final AnnotatedElement annotatedElement; private final Type type; private AnnotatedElement typeElement; @Nullable private Annotation annotation; @Nullable private String httpElementName; private boolean pathVariable; private boolean supportContainer; private boolean supportOptional; private boolean supportDefault; @Nullable private BiFunction<AnnotatedValueResolver, ResolverContext, Object> resolver; private AggregationStrategy aggregation = AggregationStrategy.NONE; private Builder(AnnotatedElement annotatedElement, Type type) { this.annotatedElement = requireNonNull(annotatedElement, "annotatedElement"); this.type = requireNonNull(type, "type"); typeElement = annotatedElement; } /** * Sets the annotation which is one of {@link Param}, {@link Header} or {@link RequestObject}. */ private Builder annotation(Annotation annotation) { this.annotation = annotation; return this; } /** * Sets a name of the element. */ private Builder httpElementName(String httpElementName) { this.httpElementName = httpElementName; return this; } /** * Sets whether this element is a path variable. */ private Builder pathVariable(boolean pathVariable) { this.pathVariable = pathVariable; return this; } /** * Sets whether the value type can be a {@link List} or {@link Set}. */ private Builder supportContainer(boolean supportContainer) { this.supportContainer = supportContainer; return this; } /** * Sets whether the value type can be wrapped by {@link Optional}. */ private Builder supportOptional(boolean supportOptional) { this.supportOptional = supportOptional; return this; } /** * Sets whether the element can be annotated with {@link Default} annotation. */ private Builder supportDefault(boolean supportDefault) { this.supportDefault = supportDefault; return this; } /** * Sets an {@link AnnotatedElement} which is used to infer its type. */ private Builder typeElement(AnnotatedElement typeElement) { this.typeElement = typeElement; return this; } /** * Sets a value resolver. */ private Builder resolver(BiFunction<AnnotatedValueResolver, ResolverContext, Object> resolver) { this.resolver = resolver; return this; } /** * Sets an {@link AggregationStrategy} for the element. */ private Builder aggregation(AggregationStrategy aggregation) { this.aggregation = aggregation; return this; } private static Type parameterizedTypeOf(AnnotatedElement element) { if (element instanceof Parameter) { return ((Parameter) element).getParameterizedType(); } if (element instanceof Field) { return ((Field) element).getGenericType(); } throw new IllegalArgumentException("Unsupported annotated element: " + element.getClass().getSimpleName()); } private static Entry<Class<?>, Class<?>> resolveTypes(Type parameterizedType, Type type, boolean unwrapOptionalType) { if (unwrapOptionalType) { // Unwrap once again so that a pattern like 'Optional<List<?>>' can be supported. assert parameterizedType instanceof ParameterizedType : String.valueOf(parameterizedType); parameterizedType = ((ParameterizedType) parameterizedType).getActualTypeArguments()[0]; } final Class<?> elementType; final Class<?> containerType; if (parameterizedType instanceof ParameterizedType) { try { elementType = (Class<?>) ((ParameterizedType) parameterizedType).getActualTypeArguments()[0]; } catch (Throwable cause) { throw new IllegalArgumentException("Invalid parameter type: " + parameterizedType, cause); } containerType = normalizeContainerType( (Class<?>) ((ParameterizedType) parameterizedType).getRawType()); } else { elementType = unwrapOptionalType ? (Class<?>) parameterizedType : (Class<?>) type; containerType = null; } return new SimpleImmutableEntry<>(containerType, validateElementType(elementType)); } private AnnotatedValueResolver build() { checkArgument(resolver != null, "'resolver' should be specified"); // Request convert may produce 'Optional<?>' value. But it is different from supporting // 'Optional' type. So if the annotation is 'RequestObject', 'shouldWrapValueAsOptional' // is always set as 'false'. final boolean shouldWrapValueAsOptional = type == Optional.class && (annotation == null || annotation.annotationType() != RequestObject.class); if (!supportOptional && shouldWrapValueAsOptional) { throw new IllegalArgumentException( '@' + Optional.class.getSimpleName() + " is not supported for: " + (annotation != null ? annotation.annotationType().getSimpleName() : type.getTypeName())); } final boolean shouldExist; final String defaultValue; final Default aDefault = annotatedElement.getAnnotation(Default.class); if (aDefault != null) { if (!supportDefault) { throw new IllegalArgumentException( '@' + Default.class.getSimpleName() + " is not supported for: " + (annotation != null ? annotation.annotationType().getSimpleName() : type.getTypeName())); } // Warn unusual usage. e.g. @Param @Default("a") Optional<String> param if (shouldWrapValueAsOptional) { // 'annotatedElement' can be one of constructor, field, method or parameter. // So, it may be printed verbosely but it's okay because it provides where this message // is caused. logger.warn("Both {} type and @{} are specified on {}. One of them can be omitted.", Optional.class.getSimpleName(), Default.class.getSimpleName(), annotatedElement); } shouldExist = false; defaultValue = getSpecifiedValue(aDefault.value()).get(); } else { shouldExist = !shouldWrapValueAsOptional; // Set the default value to 'null' if it was not specified. defaultValue = null; } if (pathVariable && !shouldExist) { throw new IllegalArgumentException("Path variable should be mandatory: " + annotatedElement); } final Entry<Class<?>, Class<?>> types; if (annotation != null && (annotation.annotationType() == Param.class || annotation.annotationType() == Header.class)) { assert httpElementName != null; // The value annotated with @Param or @Header should be converted to the desired type, // so the type should be resolved here. final Type parameterizedType = parameterizedTypeOf(typeElement); types = resolveTypes(parameterizedType, type, shouldWrapValueAsOptional); // Currently a container type such as 'List' and 'Set' is allowed to @Header annotation // and HTTP parameters specified by @Param annotation. if (!supportContainer && types.getKey() != null) { throw new IllegalArgumentException("Unsupported collection type: " + parameterizedType); } } else { assert type.getClass() == Class.class : String.valueOf(type); // // Here, 'type' should be one of the following types: // - RequestContext (or ServiceRequestContext) // - Request (or HttpRequest) // - AggregatedHttpMessage // - HttpParameters // - User classes which can be converted by request converter // // So the container type should be 'null'. // types = new SimpleImmutableEntry<>(null, (Class<?>) type); } return new AnnotatedValueResolver(annotation, httpElementName, pathVariable, shouldExist, shouldWrapValueAsOptional, types.getKey(), types.getValue(), defaultValue, resolver, aggregation); } } private static boolean isFormData(@Nullable MediaType contentType) { return contentType != null && contentType.belongsTo(MediaType.FORM_DATA); } enum AggregationStrategy { NONE, ALWAYS, FOR_FORM_DATA; /** * Returns whether the request should be aggregated. */ static boolean aggregationRequired(AggregationStrategy strategy, HttpRequest req) { requireNonNull(strategy, "strategy"); switch (strategy) { case ALWAYS: return true; case FOR_FORM_DATA: return isFormData(req.headers().contentType()); } return false; } /** * Returns {@link AggregationStrategy} which specifies how to aggregate the request * for injecting its parameters. */ static AggregationStrategy from(List<AnnotatedValueResolver> resolvers) { AggregationStrategy strategy = NONE; for (final AnnotatedValueResolver r : resolvers) { switch (r.aggregationStrategy()) { case ALWAYS: return ALWAYS; case FOR_FORM_DATA: strategy = FOR_FORM_DATA; break; } } return strategy; } } /** * A context which is used while resolving parameter values. */ static class ResolverContext { private final ServiceRequestContext context; private final HttpRequest request; @Nullable private final AggregatedHttpMessage message; @Nullable private volatile HttpParameters httpParameters; ResolverContext(ServiceRequestContext context, HttpRequest request, @Nullable AggregatedHttpMessage message) { this.context = requireNonNull(context, "context"); this.request = requireNonNull(request, "request"); this.message = message; } ServiceRequestContext context() { return context; } HttpRequest request() { return request; } @Nullable AggregatedHttpMessage message() { return message; } HttpParameters httpParameters() { HttpParameters result = httpParameters; if (result == null) { synchronized (this) { result = httpParameters; if (result == null) { httpParameters = result = httpParametersOf(context.query(), request.headers().contentType(), message); } } } return result; } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("context", context) .add("request", request) .add("message", message) .add("httpParameters", httpParameters) .toString(); } /** * Returns a map of parameters decoded from a request. * * <p>Usually one of a query string of a URI or URL-encoded form data is specified in the request. * If both of them exist though, they would be decoded and merged into a parameter map.</p> * * <p>Names and values of the parameters would be decoded as UTF-8 character set.</p> * * @see QueryStringDecoder#QueryStringDecoder(String, boolean) * @see HttpConstants#DEFAULT_CHARSET */ private static HttpParameters httpParametersOf(@Nullable String query, @Nullable MediaType contentType, @Nullable AggregatedHttpMessage message) { try { Map<String, List<String>> parameters = null; if (query != null) { parameters = new QueryStringDecoder(query, false).parameters(); } if (message != null && isFormData(contentType)) { // Respect 'charset' attribute of the 'content-type' header if it exists. final String body = message.content().toString( contentType.charset().orElse(StandardCharsets.US_ASCII)); if (!body.isEmpty()) { final Map<String, List<String>> p = new QueryStringDecoder(body, false).parameters(); if (parameters == null) { parameters = p; } else if (p != null) { parameters.putAll(p); } } } if (parameters == null || parameters.isEmpty()) { return EMPTY_PARAMETERS; } return HttpParameters.copyOf(parameters); } catch (Exception e) { // If we failed to decode the query string, we ignore the exception raised here. // A missing parameter might be checked when invoking the annotated method. logger.debug("Failed to decode query string: {}", query, e); return EMPTY_PARAMETERS; } } } private static final class EnumConverter<T extends Enum<T>> { private final boolean isCaseSensitiveEnum; private final Map<String, T> enumMap; /** * Creates an instance for the given {@link Enum} class. */ EnumConverter(Class<T> enumClass) { final Set<T> enumInstances = EnumSet.allOf(enumClass); final Map<String, T> lowerCaseEnumMap = enumInstances.stream().collect( toImmutableMap(e -> Ascii.toLowerCase(e.name()), Function.identity(), (e1, e2) -> e1)); if (enumInstances.size() != lowerCaseEnumMap.size()) { enumMap = enumInstances.stream().collect(toImmutableMap(Enum::name, Function.identity())); isCaseSensitiveEnum = true; } else { enumMap = lowerCaseEnumMap; isCaseSensitiveEnum = false; } } /** * Returns the {@link Enum} value corresponding to the specified {@code str}. */ T toEnum(String str) { final T result = enumMap.get(isCaseSensitiveEnum ? str : Ascii.toLowerCase(str)); if (result != null) { return result; } throw new IllegalArgumentException( "unknown enum value: " + str + " (expected: " + enumMap.values() + ')'); } } /** * An interface to make a {@link RequestConverterFunction} be adapted for * {@link AnnotatedValueResolver} internal implementation. */ @FunctionalInterface interface RequestObjectResolver { static RequestObjectResolver of(RequestConverterFunction function) { return (resolverContext, expectedResultType, beanFactoryId) -> { final AggregatedHttpMessage message = resolverContext.message(); if (message == null) { throw new IllegalArgumentException( "Cannot convert this request to an object because it is not aggregated."); } return function.convertRequest(resolverContext.context(), message, expectedResultType); }; } @Nullable Object convert(ResolverContext resolverContext, Class<?> expectedResultType, @Nullable BeanFactoryId beanFactoryId) throws Throwable; } /** * A subtype of {@link IllegalArgumentException} which is raised when no annotated parameters exist * in a constructor or method. */ static class NoAnnotatedParameterException extends IllegalArgumentException { private static final long serialVersionUID = -6003890710456747277L; NoAnnotatedParameterException(String name) { super("No annotated parameters found from: " + name); } } /** * A subtype of {@link NoAnnotatedParameterException} which is raised when no parameters exist in * a constructor or method. */ static class NoParameterException extends NoAnnotatedParameterException { private static final long serialVersionUID = 3390292442571367102L; NoParameterException(String name) { super("No parameters found from: " + name); } } }
jmostella/armeria
core/src/main/java/com/linecorp/armeria/server/AnnotatedValueResolver.java
Java
apache-2.0
48,024
<?php /* * Copyright 2014 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ namespace Google\Service\Document; class GoogleCloudDocumentaiV1beta3BatchProcessResponse extends \Google\Model { } // Adding a class alias for backwards compatibility with the previous class name. class_alias(GoogleCloudDocumentaiV1beta3BatchProcessResponse::class, 'Google_Service_Document_GoogleCloudDocumentaiV1beta3BatchProcessResponse');
googleapis/google-api-php-client-services
src/Document/GoogleCloudDocumentaiV1beta3BatchProcessResponse.php
PHP
apache-2.0
944
/* 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.flowable.engine.test.bpmn.servicetask; import org.flowable.engine.IdentityService; import org.flowable.engine.ManagementService; import org.flowable.engine.delegate.DelegateExecution; import org.flowable.engine.delegate.JavaDelegate; import org.flowable.engine.impl.context.Context; import org.flowable.engine.impl.interceptor.Command; import org.flowable.engine.impl.interceptor.CommandContext; import org.flowable.idm.api.Group; import org.flowable.idm.api.User; /** * @author Joram Barrez */ public class CreateUserAndMembershipTestDelegate implements JavaDelegate { @Override public void execute(DelegateExecution execution) { ManagementService managementService = Context.getProcessEngineConfiguration().getManagementService(); managementService.executeCommand(new Command<Void>() { @Override public Void execute(CommandContext commandContext) { return null; } }); IdentityService identityService = Context.getProcessEngineConfiguration().getIdentityService(); String username = "Kermit"; User user = identityService.newUser(username); user.setPassword("123"); user.setFirstName("Manually"); user.setLastName("created"); identityService.saveUser(user); // Add admin group Group group = identityService.newGroup("admin"); identityService.saveGroup(group); identityService.createMembership(username, "admin"); } }
robsoncardosoti/flowable-engine
modules/flowable-engine/src/test/java/org/flowable/engine/test/bpmn/servicetask/CreateUserAndMembershipTestDelegate.java
Java
apache-2.0
2,078
/** * 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; import org.apache.camel.ContextTestSupport; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.component.mock.MockEndpoint; import org.apache.camel.impl.JndiRegistry; /** * @version */ public class RecipientListBeanTest extends ContextTestSupport { @Override protected JndiRegistry createRegistry() throws Exception { JndiRegistry jndi = super.createRegistry(); jndi.bind("myBean", new MyBean()); return jndi; } public void testRecipientListWithBean() throws Exception { MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedBodiesReceived("Hello c"); String out = template.requestBody("direct:start", "direct:a,direct:b,direct:c", String.class); assertEquals("Hello c", out); assertMockEndpointsSatisfied(); } protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { public void configure() { from("direct:start").recipientList(bean("myBean", "foo")).to("mock:result"); from("direct:a").transform(constant("Hello a")); from("direct:b").transform(constant("Hello b")); from("direct:c").transform(constant("Hello c")); } }; } public class MyBean { public String[] foo(String body) { return body.split(","); } } }
cexbrayat/camel
camel-core/src/test/java/org/apache/camel/processor/RecipientListBeanTest.java
Java
apache-2.0
2,243
$(document).ready(function() { $('#btn-create-version').on('click', function(e) { e.preventDefault(); var newVersion = $('#new-version').val(); if (newVersion) { var assetId = $('#asset-id').val(); var assetType = $('#asset-type').val(); var path = caramel.url('/apis/asset/' + assetId + '/create-version?type=' + assetType); var assetPath = caramel.url('/assets/' + assetType + '/details/'); $('#btn-create-version').addClass('disabled'); $('#new-version-loading').removeClass('hide'); var alertMessage = $("#alertSection"); $.ajax({ url: path, data: JSON.stringify({ "attributes": { "overview_version": newVersion } }), type: 'POST', success: function(response) { messages.alertSuccess('Asset version created successfully!,You will be redirected to new asset details page in few seconds.....'); setTimeout(function() { var path = caramel.url('assets/' + assetType + '/details/' + response.data); window.location = path; }, 3000); }, error: function(error) { var errorText = JSON.parse(error.responseText).error; messages.alertError(errorText); $('#btn-create-version').removeClass('disabled'); $('#new-version-loading').addClass('hide'); } }); } }); $('#btn-cancel-version').on('click', function(e) { var assetId = $('#asset-id').val(); var assetType = $('#asset-type').val(); var path = caramel.url('/assets/' + assetType + '/details/' + assetId); $.ajax({ success: function(response) { window.location = path; } }); }); });
sameerak/carbon-store
apps/publisher/themes/default/js/copy-asset.js
JavaScript
apache-2.0
2,044
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Pollster.CommonCode; namespace Pollster.PollWebFrontend.Models { public class IndexPollFeedViewModel { public IList<PollDefinition> Polls { get; set; } } public class SubmittedVoteViewModel { public string PollId { get; set; } public string VotedOptionId { get; set; } public Dictionary<string, int> LatestVotes { get; set; } public bool Success { get; set; } public string ErrorMessage { get; set; } } }
awslabs/aws-sdk-net-samples
Talks/vslive-2015/Pollster/App/src/PollWebFrontend/Models/PollFeedViewModels.cs
C#
apache-2.0
590
import shelve import os import re from resource_api.interfaces import Resource as BaseResource, Link as BaseLink, AbstractUriPolicy from resource_api.schema import StringField, DateTimeField, IntegerField from resource_api.service import Service from resource_api.errors import ValidationError RE_SHA1 = re.compile("^[a-f0-9]{40}$") SHELVE_PATH = "/tmp/school.shelve.db" class ShelveService(Service): def __init__(self): super(ShelveService, self).__init__() self._storage = shelve.open(SHELVE_PATH, writeback=True) def _get_context(self): return {"storage": self._storage} def _get_user(self, data): return None def __del__(self): self._storage.close() class Resource(BaseResource): def __init__(self, context): super(Resource, self).__init__(context) self._storage = context["storage"] def exists(self, user, pk): return pk in self._storage.get(self.get_name(), {}) def get_data(self, user, pk): return self._storage.get(self.get_name(), {}).get(pk) def delete(self, user, pk): self._storage.get(self.get_name(), {}).pop(pk) self._storage.sync() def create(self, user, pk, data): if self.get_name() not in self._storage: self._storage[self.get_name()] = {} self._storage[self.get_name()][pk] = data self._storage.sync() def update(self, user, pk, data): self._storage[self.get_name()][pk].update(data) self._storage.sync() def get_uris(self, user, params=None): return self._storage.get(self.get_name(), {}).keys() def get_count(self, user, params=None): return len(self.get_uris(params)) class Link(BaseLink): def __init__(self, context): super(Link, self).__init__(context) self._storage = context["storage"] def exists(self, user, pk, rel_pk): return rel_pk in self._storage.get((pk, self.get_name()), {}) def get_data(self, user, pk, rel_pk): return self._storage.get((pk, self.get_name()), {}).get(rel_pk) def create(self, user, pk, rel_pk, data=None): key = (pk, self.get_name()) if key not in self._storage: self._storage[key] = {} self._storage[key][rel_pk] = data self._storage.sync() def update(self, user, pk, rel_pk, data): self._storage[key][rel_pk].update(data) self._storage.sync() def delete(self, user, pk, rel_pk): self._storage.get((pk, self.get_name()), {}).pop(rel_pk) self._storage.sync() def get_uris(self, user, pk, params=None): return self._storage.get((pk, self.get_name()), {}).keys() def get_count(self, user, pk, params=None): return len(self.get_uris(pk, params)) class Student(Resource): """ A pupil """ class Schema: email = StringField(regex="[^@]+@[^@]+\.[^@]+", pk=True, description="Addess to which the notifications shall be sent") first_name = StringField(description="Given name(s)") last_name = StringField(description="Family name(s)") birthday = DateTimeField() class Links: class courses(Link): """ Courses the student has ever attended """ class Schema: grade = IntegerField(min_val=1, max_val=5) target = "Course" related_name = "students" master = True class comments(Link): """ Comments made by the student """ target = "Comment" related_name = "student" class ratings(Link): """ Ratings given by the student """ target = "TeacherRating" related_name = "student" class Teacher(Resource): """ A lecturer """ class Schema: email = StringField(regex="[^@]+@[^@]+\.[^@]+", pk=True, description="Addess to which the notifications shall be sent") first_name = StringField(description="Given name(s)") last_name = StringField(description="Family name(s)") category = StringField(description="TQS Category", choices=["four", "five", "five plus", "six"]) class Links: class ratings(Link): """ Ratings given to the teacher """ target = "TeacherRating" related_name = "teacher" class courses(Link): """ Courses the teacher is responsible for """ target = "Course" related_name = "teacher" class Course(Resource): """ An educational unit represinting the lessons for a specific set of topics """ class Schema: name = StringField(pk=True, description="Name of the course. E.g. physics, maths.") duration = IntegerField(description="Length of the course in weeks") class Links: class teacher(Link): """ The lecturer of the course """ target = "Teacher" related_name = "courses" cardinality = Link.cardinalities.ONE master = True required = True class comments(Link): """ All comments made about the course """ target = "Comment" related_name = "course" class ratings(Link): """ All ratings that were given to the teachers of the specific course """ target = "TeacherRating" related_name = "course" class students(Link): """ All pupils who attend the course """ target = "Student" related_name = "courses" class AutoGenSha1UriPolicy(AbstractUriPolicy): """ Uses a randomly generated sha1 as a primary key """ @property def type(self): return "autogen_policy" def generate_pk(self, data): return os.urandom(16).encode('hex') def serialize(self, pk): return pk def deserialize(self, pk): if not isinstance(pk, basestring): raise ValidationError("Has to be string") if not RE_SHA1.match(value): raise ValidationError("PK is not a valid SHA1") return pk class Comment(Resource): """ Student's comment about the course """ UriPolicy = AutoGenSha1UriPolicy class Schema: pk = StringField(pk=True, description="Identifier of the resource") value = StringField(description="Text of the comment") creation_time = DateTimeField(description="Time when the comment was added (for sorting purpose)") class Links: class student(Link): """ The pupil who made the comment """ target = "Student" related_name = "comments" cardinality = Link.cardinalities.ONE master = True required = True class course(Link): """ The subject the comment was made about """ target = "Course" related_name = "comments" cardinality = Link.cardinalities.ONE master = True required = True class TeacherRating(Resource): """ Student's rating about teacher's performance """ UriPolicy = AutoGenSha1UriPolicy class Schema: pk = StringField(pk=True, description="Identifier of the resource") value = IntegerField(min_val=0, max_val=100, description="Lecturer's performance identifier ") creation_time = DateTimeField(description="Time when the rating was added (for sorting purpose)") class Links: class student(Link): """ The pupil who gave the rating to the teacher """ target = "Student" related_name = "ratings" cardinality = Link.cardinalities.ONE master = True required = True class course(Link): """ The subject with respect to which the rating was given """ target = "Course" related_name = "ratings" cardinality = Link.cardinalities.ONE master = True required = True class teacher(Link): """ The lecturer to whom the rating is related """ target = "Teacher" related_name = "ratings" cardinality = Link.cardinalities.ONE master = True required = True srv = ShelveService() srv.register(Student) srv.register(Teacher) srv.register(Course) srv.register(Comment) srv.register(TeacherRating) srv.setup()
gurunars/resource-api
documentation/tutorial/service_v4.py
Python
apache-2.0
8,456
// 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.ver15; 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 com.google.common.collect.ImmutableSet; import io.netty.buffer.ByteBuf; import com.google.common.hash.PrimitiveSink; import com.google.common.hash.Funnel; class OFTableDescStatsRequestVer15 implements OFTableDescStatsRequest { private static final Logger logger = LoggerFactory.getLogger(OFTableDescStatsRequestVer15.class); // version: 1.5 final static byte WIRE_VERSION = 6; final static int LENGTH = 16; private final static long DEFAULT_XID = 0x0L; private final static Set<OFStatsRequestFlags> DEFAULT_FLAGS = ImmutableSet.<OFStatsRequestFlags>of(); // OF message fields private final long xid; private final Set<OFStatsRequestFlags> flags; // // Immutable default instance final static OFTableDescStatsRequestVer15 DEFAULT = new OFTableDescStatsRequestVer15( DEFAULT_XID, DEFAULT_FLAGS ); // package private constructor - used by readers, builders, and factory OFTableDescStatsRequestVer15(long xid, Set<OFStatsRequestFlags> flags) { if(flags == null) { throw new NullPointerException("OFTableDescStatsRequestVer15: property flags cannot be null"); } this.xid = xid; this.flags = flags; } // Accessors for OF message fields @Override public OFVersion getVersion() { return OFVersion.OF_15; } @Override public OFType getType() { return OFType.STATS_REQUEST; } @Override public long getXid() { return xid; } @Override public OFStatsType getStatsType() { return OFStatsType.TABLE_DESC; } @Override public Set<OFStatsRequestFlags> getFlags() { return flags; } public OFTableDescStatsRequest.Builder createBuilder() { return new BuilderWithParent(this); } static class BuilderWithParent implements OFTableDescStatsRequest.Builder { final OFTableDescStatsRequestVer15 parentMessage; // OF message fields private boolean xidSet; private long xid; private boolean flagsSet; private Set<OFStatsRequestFlags> flags; BuilderWithParent(OFTableDescStatsRequestVer15 parentMessage) { this.parentMessage = parentMessage; } @Override public OFVersion getVersion() { return OFVersion.OF_15; } @Override public OFType getType() { return OFType.STATS_REQUEST; } @Override public long getXid() { return xid; } @Override public OFTableDescStatsRequest.Builder setXid(long xid) { this.xid = xid; this.xidSet = true; return this; } @Override public OFStatsType getStatsType() { return OFStatsType.TABLE_DESC; } @Override public Set<OFStatsRequestFlags> getFlags() { return flags; } @Override public OFTableDescStatsRequest.Builder setFlags(Set<OFStatsRequestFlags> flags) { this.flags = flags; this.flagsSet = true; return this; } @Override public OFTableDescStatsRequest build() { long xid = this.xidSet ? this.xid : parentMessage.xid; Set<OFStatsRequestFlags> flags = this.flagsSet ? this.flags : parentMessage.flags; if(flags == null) throw new NullPointerException("Property flags must not be null"); // return new OFTableDescStatsRequestVer15( xid, flags ); } } static class Builder implements OFTableDescStatsRequest.Builder { // OF message fields private boolean xidSet; private long xid; private boolean flagsSet; private Set<OFStatsRequestFlags> flags; @Override public OFVersion getVersion() { return OFVersion.OF_15; } @Override public OFType getType() { return OFType.STATS_REQUEST; } @Override public long getXid() { return xid; } @Override public OFTableDescStatsRequest.Builder setXid(long xid) { this.xid = xid; this.xidSet = true; return this; } @Override public OFStatsType getStatsType() { return OFStatsType.TABLE_DESC; } @Override public Set<OFStatsRequestFlags> getFlags() { return flags; } @Override public OFTableDescStatsRequest.Builder setFlags(Set<OFStatsRequestFlags> flags) { this.flags = flags; this.flagsSet = true; return this; } // @Override public OFTableDescStatsRequest build() { long xid = this.xidSet ? this.xid : DEFAULT_XID; Set<OFStatsRequestFlags> flags = this.flagsSet ? this.flags : DEFAULT_FLAGS; if(flags == null) throw new NullPointerException("Property flags must not be null"); return new OFTableDescStatsRequestVer15( xid, flags ); } } final static Reader READER = new Reader(); static class Reader implements OFMessageReader<OFTableDescStatsRequest> { @Override public OFTableDescStatsRequest readFrom(ByteBuf bb) throws OFParseError { int start = bb.readerIndex(); // fixed value property version == 6 byte version = bb.readByte(); if(version != (byte) 0x6) throw new OFParseError("Wrong version: Expected=OFVersion.OF_15(6), got="+version); // fixed value property type == 18 byte type = bb.readByte(); if(type != (byte) 0x12) throw new OFParseError("Wrong type: Expected=OFType.STATS_REQUEST(18), got="+type); int length = U16.f(bb.readShort()); if(length != 16) throw new OFParseError("Wrong length: Expected=16(16), got="+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 statsType == 14 short statsType = bb.readShort(); if(statsType != (short) 0xe) throw new OFParseError("Wrong statsType: Expected=OFStatsType.TABLE_DESC(14), got="+statsType); Set<OFStatsRequestFlags> flags = OFStatsRequestFlagsSerializerVer15.readFrom(bb); // pad: 4 bytes bb.skipBytes(4); OFTableDescStatsRequestVer15 tableDescStatsRequestVer15 = new OFTableDescStatsRequestVer15( xid, flags ); if(logger.isTraceEnabled()) logger.trace("readFrom - read={}", tableDescStatsRequestVer15); return tableDescStatsRequestVer15; } } public void putTo(PrimitiveSink sink) { FUNNEL.funnel(this, sink); } final static OFTableDescStatsRequestVer15Funnel FUNNEL = new OFTableDescStatsRequestVer15Funnel(); static class OFTableDescStatsRequestVer15Funnel implements Funnel<OFTableDescStatsRequestVer15> { private static final long serialVersionUID = 1L; @Override public void funnel(OFTableDescStatsRequestVer15 message, PrimitiveSink sink) { // fixed value property version = 6 sink.putByte((byte) 0x6); // fixed value property type = 18 sink.putByte((byte) 0x12); // fixed value property length = 16 sink.putShort((short) 0x10); sink.putLong(message.xid); // fixed value property statsType = 14 sink.putShort((short) 0xe); OFStatsRequestFlagsSerializerVer15.putTo(message.flags, sink); // skip pad (4 bytes) } } public void writeTo(ByteBuf bb) { WRITER.write(bb, this); } final static Writer WRITER = new Writer(); static class Writer implements OFMessageWriter<OFTableDescStatsRequestVer15> { @Override public void write(ByteBuf bb, OFTableDescStatsRequestVer15 message) { // fixed value property version = 6 bb.writeByte((byte) 0x6); // fixed value property type = 18 bb.writeByte((byte) 0x12); // fixed value property length = 16 bb.writeShort((short) 0x10); bb.writeInt(U32.t(message.xid)); // fixed value property statsType = 14 bb.writeShort((short) 0xe); OFStatsRequestFlagsSerializerVer15.writeTo(bb, message.flags); // pad: 4 bytes bb.writeZero(4); } } @Override public String toString() { StringBuilder b = new StringBuilder("OFTableDescStatsRequestVer15("); b.append("xid=").append(xid); b.append(", "); b.append("flags=").append(flags); 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; OFTableDescStatsRequestVer15 other = (OFTableDescStatsRequestVer15) obj; if( xid != other.xid) return false; if (flags == null) { if (other.flags != null) return false; } else if (!flags.equals(other.flags)) return false; return true; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * (int) (xid ^ (xid >>> 32)); result = prime * result + ((flags == null) ? 0 : flags.hashCode()); return result; } }
mehdi149/OF_COMPILER_0.1
gen-src/main/java/org/projectfloodlight/openflow/protocol/ver15/OFTableDescStatsRequestVer15.java
Java
apache-2.0
11,425
/** * Copyright 2009-2012 WSO2, Inc. (http://wso2.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.wso2.developerstudio.eclipse.gmf.esb.provider; import java.util.Collection; import java.util.List; import org.apache.commons.lang.WordUtils; import org.eclipse.emf.common.notify.AdapterFactory; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.common.util.ResourceLocator; import org.eclipse.emf.ecore.EStructuralFeature; import org.eclipse.emf.edit.provider.ComposeableAdapterFactory; import org.eclipse.emf.edit.provider.IEditingDomainItemProvider; import org.eclipse.emf.edit.provider.IItemLabelProvider; import org.eclipse.emf.edit.provider.IItemPropertyDescriptor; import org.eclipse.emf.edit.provider.IItemPropertySource; import org.eclipse.emf.edit.provider.IStructuredItemContentProvider; import org.eclipse.emf.edit.provider.ITreeItemContentProvider; import org.eclipse.emf.edit.provider.ItemPropertyDescriptor; import org.eclipse.emf.edit.provider.ItemProviderAdapter; import org.eclipse.emf.edit.provider.ViewerNotification; import org.wso2.developerstudio.eclipse.gmf.esb.EndPointProperty; import org.wso2.developerstudio.eclipse.gmf.esb.EsbFactory; import org.wso2.developerstudio.eclipse.gmf.esb.EsbPackage; import org.wso2.developerstudio.eclipse.gmf.esb.PropertyValueType; import org.wso2.developerstudio.eclipse.gmf.esb.presentation.EEFPropertyViewUtil; /** * This is the item provider adapter for a {@link org.wso2.developerstudio.eclipse.gmf.esb.EndPointProperty} object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public class EndPointPropertyItemProvider extends ItemProviderAdapter implements IEditingDomainItemProvider, IStructuredItemContentProvider, ITreeItemContentProvider, IItemLabelProvider, IItemPropertySource { /** * This constructs an instance from a factory and a notifier. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EndPointPropertyItemProvider(AdapterFactory adapterFactory) { super(adapterFactory); } /** * This returns the property descriptors for the adapted class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public List<IItemPropertyDescriptor> getPropertyDescriptors(Object object) { if (itemPropertyDescriptors == null) { super.getPropertyDescriptors(object); addNamePropertyDescriptor(object); addValuePropertyDescriptor(object); addScopePropertyDescriptor(object); addValueTypePropertyDescriptor(object); } return itemPropertyDescriptors; } /** * This adds a property descriptor for the Name feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected void addNamePropertyDescriptor(Object object) { itemPropertyDescriptors.add (createItemPropertyDescriptor (((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(), getResourceLocator(), getString("_UI_EndPointProperty_name_feature"), getString("_UI_PropertyDescriptor_description", "_UI_EndPointProperty_name_feature", "_UI_EndPointProperty_type"), EsbPackage.Literals.END_POINT_PROPERTY__NAME, true, false, false, ItemPropertyDescriptor.GENERIC_VALUE_IMAGE, null, null)); } /** * This adds a property descriptor for the Value feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected void addValuePropertyDescriptor(Object object) { itemPropertyDescriptors.add (createItemPropertyDescriptor (((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(), getResourceLocator(), getString("_UI_EndPointProperty_value_feature"), getString("_UI_PropertyDescriptor_description", "_UI_EndPointProperty_value_feature", "_UI_EndPointProperty_type"), EsbPackage.Literals.END_POINT_PROPERTY__VALUE, true, false, false, ItemPropertyDescriptor.GENERIC_VALUE_IMAGE, null, null)); } /** * This adds a property descriptor for the Scope feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected void addScopePropertyDescriptor(Object object) { itemPropertyDescriptors.add (createItemPropertyDescriptor (((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(), getResourceLocator(), getString("_UI_EndPointProperty_scope_feature"), getString("_UI_PropertyDescriptor_description", "_UI_EndPointProperty_scope_feature", "_UI_EndPointProperty_type"), EsbPackage.Literals.END_POINT_PROPERTY__SCOPE, true, false, false, ItemPropertyDescriptor.GENERIC_VALUE_IMAGE, null, null)); } /** * This adds a property descriptor for the Value Type feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected void addValueTypePropertyDescriptor(Object object) { itemPropertyDescriptors.add (createItemPropertyDescriptor (((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(), getResourceLocator(), getString("_UI_EndPointProperty_valueType_feature"), getString("_UI_PropertyDescriptor_description", "_UI_EndPointProperty_valueType_feature", "_UI_EndPointProperty_type"), EsbPackage.Literals.END_POINT_PROPERTY__VALUE_TYPE, true, false, false, ItemPropertyDescriptor.GENERIC_VALUE_IMAGE, null, null)); } /** * This specifies how to implement {@link #getChildren} and is used to deduce an appropriate feature for an * {@link org.eclipse.emf.edit.command.AddCommand}, {@link org.eclipse.emf.edit.command.RemoveCommand} or * {@link org.eclipse.emf.edit.command.MoveCommand} in {@link #createCommand}. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Collection<? extends EStructuralFeature> getChildrenFeatures(Object object) { if (childrenFeatures == null) { super.getChildrenFeatures(object); childrenFeatures.add(EsbPackage.Literals.END_POINT_PROPERTY__VALUE_EXPRESSION); } return childrenFeatures; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EStructuralFeature getChildFeature(Object object, Object child) { // Check the type of the specified child object and return the proper feature to use for // adding (see {@link AddCommand}) it as a child. return super.getChildFeature(object, child); } /** * This returns EndPointProperty.gif. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object getImage(Object object) { return overlayImage(object, getResourceLocator().getImage("full/obj16/EndPointProperty")); } /** * This returns the label text for the adapted class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated NOT */ @Override public String getText(Object object) { String propertyName = ((EndPointProperty) object).getName(); String propertyNameLabel = WordUtils.abbreviate(propertyName, 40, 45, " ..."); String propertyValueType = ((EndPointProperty) object).getValueType().toString(); String propertyValue = ((EndPointProperty) object).getValue(); String valueExpression = ((EndPointProperty) object).getValueExpression().toString(); if (propertyValueType.equalsIgnoreCase(PropertyValueType.LITERAL.getName())) { if (((EndPointProperty) object).getValue() != null) { return propertyName == null || propertyName.length() == 0 ? getString("_UI_EndPointProperty_type") : getString("_UI_EndPointProperty_type") + " - " + EEFPropertyViewUtil.spaceFormat(propertyNameLabel) + EEFPropertyViewUtil.spaceFormat(propertyValue); } else { return propertyName == null || propertyName.length() == 0 ? getString("_UI_EndPointProperty_type") : getString("_UI_EndPointProperty_type") + " - " + EEFPropertyViewUtil.spaceFormat(propertyNameLabel); } } else { return propertyName == null || propertyName.length() == 0 ? getString("_UI_EndPointProperty_type") : getString("_UI_EndPointProperty_type") + " - " + EEFPropertyViewUtil.spaceFormat(propertyNameLabel) + EEFPropertyViewUtil.spaceFormat(valueExpression); } } /** * This handles model notifications by calling {@link #updateChildren} to update any cached * children and by creating a viewer notification, which it passes to {@link #fireNotifyChanged}. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void notifyChanged(Notification notification) { updateChildren(notification); switch (notification.getFeatureID(EndPointProperty.class)) { case EsbPackage.END_POINT_PROPERTY__NAME: case EsbPackage.END_POINT_PROPERTY__VALUE: case EsbPackage.END_POINT_PROPERTY__SCOPE: case EsbPackage.END_POINT_PROPERTY__VALUE_TYPE: fireNotifyChanged(new ViewerNotification(notification, notification.getNotifier(), false, true)); return; case EsbPackage.END_POINT_PROPERTY__VALUE_EXPRESSION: fireNotifyChanged(new ViewerNotification(notification, notification.getNotifier(), true, false)); return; } super.notifyChanged(notification); } /** * This adds {@link org.eclipse.emf.edit.command.CommandParameter}s describing the children * that can be created under this object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected void collectNewChildDescriptors(Collection<Object> newChildDescriptors, Object object) { super.collectNewChildDescriptors(newChildDescriptors, object); newChildDescriptors.add (createChildParameter (EsbPackage.Literals.END_POINT_PROPERTY__VALUE_EXPRESSION, EsbFactory.eINSTANCE.createNamespacedProperty())); } /** * Return the resource locator for this item provider's resources. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public ResourceLocator getResourceLocator() { return EsbEditPlugin.INSTANCE; } }
prabushi/devstudio-tooling-esb
plugins/org.wso2.developerstudio.eclipse.gmf.esb.edit/src/org/wso2/developerstudio/eclipse/gmf/esb/provider/EndPointPropertyItemProvider.java
Java
apache-2.0
11,996
// 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_interface.java // Do not modify package org.projectfloodlight.openflow.protocol.bsntlv; 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 io.netty.buffer.ByteBuf; public interface OFBsnTlvExternalGatewayMac extends OFObject, OFBsnTlv { int getType(); MacAddress getValue(); OFVersion getVersion(); void writeTo(ByteBuf channelBuffer); Builder createBuilder(); public interface Builder extends OFBsnTlv.Builder { OFBsnTlvExternalGatewayMac build(); int getType(); MacAddress getValue(); Builder setValue(MacAddress value); OFVersion getVersion(); } }
mehdi149/OF_COMPILER_0.1
gen-src/main/java/org/projectfloodlight/openflow/protocol/bsntlv/OFBsnTlvExternalGatewayMac.java
Java
apache-2.0
1,862
package org.ansj.ansj_lucene_plug; import org.ansj.domain.Term; import org.ansj.library.DicLibrary; import org.ansj.lucene6.AnsjAnalyzer; import org.ansj.lucene6.AnsjAnalyzer.TYPE; import org.ansj.splitWord.analysis.IndexAnalysis; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.TokenStream; import org.apache.lucene.analysis.miscellaneous.PerFieldAnalyzerWrapper; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field.Store; import org.apache.lucene.document.TextField; import org.apache.lucene.index.*; import org.apache.lucene.queryparser.classic.ParseException; import org.apache.lucene.queryparser.classic.QueryParser; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.Query; import org.apache.lucene.search.TopDocs; import org.apache.lucene.search.highlight.Highlighter; import org.apache.lucene.search.highlight.InvalidTokenOffsetsException; import org.apache.lucene.search.highlight.QueryScorer; import org.apache.lucene.search.highlight.SimpleHTMLFormatter; import org.apache.lucene.store.Directory; import org.apache.lucene.store.RAMDirectory; import org.junit.Test; import java.io.IOException; import java.io.StringReader; public class IndexAndTest { @Test public void test() throws Exception { DicLibrary.put(DicLibrary.DEFAULT, "../../library/default.dic"); PerFieldAnalyzerWrapper analyzer = new PerFieldAnalyzerWrapper(new AnsjAnalyzer(TYPE.index_ansj)); Directory directory = null; IndexWriter iwriter = null; IndexWriterConfig ic = new IndexWriterConfig(analyzer); String text = "旅游和服务是最好的"; System.out.println(IndexAnalysis.parse(text)); // 建立内存索引对象 directory = new RAMDirectory(); iwriter = new IndexWriter(directory, ic); addContent(iwriter, text); iwriter.commit(); iwriter.close(); System.out.println("索引建立完毕"); Analyzer queryAnalyzer = new AnsjAnalyzer(AnsjAnalyzer.TYPE.index_ansj); System.out.println("index ok to search!"); for (Term t : IndexAnalysis.parse(text)) { System.out.println(t.getName()); search(queryAnalyzer, directory, "\"" + t.getName() + "\""); } } private void search(Analyzer queryAnalyzer, Directory directory, String queryStr) throws CorruptIndexException, IOException, ParseException { IndexSearcher isearcher; DirectoryReader directoryReader = DirectoryReader.open(directory); // 查询索引 isearcher = new IndexSearcher(directoryReader); QueryParser tq = new QueryParser("text", queryAnalyzer); Query query = tq.parse(queryStr); System.out.println(query); TopDocs hits = isearcher.search(query, 5); System.out.println(queryStr + ":共找到" + hits.totalHits + "条记录!"); for (int i = 0; i < hits.scoreDocs.length; i++) { int docId = hits.scoreDocs[i].doc; Document document = isearcher.doc(docId); System.out.println(toHighlighter(queryAnalyzer, query, document)); } } private void addContent(IndexWriter iwriter, String text) throws CorruptIndexException, IOException { Document doc = new Document(); IndexableField field = new TextField("text", text, Store.YES); doc.add(field); iwriter.addDocument(doc); } /** * 高亮设置 * * @param query * @param doc * @param field * @return */ private String toHighlighter(Analyzer analyzer, Query query, Document doc) { String field = "text"; try { SimpleHTMLFormatter simpleHtmlFormatter = new SimpleHTMLFormatter("<font color=\"red\">", "</font>"); Highlighter highlighter = new Highlighter(simpleHtmlFormatter, new QueryScorer(query)); TokenStream tokenStream1 = analyzer.tokenStream("text", new StringReader(doc.get(field))); String highlighterStr = highlighter.getBestFragment(tokenStream1, doc.get(field)); return highlighterStr == null ? doc.get(field) : highlighterStr; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvalidTokenOffsetsException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } }
NLPchina/ansj_seg
plugin/ansj_lucene6_plugin/src/test/java/org/ansj/ansj_lucene_plug/IndexAndTest.java
Java
apache-2.0
4,074
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.operator; import com.facebook.presto.spi.Page; import com.facebook.presto.spi.PageBuilder; import com.facebook.presto.spi.block.Block; import com.facebook.presto.spi.block.BlockBuilder; import com.facebook.presto.spi.type.Type; import com.facebook.presto.sql.gen.JoinCompiler; import com.facebook.presto.util.array.LongBigArray; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import it.unimi.dsi.fastutil.objects.ObjectArrayList; import java.util.Arrays; import java.util.List; import java.util.Optional; import static com.facebook.presto.operator.SyntheticAddress.decodePosition; import static com.facebook.presto.operator.SyntheticAddress.decodeSliceIndex; import static com.facebook.presto.operator.SyntheticAddress.encodeSyntheticAddress; import static com.facebook.presto.spi.type.BigintType.BIGINT; import static com.facebook.presto.sql.gen.JoinCompiler.PagesHashStrategyFactory; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static io.airlift.slice.SizeOf.sizeOf; import static it.unimi.dsi.fastutil.HashCommon.arraySize; import static it.unimi.dsi.fastutil.HashCommon.murmurHash3; // This implementation assumes arrays used in the hash are always a power of 2 public class MultiChannelGroupByHash implements GroupByHash { private static final JoinCompiler JOIN_COMPILER = new JoinCompiler(); private static final float FILL_RATIO = 0.9f; private final List<Type> types; private final int[] channels; private final PagesHashStrategy hashStrategy; private final List<ObjectArrayList<Block>> channelBuilders; private final HashGenerator hashGenerator; private final Optional<Integer> precomputedHashChannel; private PageBuilder currentPageBuilder; private long completedPagesMemorySize; private int maxFill; private int mask; private long[] key; private int[] value; private final LongBigArray groupAddress; private int nextGroupId; public MultiChannelGroupByHash(List<? extends Type> hashTypes, int[] hashChannels, Optional<Integer> inputHashChannel, int expectedSize) { checkNotNull(hashTypes, "hashTypes is null"); checkArgument(hashTypes.size() == hashChannels.length, "hashTypes and hashChannels have different sizes"); checkNotNull(inputHashChannel, "inputHashChannel is null"); checkArgument(expectedSize > 0, "expectedSize must be greater than zero"); this.types = inputHashChannel.isPresent() ? ImmutableList.copyOf(Iterables.concat(hashTypes, ImmutableList.of(BIGINT))) : ImmutableList.copyOf(hashTypes); this.channels = checkNotNull(hashChannels, "hashChannels is null").clone(); this.hashGenerator = inputHashChannel.isPresent() ? new PrecomputedHashGenerator(inputHashChannel.get()) : new InterpretedHashGenerator(ImmutableList.copyOf(hashTypes), hashChannels); // For each hashed channel, create an appendable list to hold the blocks (builders). As we // add new values we append them to the existing block builder until it fills up and then // we add a new block builder to each list. ImmutableList.Builder<Integer> outputChannels = ImmutableList.builder(); ImmutableList.Builder<ObjectArrayList<Block>> channelBuilders = ImmutableList.builder(); for (int i = 0; i < hashChannels.length; i++) { outputChannels.add(i); channelBuilders.add(ObjectArrayList.wrap(new Block[1024], 0)); } if (inputHashChannel.isPresent()) { this.precomputedHashChannel = Optional.of(hashChannels.length); channelBuilders.add(ObjectArrayList.wrap(new Block[1024], 0)); } else { this.precomputedHashChannel = Optional.empty(); } this.channelBuilders = channelBuilders.build(); PagesHashStrategyFactory pagesHashStrategyFactory = JOIN_COMPILER.compilePagesHashStrategyFactory(this.types, outputChannels.build()); hashStrategy = pagesHashStrategyFactory.createPagesHashStrategy(this.channelBuilders, this.precomputedHashChannel); startNewPage(); // reserve memory for the arrays int hashSize = arraySize(expectedSize, FILL_RATIO); maxFill = calculateMaxFill(hashSize); mask = hashSize - 1; key = new long[hashSize]; Arrays.fill(key, -1); value = new int[hashSize]; groupAddress = new LongBigArray(); groupAddress.ensureCapacity(maxFill); } @Override public long getEstimatedSize() { return (sizeOf(channelBuilders.get(0).elements()) * channelBuilders.size()) + completedPagesMemorySize + currentPageBuilder.getSizeInBytes() + sizeOf(key) + sizeOf(value) + groupAddress.sizeOf(); } @Override public List<Type> getTypes() { return types; } @Override public int getGroupCount() { return nextGroupId; } @Override public void appendValuesTo(int groupId, PageBuilder pageBuilder, int outputChannelOffset) { long address = groupAddress.get(groupId); int blockIndex = decodeSliceIndex(address); int position = decodePosition(address); hashStrategy.appendTo(blockIndex, position, pageBuilder, outputChannelOffset); } @Override public void addPage(Page page) { Block[] hashBlocks = extractHashColumns(page); // get the group id for each position int positionCount = page.getPositionCount(); for (int position = 0; position < positionCount; position++) { // get the group for the current row putIfAbsent(position, page, hashBlocks); } } @Override public GroupByIdBlock getGroupIds(Page page) { int positionCount = page.getPositionCount(); // we know the exact size required for the block BlockBuilder blockBuilder = BIGINT.createFixedSizeBlockBuilder(positionCount); // extract the hash columns Block[] hashBlocks = extractHashColumns(page); // get the group id for each position for (int position = 0; position < positionCount; position++) { // get the group for the current row int groupId = putIfAbsent(position, page, hashBlocks); // output the group id for this row BIGINT.writeLong(blockBuilder, groupId); } return new GroupByIdBlock(nextGroupId, blockBuilder.build()); } @Override public boolean contains(int position, Page page) { int rawHash = hashStrategy.hashRow(position, page.getBlocks()); int hashPosition = getHashPosition(rawHash, mask); // look for a slot containing this key while (key[hashPosition] != -1) { long address = key[hashPosition]; if (hashStrategy.positionEqualsRow(decodeSliceIndex(address), decodePosition(address), position, page.getBlocks())) { // found an existing slot for this key return true; } // increment position and mask to handle wrap around hashPosition = (hashPosition + 1) & mask; } return false; } @Override public int putIfAbsent(int position, Page page) { return putIfAbsent(position, page, extractHashColumns(page)); } private int putIfAbsent(int position, Page page, Block[] hashBlocks) { int rawHash = hashGenerator.hashPosition(position, page); int hashPosition = getHashPosition(rawHash, mask); // look for an empty slot or a slot containing this key int groupId = -1; while (key[hashPosition] != -1) { long address = key[hashPosition]; if (positionEqualsCurrentRow(decodeSliceIndex(address), decodePosition(address), position, hashBlocks)) { // found an existing slot for this key groupId = value[hashPosition]; break; } // increment position and mask to handle wrap around hashPosition = (hashPosition + 1) & mask; } // did we find an existing group? if (groupId < 0) { groupId = addNewGroup(hashPosition, position, page, rawHash); } return groupId; } private int addNewGroup(int hashPosition, int position, Page page, int rawHash) { // add the row to the open page Block[] blocks = page.getBlocks(); for (int i = 0; i < channels.length; i++) { int hashChannel = channels[i]; Type type = types.get(i); type.appendTo(blocks[hashChannel], position, currentPageBuilder.getBlockBuilder(i)); } if (precomputedHashChannel.isPresent()) { BIGINT.writeLong(currentPageBuilder.getBlockBuilder(precomputedHashChannel.get()), rawHash); } currentPageBuilder.declarePosition(); int pageIndex = channelBuilders.get(0).size() - 1; int pagePosition = currentPageBuilder.getPositionCount() - 1; long address = encodeSyntheticAddress(pageIndex, pagePosition); // record group id in hash int groupId = nextGroupId++; key[hashPosition] = address; value[hashPosition] = groupId; groupAddress.set(groupId, address); // create new page builder if this page is full if (currentPageBuilder.isFull()) { startNewPage(); } // increase capacity, if necessary if (nextGroupId >= maxFill) { rehash(maxFill * 2); } return groupId; } private void startNewPage() { if (currentPageBuilder != null) { completedPagesMemorySize += currentPageBuilder.getSizeInBytes(); } currentPageBuilder = new PageBuilder(types); for (int i = 0; i < types.size(); i++) { channelBuilders.get(i).add(currentPageBuilder.getBlockBuilder(i)); } } private void rehash(int size) { int newSize = arraySize(size + 1, FILL_RATIO); int newMask = newSize - 1; long[] newKey = new long[newSize]; Arrays.fill(newKey, -1); int[] newValue = new int[newSize]; int oldIndex = 0; for (int groupId = 0; groupId < nextGroupId; groupId++) { // seek to the next used slot while (key[oldIndex] == -1) { oldIndex++; } // get the address for this slot long address = key[oldIndex]; // find an empty slot for the address int pos = getHashPosition(hashPosition(address), newMask); while (newKey[pos] != -1) { pos = (pos + 1) & newMask; } // record the mapping newKey[pos] = address; newValue[pos] = value[oldIndex]; oldIndex++; } this.mask = newMask; this.maxFill = calculateMaxFill(newSize); this.key = newKey; this.value = newValue; groupAddress.ensureCapacity(maxFill); } private Block[] extractHashColumns(Page page) { Block[] hashBlocks = new Block[channels.length]; for (int i = 0; i < channels.length; i++) { hashBlocks[i] = page.getBlock(channels[i]); } return hashBlocks; } private int hashPosition(long sliceAddress) { int sliceIndex = decodeSliceIndex(sliceAddress); int position = decodePosition(sliceAddress); if (precomputedHashChannel.isPresent()) { return getRawHash(sliceIndex, position); } return hashStrategy.hashPosition(sliceIndex, position); } private int getRawHash(int sliceIndex, int position) { return (int) channelBuilders.get(precomputedHashChannel.get()).get(sliceIndex).getLong(position, 0); } private boolean positionEqualsCurrentRow(int sliceIndex, int slicePosition, int position, Block[] blocks) { return hashStrategy.positionEqualsRow(sliceIndex, slicePosition, position, blocks); } private static int getHashPosition(int rawHash, int mask) { return murmurHash3(rawHash) & mask; } private static int calculateMaxFill(int hashSize) { checkArgument(hashSize > 0, "hashSize must greater than 0"); int maxFill = (int) Math.ceil(hashSize * FILL_RATIO); if (maxFill == hashSize) { maxFill--; } checkArgument(hashSize > maxFill, "hashSize must be larger than maxFill"); return maxFill; } }
pnowojski/presto
presto-main/src/main/java/com/facebook/presto/operator/MultiChannelGroupByHash.java
Java
apache-2.0
13,353
export { Clock } from './Clock';
HewlettPackard/grommet
src/js/components/Clock/index.js
JavaScript
apache-2.0
33
/* * JFoenix * Copyright (c) 2015, JFoenix and/or its affiliates., 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 3.0 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. */ package demos.components; import com.jfoenix.controls.JFXDatePicker; import com.jfoenix.controls.JFXTimePicker; import demos.MainDemo; import javafx.application.Application; import javafx.collections.ObservableList; import javafx.geometry.Insets; import javafx.scene.Scene; import javafx.scene.control.DatePicker; import javafx.scene.layout.FlowPane; import javafx.scene.layout.StackPane; import javafx.scene.paint.Color; import javafx.stage.Stage; public class DatePickerDemo extends Application { @Override public void start(Stage stage) { FlowPane main = new FlowPane(); main.setVgap(20); main.setHgap(20); DatePicker datePicker = new DatePicker(); main.getChildren().add(datePicker); JFXDatePicker datePickerFX = new JFXDatePicker(); main.getChildren().add(datePickerFX); datePickerFX.setPromptText("pick a date"); JFXTimePicker blueDatePicker = new JFXTimePicker(); blueDatePicker.setDefaultColor(Color.valueOf("#3f51b5")); blueDatePicker.setOverLay(true); main.getChildren().add(blueDatePicker); StackPane pane = new StackPane(); pane.getChildren().add(main); StackPane.setMargin(main, new Insets(100)); pane.setStyle("-fx-background-color:WHITE"); final Scene scene = new Scene(pane, 400, 700); final ObservableList<String> stylesheets = scene.getStylesheets(); stylesheets.addAll(MainDemo.class.getResource("/css/jfoenix-fonts.css").toExternalForm(), MainDemo.class.getResource("/css/jfoenix-design.css").toExternalForm()); stage.setTitle("JFX Date Picker Demo"); stage.setScene(scene); stage.show(); } public static void main(String[] args) { launch(args); } }
jfoenixadmin/JFoenix
demo/src/main/java/demos/components/DatePickerDemo.java
Java
apache-2.0
2,537
package com.planet_ink.coffee_mud.Abilities.Spells; import com.planet_ink.coffee_mud.core.interfaces.*; import com.planet_ink.coffee_mud.core.*; import com.planet_ink.coffee_mud.Abilities.interfaces.*; import com.planet_ink.coffee_mud.Areas.interfaces.*; import com.planet_ink.coffee_mud.Behaviors.interfaces.*; import com.planet_ink.coffee_mud.CharClasses.interfaces.*; import com.planet_ink.coffee_mud.Commands.interfaces.*; import com.planet_ink.coffee_mud.Common.interfaces.*; import com.planet_ink.coffee_mud.Exits.interfaces.*; import com.planet_ink.coffee_mud.Items.interfaces.*; import com.planet_ink.coffee_mud.Locales.interfaces.*; import com.planet_ink.coffee_mud.MOBS.interfaces.*; import com.planet_ink.coffee_mud.Races.interfaces.*; import java.util.*; /* Copyright 2000-2010 Bo Zimmerman 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. */ @SuppressWarnings("unchecked") public class Spell_Blademouth extends Spell { public String ID() { return "Spell_Blademouth"; } public String name(){return "Blademouth";} public String displayText(){return "(blades in your mouth)";} public int abstractQuality(){return Ability.QUALITY_MALICIOUS;} protected int canAffectCode(){return CAN_MOBS;} public int classificationCode(){ return Ability.ACODE_SPELL|Ability.DOMAIN_EVOCATION;} public Vector limbsToRemove=new Vector(); protected boolean noRecurse=false; public void executeMsg(Environmental host, CMMsg msg) { if((msg.sourceMinor()==CMMsg.TYP_SPEAK) &&(!noRecurse) &&(affected instanceof MOB) &&(invoker!=null) &&(msg.amISource((MOB)affected)) &&(msg.source().location()!=null) &&(msg.source().charStats().getMyRace().bodyMask()[Race.BODY_MOUTH]>=0)) { noRecurse=true; try{CMLib.combat().postDamage(invoker,msg.source(),this,msg.source().maxState().getHitPoints()/10,CMMsg.MASK_ALWAYS|CMMsg.TYP_CAST_SPELL,Weapon.TYPE_SLASHING,"The blades in <T-YOUPOSS> mouth <DAMAGE> <T-HIM-HER>!"); }finally{noRecurse=false;} } super.executeMsg(host,msg); } public int castingQuality(MOB mob, Environmental target) { if(mob!=null) { if(target instanceof MOB) { if(((MOB)target).charStats().getMyRace().bodyMask()[Race.BODY_MOUTH]<=0) return Ability.QUALITY_INDIFFERENT; } } return super.castingQuality(mob,target); } public boolean invoke(MOB mob, Vector commands, Environmental givenTarget, boolean auto, int asLevel) { MOB target=this.getTarget(mob,commands,givenTarget); if(target==null) return false; if(target.charStats().getMyRace().bodyMask()[Race.BODY_MOUTH]<=0) { if(!auto) mob.tell("There is no mouth on "+target.name()+" to fill with blades!"); return false; } // the invoke method for spells receives as // parameters the invoker, and the REMAINING // command line parameters, divided into words, // and added as String objects to a vector. if(!super.invoke(mob,commands,givenTarget,auto,asLevel)) return false; // now see if it worked boolean success=proficiencyCheck(mob,0,auto); if(success) { // it worked, so build a copy of this ability, // and add it to the affects list of the // affected MOB. Then tell everyone else // what happened. CMMsg msg=CMClass.getMsg(mob,target,this,verbalCastCode(mob,target,auto),(auto?"!":"^S<S-NAME> invoke(s) a sharp spell upon <T-NAMESELF>")); if(mob.location().okMessage(mob,msg)) { mob.location().send(mob,msg); super.maliciousAffect(mob,target,asLevel,0,-1); } } else return maliciousFizzle(mob,target,"<S-NAME> incant(s) sharply at <T-NAMESELF>, but flub(s) the spell."); // return whether it worked return success; } }
welterde/ewok
com/planet_ink/coffee_mud/Abilities/Spells/Spell_Blademouth.java
Java
apache-2.0
4,439
import greenfoot.*; public class insert extends Actor { pause p = new pause(); player pa = new player(); GreenfootSound SFX2 = new GreenfootSound("sfx/button_click.mp3"); public void act() { setLocation(550, 275); if(Greenfoot.isKeyDown("escape")) { SFX2.play(); getWorld().removeObjects(getWorld().getObjects(insert.class)); p.setPaused(false); } if(Greenfoot.isKeyDown("enter")) { SFX2.play(); if(pa.getKey() && getWorld().getObjects(complete.class).isEmpty()) { getWorld().addObject(new complete(),550,275); } else if(!pa.getKey() && getWorld().getObjects(no_key.class).isEmpty()) { getWorld().addObject(new no_key(),550,275); } } } }
Juklabs/edmundo
insert.java
Java
apache-2.0
757
/* * 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.logging.v2.model; /** * Specifies a location in a source code file. * * <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 Cloud Logging 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 SourceLocation extends com.google.api.client.json.GenericJson { /** * Source file name. Depending on the runtime environment, this might be a simple name or a fully- * qualified name. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String file; /** * Human-readable name of the function or method being invoked, with optional context such as the * class or package name. This information is used in contexts such as the logs viewer, where a * file and line number are less meaningful. The format can vary by language. For example: * qual.if.ied.Class.method (Java), dir/package.func (Go), function (Python). * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String functionName; /** * Line within the source file. * The value may be {@code null}. */ @com.google.api.client.util.Key @com.google.api.client.json.JsonString private java.lang.Long line; /** * Source file name. Depending on the runtime environment, this might be a simple name or a fully- * qualified name. * @return value or {@code null} for none */ public java.lang.String getFile() { return file; } /** * Source file name. Depending on the runtime environment, this might be a simple name or a fully- * qualified name. * @param file file or {@code null} for none */ public SourceLocation setFile(java.lang.String file) { this.file = file; return this; } /** * Human-readable name of the function or method being invoked, with optional context such as the * class or package name. This information is used in contexts such as the logs viewer, where a * file and line number are less meaningful. The format can vary by language. For example: * qual.if.ied.Class.method (Java), dir/package.func (Go), function (Python). * @return value or {@code null} for none */ public java.lang.String getFunctionName() { return functionName; } /** * Human-readable name of the function or method being invoked, with optional context such as the * class or package name. This information is used in contexts such as the logs viewer, where a * file and line number are less meaningful. The format can vary by language. For example: * qual.if.ied.Class.method (Java), dir/package.func (Go), function (Python). * @param functionName functionName or {@code null} for none */ public SourceLocation setFunctionName(java.lang.String functionName) { this.functionName = functionName; return this; } /** * Line within the source file. * @return value or {@code null} for none */ public java.lang.Long getLine() { return line; } /** * Line within the source file. * @param line line or {@code null} for none */ public SourceLocation setLine(java.lang.Long line) { this.line = line; return this; } @Override public SourceLocation set(String fieldName, Object value) { return (SourceLocation) super.set(fieldName, value); } @Override public SourceLocation clone() { return (SourceLocation) super.clone(); } }
googleapis/google-api-java-client-services
clients/google-api-services-logging/v2/1.31.0/com/google/api/services/logging/v2/model/SourceLocation.java
Java
apache-2.0
4,414
package org.geojson; import java.util.List; public class MultiLineString extends Geometry<List<LngLatAlt>> { public MultiLineString() { } public MultiLineString(List<LngLatAlt> line) { add(line); } @Override public <T> T accept(GeoJsonObjectVisitor<T> geoJsonObjectVisitor) { return geoJsonObjectVisitor.visit(this); } @Override public String toString() { return "MultiLineString{} " + super.toString(); } }
mastinno/geojson-jackson-java
src/main/java/org/geojson/MultiLineString.java
Java
apache-2.0
430
/** * Copyright 2013-2019 the original author or authors from the Jeddict project (https://jeddict.github.io/). * * 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 * workingCopy 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.github.jeddict.jcode; /** * * @author Gaurav Gupta */ public class SecurityConstants { public static final String EMBEDDED_IDENTITY_STORE_DEFINITION = "javax.security.identitystore.annotation.EmbeddedIdentityStoreDefinition"; public static final String CREDENTIALS = "javax.security.identitystore.annotation.Credentials"; public static final String CALLER_NAME = "callerName"; public static final String PASSWORD = "password"; public static final String DEFAULT_CREDENTIALS = "user"; }
jGauravGupta/jpamodeler
jcode-util/src/main/java/io/github/jeddict/jcode/SecurityConstants.java
Java
apache-2.0
1,229
# coding=utf-8 import os.path import sys import types import getopt from getopt import GetoptError import text_file import regex_utils import string_utils as str_utils def grep(target, pattern, number = False, model = 'e'): ''' grep: print lines matching a pattern @param target:string list or text file name @param pattern: regex pattern or line number pattern or reduce function: bool=action(str) @param number: with line number @param model: s: substring model, e: regex model, n: line number model, a: action model @summary: list= ['1:huiyugeng:male', '2:zhuzhu:male', '3:maomao:female'] print grep.grep(list, '^(?!.*female).*$', ':', [1]) output: ['huiyugeng', 'zhuzhu'] ''' if isinstance(target, basestring): text = text_file.read_file(target) elif isinstance(target, list): text = target else: text = None if not text: return None line_num = 1; result = [] for line_text in text: line_text = str(line_text) if __match(line_num, line_text, model, pattern): line_text = __print(line_num, line_text, number) if line_text != None: result.append(line_text) line_num = line_num + 1 return result def __match(line_num, line_text, model, pattern): if str_utils.is_blank(line_text): return False if str_utils.is_blank(pattern): return True patterns = [] if type(pattern) == types.ListType: patterns = pattern elif type(pattern) == types.FunctionType: patterns = [pattern] else: patterns = [str(pattern)] if str_utils.is_empty(model) : model = 's' model = model.lower() for match_pattern in patterns: if model == 's': if match_pattern in line_text: return True elif model == 'n': _min, _max = __split_region(match_pattern) if line_num >= _min and line_num <= _max: return True elif model == 'e': if regex_utils.check_line(match_pattern, line_text): return True elif model == 'a': if type(pattern) == types.FunctionType: if pattern(line_text): return True return False def __split_region(pattern): if pattern.startswith('[') and pattern.endswith(']') and ',' in pattern: region = pattern[1: len(pattern) - 1].split(',') if region != None and len(region) == 2: _min = int(region[0].strip()) _max = int(region[1].strip()) return _min, _max return 0, 0 def __print(line, text, number): if number: return str(line) + ':' + text.strip() else: return text.strip() def exec_cmd(argv): try: filename = None pattern = None number = False model = 'e' if len(argv) > 2: opts, _ = getopt.getopt(argv[2:],'hf:p:nm:', ['help', '--file', '--pattern', '--number', '--model']) for name, value in opts: if name in ('-h', '--help'): show_help() if name in ('-f', '--file'): filename = value if name in ('-p', '--pattern'): pattern = value if name in ('-n', '--number'): number = True if name in ('-m', '--model'): model = value if str_utils.is_empty(filename) or not os.path.exists(filename): print 'error : could not find file : ' + filename sys.exit() if str_utils.is_empty(pattern): print 'error : pattern is empty' sys.exit() result = grep(filename, pattern, number, model) if result and isinstance(result, list): for line in result: print line else: show_help() except GetoptError, e: print 'error : ' + e.msg except Exception, e: print 'error : ' + e.message def show_help(): pass
interhui/py-text
text/grep.py
Python
apache-2.0
4,283
/* * Copyright 2014 JBoss 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.teiid.webui.client.widgets; import org.jboss.errai.ui.client.widget.ListWidget; import com.google.gwt.user.client.ui.FlowPanel; /** * ServiceFlowPanel - extends Errai ListWidget, providing the desired Flow behavior for the DataServicesLibraryScreen * */ public class ServiceFlowListWidget extends ListWidget<ServiceRow, LibraryServiceWidget> { public ServiceFlowListWidget() { super(new FlowPanel()); } @Override public Class<LibraryServiceWidget> getItemWidgetType() { return LibraryServiceWidget.class; } }
Teiid-Designer/teiid-webui
teiid-webui-webapp/src/main/java/org/teiid/webui/client/widgets/ServiceFlowListWidget.java
Java
apache-2.0
1,154
/******************************************************************************* * Copyright 2013 * Ubiquitous Knowledge Processing (UKP) Lab * Technische Universität Darmstadt * * 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 dkpro.similarity.experiments.wordpairs.io; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; import org.apache.commons.lang.ArrayUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.math3.stat.correlation.PearsonsCorrelation; import org.apache.commons.math3.stat.correlation.SpearmansCorrelation; import org.apache.uima.analysis_engine.AnalysisEngineProcessException; import org.apache.uima.fit.component.JCasAnnotator_ImplBase; import org.apache.uima.fit.descriptor.ConfigurationParameter; import org.apache.uima.fit.util.JCasUtil; import org.apache.uima.jcas.JCas; import de.tudarmstadt.ukp.dkpro.core.api.metadata.type.DocumentMetaData; import dkpro.similarity.type.SemRelWordPair; import dkpro.similarity.type.SemanticRelatedness; public class SemanticRelatednessResultWriter extends JCasAnnotator_ImplBase { private static final String SEP = ":"; private static final String LF = System.getProperty("line.separator"); public static final String PARAM_SHOW_DETAILS = "ShowDetails"; @ConfigurationParameter(name = PARAM_SHOW_DETAILS, mandatory=true, defaultValue="false") private boolean showDetails; @Override public void process(JCas jcas) throws AnalysisEngineProcessException { Result result = new Result(); for (SemanticRelatedness sr : JCasUtil.select(jcas, SemanticRelatedness.class)) { String measureName = sr.getMeasureName(); String measureType = sr.getMeasureType(); String term1 = sr.getTerm1(); String term2 = sr.getTerm2(); double relatednessValue = sr.getRelatednessValue(); String measureKey = measureType + "-" + measureName; SemRelWordPair wp = (SemRelWordPair) sr.getWordPair(); result.addScore(term1, term2, measureKey, relatednessValue, wp.getGoldValue()); } if (showDetails) { System.out.println("UNFILTERED"); System.out.println(result.getWordpairs().size() + " word pairs"); System.out.println( getFormattedResultMap(result) ); } // filter invalid keys in the result object (i.e. wordpairs where at least one measure returned NOT_FOUND) Result filteredResult = getFilteredResult(result); if (showDetails) { System.out.println("FILTERED"); System.out.println(filteredResult.getWordpairs().size() + " word pairs"); System.out.println( getFormattedResultMap(filteredResult) ); } if (showDetails) { System.out.println(DocumentMetaData.get(jcas).getDocumentTitle()); System.out.println( getMeasures(filteredResult) ); System.out.println( getCorrelations(filteredResult) ); System.out.println(); } else { for (String measure : filteredResult.measures) { System.out.println(getShortResults(filteredResult, measure, DocumentMetaData.get(jcas).getDocumentTitle())); } } } private String getFormattedResultMap(Result result) { StringBuilder sb = new StringBuilder(); sb.append("Term1"); sb.append(SEP); sb.append("Term2"); sb.append(SEP); sb.append("Gold"); sb.append(SEP); sb.append(StringUtils.join(result.getMeasures(), SEP)); sb.append(LF); for (String wordpair : result.getWordpairs()) { sb.append(wordpair); sb.append(SEP); sb.append(result.getGoldValue(wordpair)); for (String measure : result.getMeasures()) { sb.append(SEP); sb.append(result.getScore(wordpair, measure)); } sb.append(LF); } sb.append(LF); return sb.toString(); } private class Result { private final Map<String,Scores> wordpairScoresMap; private final Map<String,Double> wordpairGoldMap; private final Set<String> measures; public Result() { wordpairScoresMap = new TreeMap<String,Scores>(); wordpairGoldMap = new TreeMap<String,Double>(); measures = new TreeSet<String>(); } public void addScore(String term1, String term2, String measureKey, double relatednessValue, double goldValue) throws AnalysisEngineProcessException { String key = getKeyTerm(term1, term2); addScore(key, measureKey, relatednessValue, goldValue); } public void addScore(String key, String measureKey, double relatednessValue, double goldValue) throws AnalysisEngineProcessException { measures.add(measureKey); if ( //word pair is already stored in map wordpairGoldMap.containsKey(key) && //it has been evaluated with the same measure "measureKey" wordpairScoresMap.get( key ).containsMeasure(measureKey) ) { System.out.println("wordpairGoldMap already contains key: " + key); System.out.println("Ignoring this duplicate word pair. Duplicates might occurr because of stemming."); return; } wordpairGoldMap.put(key, goldValue); if (wordpairScoresMap.containsKey(key)) { Scores scores = wordpairScoresMap.get( key ); scores.update(measureKey, relatednessValue); wordpairScoresMap.put(key, scores); } else { Scores scores = new Scores(measureKey, relatednessValue); wordpairScoresMap.put(key, scores); } } public Set<String> getMeasures() { return measures; } public Set<String> getWordpairs() { return wordpairScoresMap.keySet(); } public Double getScore(String wordpair, String measure) { return wordpairScoresMap.get(wordpair).getValue(measure); } public Double getGoldValue(String wordpair) { return wordpairGoldMap.get(wordpair); } /** * @return The list of gold standard values in key sorted order. */ public List<Double> getGoldList() { List<Double> goldList = new ArrayList<Double>(); for (String wordpair : wordpairGoldMap.keySet()) { goldList.add(wordpairGoldMap.get(wordpair)); } return goldList; } /** * @param measure * @return The list of scores for the given measure in key sorted order. */ public List<Double> getScoreList(String measure) { List<Double> scoreList = new ArrayList<Double>(); for (String wordpair : wordpairGoldMap.keySet()) { scoreList.add(wordpairScoresMap.get(wordpair).getValue(measure)); } return scoreList; } private String getKeyTerm(String term1, String term2) { String key; if (term1.compareTo(term2) < 0) { key = term1 + SEP + term2; } else { key = term2 + SEP + term1; } return key; } } private static class Scores { private final Map<String,Double> measureScoreMap; public Scores(String measureKey, double relatednessValue) { measureScoreMap = new TreeMap<String,Double>(); measureScoreMap.put(measureKey, relatednessValue); } public void update(String measureKey, double relatednessValue) throws AnalysisEngineProcessException { if (measureScoreMap.containsKey(measureKey)) { throw new AnalysisEngineProcessException(new Throwable("Score for measure " + measureKey + " already exists. Do you have run the measure twice? Might also be caused by a duplicate word pair (e.g. money-cash and bank-money/money-bank are included twice in the original Fikelstein-353 dataset).")); } measureScoreMap.put(measureKey, relatednessValue); } public boolean containsMeasure(String measure) { return measureScoreMap.containsKey(measure); } public Double getValue(String measure) { return measureScoreMap.get(measure); } } private Result getFilteredResult(Result result) throws AnalysisEngineProcessException { Set<String> wordpairsToFilter = new HashSet<String>(); for (String wordpair : result.getWordpairs()) { for (String measure : result.getMeasures()) { if (result.getScore(wordpair, measure) == null) { wordpairsToFilter.add(wordpair); } else if (result.getScore(wordpair, measure) < 0.0) { wordpairsToFilter.add(wordpair); } } } Result filteredResult = new Result(); for (String wordpair : result.getWordpairs()) { if (!wordpairsToFilter.contains(wordpair)) { for (String measure : result.getMeasures()) { filteredResult.addScore(wordpair, measure, result.getScore(wordpair, measure), result.getGoldValue(wordpair)); } } } return filteredResult; } private String getShortResults(Result result, String measure, String document) { StringBuilder sb = new StringBuilder(); sb.append("RESULT"); sb.append(SEP); sb.append(document); sb.append(SEP); sb.append(measure); sb.append(SEP); List<Double> scoreList = result.getScoreList(measure); List<Double> goldList = result.getGoldList(); double pearsonCorrelation = new PearsonsCorrelation().correlation( ArrayUtils.toPrimitive(goldList.toArray(new Double[goldList.size()])), ArrayUtils.toPrimitive(scoreList.toArray(new Double[goldList.size()])) ); double spearmanCorrelation = new SpearmansCorrelation().correlation( ArrayUtils.toPrimitive(goldList.toArray(new Double[goldList.size()])), ArrayUtils.toPrimitive(scoreList.toArray(new Double[goldList.size()])) ); sb.append(spearmanCorrelation); sb.append(SEP); sb.append(pearsonCorrelation); return sb.toString(); } private String getCorrelations(Result result) { Map<String,Double> pearsonCorrelationMap = new HashMap<String,Double>(); Map<String,Double> spearmanCorrelationMap = new HashMap<String,Double>(); List<Double> goldList = result.getGoldList(); for (String measure : result.getMeasures()) { List<Double> scoreList = result.getScoreList(measure); double pearsonCorrelation = new PearsonsCorrelation().correlation( ArrayUtils.toPrimitive(goldList.toArray(new Double[goldList.size()])), ArrayUtils.toPrimitive(scoreList.toArray(new Double[goldList.size()])) ); pearsonCorrelationMap.put(measure, pearsonCorrelation); double spearmanCorrelation = new SpearmansCorrelation().correlation( ArrayUtils.toPrimitive(goldList.toArray(new Double[goldList.size()])), ArrayUtils.toPrimitive(scoreList.toArray(new Double[goldList.size()])) ); spearmanCorrelationMap.put(measure, spearmanCorrelation); } StringBuilder sb = new StringBuilder(); sb.append("Pearson: "); for (String measure : result.getMeasures()) { sb.append(pearsonCorrelationMap.get(measure)); sb.append(SEP); } sb.append(LF); sb.append("Spearman: "); for (String measure : result.getMeasures()) { sb.append(spearmanCorrelationMap.get(measure)); sb.append(SEP); } return sb.toString(); } private String getMeasures(Result result) { StringBuilder sb = new StringBuilder(); sb.append("Measure: "); for (String measure : result.getMeasures()) { sb.append(measure); sb.append(SEP); } return sb.toString(); } }
TitasNandi/Summer_Project
dkpro-similarity-master/dkpro-similarity-experiments-wordpairs-asl/src/main/java/dkpro/similarity/experiments/wordpairs/io/SemanticRelatednessResultWriter.java
Java
apache-2.0
13,282
package org.wso2.carbon.identity.configuration.mgt.endpoint.dto; import io.swagger.annotations.*; import com.fasterxml.jackson.annotation.*; import javax.validation.constraints.NotNull; @ApiModel(description = "") public class ResourceFileDTO { @NotNull private String name = null; private String file = null; /** * Describes the name of the file. **/ @ApiModelProperty(required = true, value = "Describes the name of the file.") @JsonProperty("name") public String getName() { return name; } public void setName(String name) { this.name = name; } /** * Provide the location of the file **/ @ApiModelProperty(value = "Provide the location of the file") @JsonProperty("file") public String getFile() { return file; } public void setFile(String file) { this.file = file; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class ResourceFileDTO {\n"); sb.append(" name: ").append(name).append("\n"); sb.append(" file: ").append(file).append("\n"); sb.append("}\n"); return sb.toString(); } }
omindu/carbon-identity-framework
components/configuration-mgt/org.wso2.carbon.identity.api.server.configuration.mgt/src/gen/java/org/wso2/carbon/identity/configuration/mgt/endpoint/dto/ResourceFileDTO.java
Java
apache-2.0
1,162
package mocks import ( cli "github.com/stackanetes/kubernetes-entrypoint/client" ) type MockEntrypoint struct { client cli.ClientInterface namespace string } func (m MockEntrypoint) Resolve() { } func (m MockEntrypoint) Client() (client cli.ClientInterface) { return m.client } func (m MockEntrypoint) GetNamespace() (namespace string) { return m.namespace } func NewEntrypointInNamespace(namespace string) MockEntrypoint { return MockEntrypoint{ client: NewClient(), namespace: namespace, } } func NewEntrypoint() MockEntrypoint { return NewEntrypointInNamespace("test") }
antoni/kubernetes-entrypoint
mocks/entrypoint.go
GO
apache-2.0
599
/* * 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.monitoring.v3.model; /** * Detailed information about an error category. * * <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 Cloud Monitoring 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 Error extends com.google.api.client.json.GenericJson { /** * The number of points that couldn't be written because of status. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Integer pointCount; /** * The status of the requested write operation. * The value may be {@code null}. */ @com.google.api.client.util.Key private Status status; /** * The number of points that couldn't be written because of status. * @return value or {@code null} for none */ public java.lang.Integer getPointCount() { return pointCount; } /** * The number of points that couldn't be written because of status. * @param pointCount pointCount or {@code null} for none */ public Error setPointCount(java.lang.Integer pointCount) { this.pointCount = pointCount; return this; } /** * The status of the requested write operation. * @return value or {@code null} for none */ public Status getStatus() { return status; } /** * The status of the requested write operation. * @param status status or {@code null} for none */ public Error setStatus(Status status) { this.status = status; return this; } @Override public Error set(String fieldName, Object value) { return (Error) super.set(fieldName, value); } @Override public Error clone() { return (Error) super.clone(); } }
googleapis/google-api-java-client-services
clients/google-api-services-monitoring/v3/1.31.0/com/google/api/services/monitoring/v3/model/Error.java
Java
apache-2.0
2,686
package org.hl7.fhir.dstu3.model; /* Copyright (c) 2011+, HL7, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of HL7 nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // Generated on Tue, Dec 6, 2016 09:42-0500 for FHIR v1.8.0 import java.util.*; import org.hl7.fhir.utilities.Utilities; import org.hl7.fhir.dstu3.model.Enumerations.*; import ca.uhn.fhir.model.api.annotation.ResourceDef; import ca.uhn.fhir.model.api.annotation.SearchParamDefinition; import ca.uhn.fhir.model.api.annotation.Child; import ca.uhn.fhir.model.api.annotation.ChildOrder; import ca.uhn.fhir.model.api.annotation.Description; import ca.uhn.fhir.model.api.annotation.Block; import org.hl7.fhir.instance.model.api.*; import org.hl7.fhir.exceptions.FHIRException; /** * Demographics and other administrative information about an individual or animal receiving care or other health-related services. */ @ResourceDef(name="Patient", profile="http://hl7.org/fhir/Profile/Patient") public class Patient extends DomainResource { public enum LinkType { /** * The patient resource containing this link must no longer be used. The link points forward to another patient resource that must be used in lieu of the patient resource that contains this link. */ REPLACE, /** * The patient resource containing this link is in use and valid but not considered the main source of information about a patient. The link points forward to another patient resource that should be consulted to retrieve additional patient information. */ REFER, /** * The patient resource containing this link is in use and valid, but points to another patient resource that is known to contain data about the same person. Data in this resource might overlap or contradict information found in the other patient resource. This link does not indicate any relative importance of the resources concerned, and both should be regarded as equally valid. */ SEEALSO, /** * added to help the parsers with the generic types */ NULL; public static LinkType fromCode(String codeString) throws FHIRException { if (codeString == null || "".equals(codeString)) return null; if ("replace".equals(codeString)) return REPLACE; if ("refer".equals(codeString)) return REFER; if ("seealso".equals(codeString)) return SEEALSO; if (Configuration.isAcceptInvalidEnums()) return null; else throw new FHIRException("Unknown LinkType code '"+codeString+"'"); } public String toCode() { switch (this) { case REPLACE: return "replace"; case REFER: return "refer"; case SEEALSO: return "seealso"; default: return "?"; } } public String getSystem() { switch (this) { case REPLACE: return "http://hl7.org/fhir/link-type"; case REFER: return "http://hl7.org/fhir/link-type"; case SEEALSO: return "http://hl7.org/fhir/link-type"; default: return "?"; } } public String getDefinition() { switch (this) { case REPLACE: return "The patient resource containing this link must no longer be used. The link points forward to another patient resource that must be used in lieu of the patient resource that contains this link."; case REFER: return "The patient resource containing this link is in use and valid but not considered the main source of information about a patient. The link points forward to another patient resource that should be consulted to retrieve additional patient information."; case SEEALSO: return "The patient resource containing this link is in use and valid, but points to another patient resource that is known to contain data about the same person. Data in this resource might overlap or contradict information found in the other patient resource. This link does not indicate any relative importance of the resources concerned, and both should be regarded as equally valid."; default: return "?"; } } public String getDisplay() { switch (this) { case REPLACE: return "Replace"; case REFER: return "Refer"; case SEEALSO: return "See also"; default: return "?"; } } } public static class LinkTypeEnumFactory implements EnumFactory<LinkType> { public LinkType fromCode(String codeString) throws IllegalArgumentException { if (codeString == null || "".equals(codeString)) if (codeString == null || "".equals(codeString)) return null; if ("replace".equals(codeString)) return LinkType.REPLACE; if ("refer".equals(codeString)) return LinkType.REFER; if ("seealso".equals(codeString)) return LinkType.SEEALSO; throw new IllegalArgumentException("Unknown LinkType code '"+codeString+"'"); } public Enumeration<LinkType> fromType(Base code) throws FHIRException { if (code == null || code.isEmpty()) return null; String codeString = ((PrimitiveType) code).asStringValue(); if (codeString == null || "".equals(codeString)) return null; if ("replace".equals(codeString)) return new Enumeration<LinkType>(this, LinkType.REPLACE); if ("refer".equals(codeString)) return new Enumeration<LinkType>(this, LinkType.REFER); if ("seealso".equals(codeString)) return new Enumeration<LinkType>(this, LinkType.SEEALSO); throw new FHIRException("Unknown LinkType code '"+codeString+"'"); } public String toCode(LinkType code) { if (code == LinkType.REPLACE) return "replace"; if (code == LinkType.REFER) return "refer"; if (code == LinkType.SEEALSO) return "seealso"; return "?"; } public String toSystem(LinkType code) { return code.getSystem(); } } @Block() public static class ContactComponent extends BackboneElement implements IBaseBackboneElement { /** * The nature of the relationship between the patient and the contact person. */ @Child(name = "relationship", type = {CodeableConcept.class}, order=1, min=0, max=Child.MAX_UNLIMITED, modifier=false, summary=false) @Description(shortDefinition="The kind of relationship", formalDefinition="The nature of the relationship between the patient and the contact person." ) @ca.uhn.fhir.model.api.annotation.Binding(valueSet="http://hl7.org/fhir/ValueSet/v2-0131") protected List<CodeableConcept> relationship; /** * A name associated with the contact person. */ @Child(name = "name", type = {HumanName.class}, order=2, min=0, max=1, modifier=false, summary=false) @Description(shortDefinition="A name associated with the contact person", formalDefinition="A name associated with the contact person." ) protected HumanName name; /** * A contact detail for the person, e.g. a telephone number or an email address. */ @Child(name = "telecom", type = {ContactPoint.class}, order=3, min=0, max=Child.MAX_UNLIMITED, modifier=false, summary=false) @Description(shortDefinition="A contact detail for the person", formalDefinition="A contact detail for the person, e.g. a telephone number or an email address." ) protected List<ContactPoint> telecom; /** * Address for the contact person. */ @Child(name = "address", type = {Address.class}, order=4, min=0, max=1, modifier=false, summary=false) @Description(shortDefinition="Address for the contact person", formalDefinition="Address for the contact person." ) protected Address address; /** * Administrative Gender - the gender that the contact person is considered to have for administration and record keeping purposes. */ @Child(name = "gender", type = {CodeType.class}, order=5, min=0, max=1, modifier=false, summary=false) @Description(shortDefinition="male | female | other | unknown", formalDefinition="Administrative Gender - the gender that the contact person is considered to have for administration and record keeping purposes." ) @ca.uhn.fhir.model.api.annotation.Binding(valueSet="http://hl7.org/fhir/ValueSet/administrative-gender") protected Enumeration<AdministrativeGender> gender; /** * Organization on behalf of which the contact is acting or for which the contact is working. */ @Child(name = "organization", type = {Organization.class}, order=6, min=0, max=1, modifier=false, summary=false) @Description(shortDefinition="Organization that is associated with the contact", formalDefinition="Organization on behalf of which the contact is acting or for which the contact is working." ) protected Reference organization; /** * The actual object that is the target of the reference (Organization on behalf of which the contact is acting or for which the contact is working.) */ protected Organization organizationTarget; /** * The period during which this contact person or organization is valid to be contacted relating to this patient. */ @Child(name = "period", type = {Period.class}, order=7, min=0, max=1, modifier=false, summary=false) @Description(shortDefinition="The period during which this contact person or organization is valid to be contacted relating to this patient", formalDefinition="The period during which this contact person or organization is valid to be contacted relating to this patient." ) protected Period period; private static final long serialVersionUID = 364269017L; /** * Constructor */ public ContactComponent() { super(); } /** * @return {@link #relationship} (The nature of the relationship between the patient and the contact person.) */ public List<CodeableConcept> getRelationship() { if (this.relationship == null) this.relationship = new ArrayList<CodeableConcept>(); return this.relationship; } /** * @return Returns a reference to <code>this</code> for easy method chaining */ public ContactComponent setRelationship(List<CodeableConcept> theRelationship) { this.relationship = theRelationship; return this; } public boolean hasRelationship() { if (this.relationship == null) return false; for (CodeableConcept item : this.relationship) if (!item.isEmpty()) return true; return false; } public CodeableConcept addRelationship() { //3 CodeableConcept t = new CodeableConcept(); if (this.relationship == null) this.relationship = new ArrayList<CodeableConcept>(); this.relationship.add(t); return t; } public ContactComponent addRelationship(CodeableConcept t) { //3 if (t == null) return this; if (this.relationship == null) this.relationship = new ArrayList<CodeableConcept>(); this.relationship.add(t); return this; } /** * @return The first repetition of repeating field {@link #relationship}, creating it if it does not already exist */ public CodeableConcept getRelationshipFirstRep() { if (getRelationship().isEmpty()) { addRelationship(); } return getRelationship().get(0); } /** * @return {@link #name} (A name associated with the contact person.) */ public HumanName getName() { if (this.name == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create ContactComponent.name"); else if (Configuration.doAutoCreate()) this.name = new HumanName(); // cc return this.name; } public boolean hasName() { return this.name != null && !this.name.isEmpty(); } /** * @param value {@link #name} (A name associated with the contact person.) */ public ContactComponent setName(HumanName value) { this.name = value; return this; } /** * @return {@link #telecom} (A contact detail for the person, e.g. a telephone number or an email address.) */ public List<ContactPoint> getTelecom() { if (this.telecom == null) this.telecom = new ArrayList<ContactPoint>(); return this.telecom; } /** * @return Returns a reference to <code>this</code> for easy method chaining */ public ContactComponent setTelecom(List<ContactPoint> theTelecom) { this.telecom = theTelecom; return this; } public boolean hasTelecom() { if (this.telecom == null) return false; for (ContactPoint item : this.telecom) if (!item.isEmpty()) return true; return false; } public ContactPoint addTelecom() { //3 ContactPoint t = new ContactPoint(); if (this.telecom == null) this.telecom = new ArrayList<ContactPoint>(); this.telecom.add(t); return t; } public ContactComponent addTelecom(ContactPoint t) { //3 if (t == null) return this; if (this.telecom == null) this.telecom = new ArrayList<ContactPoint>(); this.telecom.add(t); return this; } /** * @return The first repetition of repeating field {@link #telecom}, creating it if it does not already exist */ public ContactPoint getTelecomFirstRep() { if (getTelecom().isEmpty()) { addTelecom(); } return getTelecom().get(0); } /** * @return {@link #address} (Address for the contact person.) */ public Address getAddress() { if (this.address == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create ContactComponent.address"); else if (Configuration.doAutoCreate()) this.address = new Address(); // cc return this.address; } public boolean hasAddress() { return this.address != null && !this.address.isEmpty(); } /** * @param value {@link #address} (Address for the contact person.) */ public ContactComponent setAddress(Address value) { this.address = value; return this; } /** * @return {@link #gender} (Administrative Gender - the gender that the contact person is considered to have for administration and record keeping purposes.). This is the underlying object with id, value and extensions. The accessor "getGender" gives direct access to the value */ public Enumeration<AdministrativeGender> getGenderElement() { if (this.gender == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create ContactComponent.gender"); else if (Configuration.doAutoCreate()) this.gender = new Enumeration<AdministrativeGender>(new AdministrativeGenderEnumFactory()); // bb return this.gender; } public boolean hasGenderElement() { return this.gender != null && !this.gender.isEmpty(); } public boolean hasGender() { return this.gender != null && !this.gender.isEmpty(); } /** * @param value {@link #gender} (Administrative Gender - the gender that the contact person is considered to have for administration and record keeping purposes.). This is the underlying object with id, value and extensions. The accessor "getGender" gives direct access to the value */ public ContactComponent setGenderElement(Enumeration<AdministrativeGender> value) { this.gender = value; return this; } /** * @return Administrative Gender - the gender that the contact person is considered to have for administration and record keeping purposes. */ public AdministrativeGender getGender() { return this.gender == null ? null : this.gender.getValue(); } /** * @param value Administrative Gender - the gender that the contact person is considered to have for administration and record keeping purposes. */ public ContactComponent setGender(AdministrativeGender value) { if (value == null) this.gender = null; else { if (this.gender == null) this.gender = new Enumeration<AdministrativeGender>(new AdministrativeGenderEnumFactory()); this.gender.setValue(value); } return this; } /** * @return {@link #organization} (Organization on behalf of which the contact is acting or for which the contact is working.) */ public Reference getOrganization() { if (this.organization == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create ContactComponent.organization"); else if (Configuration.doAutoCreate()) this.organization = new Reference(); // cc return this.organization; } public boolean hasOrganization() { return this.organization != null && !this.organization.isEmpty(); } /** * @param value {@link #organization} (Organization on behalf of which the contact is acting or for which the contact is working.) */ public ContactComponent setOrganization(Reference value) { this.organization = value; return this; } /** * @return {@link #organization} The actual object that is the target of the reference. The reference library doesn't populate this, but you can use it to hold the resource if you resolve it. (Organization on behalf of which the contact is acting or for which the contact is working.) */ public Organization getOrganizationTarget() { if (this.organizationTarget == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create ContactComponent.organization"); else if (Configuration.doAutoCreate()) this.organizationTarget = new Organization(); // aa return this.organizationTarget; } /** * @param value {@link #organization} The actual object that is the target of the reference. The reference library doesn't use these, but you can use it to hold the resource if you resolve it. (Organization on behalf of which the contact is acting or for which the contact is working.) */ public ContactComponent setOrganizationTarget(Organization value) { this.organizationTarget = value; return this; } /** * @return {@link #period} (The period during which this contact person or organization is valid to be contacted relating to this patient.) */ public Period getPeriod() { if (this.period == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create ContactComponent.period"); else if (Configuration.doAutoCreate()) this.period = new Period(); // cc return this.period; } public boolean hasPeriod() { return this.period != null && !this.period.isEmpty(); } /** * @param value {@link #period} (The period during which this contact person or organization is valid to be contacted relating to this patient.) */ public ContactComponent setPeriod(Period value) { this.period = value; return this; } protected void listChildren(List<Property> childrenList) { super.listChildren(childrenList); childrenList.add(new Property("relationship", "CodeableConcept", "The nature of the relationship between the patient and the contact person.", 0, java.lang.Integer.MAX_VALUE, relationship)); childrenList.add(new Property("name", "HumanName", "A name associated with the contact person.", 0, java.lang.Integer.MAX_VALUE, name)); childrenList.add(new Property("telecom", "ContactPoint", "A contact detail for the person, e.g. a telephone number or an email address.", 0, java.lang.Integer.MAX_VALUE, telecom)); childrenList.add(new Property("address", "Address", "Address for the contact person.", 0, java.lang.Integer.MAX_VALUE, address)); childrenList.add(new Property("gender", "code", "Administrative Gender - the gender that the contact person is considered to have for administration and record keeping purposes.", 0, java.lang.Integer.MAX_VALUE, gender)); childrenList.add(new Property("organization", "Reference(Organization)", "Organization on behalf of which the contact is acting or for which the contact is working.", 0, java.lang.Integer.MAX_VALUE, organization)); childrenList.add(new Property("period", "Period", "The period during which this contact person or organization is valid to be contacted relating to this patient.", 0, java.lang.Integer.MAX_VALUE, period)); } @Override public Base[] getProperty(int hash, String name, boolean checkValid) throws FHIRException { switch (hash) { case -261851592: /*relationship*/ return this.relationship == null ? new Base[0] : this.relationship.toArray(new Base[this.relationship.size()]); // CodeableConcept case 3373707: /*name*/ return this.name == null ? new Base[0] : new Base[] {this.name}; // HumanName case -1429363305: /*telecom*/ return this.telecom == null ? new Base[0] : this.telecom.toArray(new Base[this.telecom.size()]); // ContactPoint case -1147692044: /*address*/ return this.address == null ? new Base[0] : new Base[] {this.address}; // Address case -1249512767: /*gender*/ return this.gender == null ? new Base[0] : new Base[] {this.gender}; // Enumeration<AdministrativeGender> case 1178922291: /*organization*/ return this.organization == null ? new Base[0] : new Base[] {this.organization}; // Reference case -991726143: /*period*/ return this.period == null ? new Base[0] : new Base[] {this.period}; // Period default: return super.getProperty(hash, name, checkValid); } } @Override public void setProperty(int hash, String name, Base value) throws FHIRException { switch (hash) { case -261851592: // relationship this.getRelationship().add(castToCodeableConcept(value)); // CodeableConcept break; case 3373707: // name this.name = castToHumanName(value); // HumanName break; case -1429363305: // telecom this.getTelecom().add(castToContactPoint(value)); // ContactPoint break; case -1147692044: // address this.address = castToAddress(value); // Address break; case -1249512767: // gender this.gender = new AdministrativeGenderEnumFactory().fromType(value); // Enumeration<AdministrativeGender> break; case 1178922291: // organization this.organization = castToReference(value); // Reference break; case -991726143: // period this.period = castToPeriod(value); // Period break; default: super.setProperty(hash, name, value); } } @Override public void setProperty(String name, Base value) throws FHIRException { if (name.equals("relationship")) this.getRelationship().add(castToCodeableConcept(value)); else if (name.equals("name")) this.name = castToHumanName(value); // HumanName else if (name.equals("telecom")) this.getTelecom().add(castToContactPoint(value)); else if (name.equals("address")) this.address = castToAddress(value); // Address else if (name.equals("gender")) this.gender = new AdministrativeGenderEnumFactory().fromType(value); // Enumeration<AdministrativeGender> else if (name.equals("organization")) this.organization = castToReference(value); // Reference else if (name.equals("period")) this.period = castToPeriod(value); // Period else super.setProperty(name, value); } @Override public Base makeProperty(int hash, String name) throws FHIRException { switch (hash) { case -261851592: return addRelationship(); // CodeableConcept case 3373707: return getName(); // HumanName case -1429363305: return addTelecom(); // ContactPoint case -1147692044: return getAddress(); // Address case -1249512767: throw new FHIRException("Cannot make property gender as it is not a complex type"); // Enumeration<AdministrativeGender> case 1178922291: return getOrganization(); // Reference case -991726143: return getPeriod(); // Period default: return super.makeProperty(hash, name); } } @Override public Base addChild(String name) throws FHIRException { if (name.equals("relationship")) { return addRelationship(); } else if (name.equals("name")) { this.name = new HumanName(); return this.name; } else if (name.equals("telecom")) { return addTelecom(); } else if (name.equals("address")) { this.address = new Address(); return this.address; } else if (name.equals("gender")) { throw new FHIRException("Cannot call addChild on a primitive type Patient.gender"); } else if (name.equals("organization")) { this.organization = new Reference(); return this.organization; } else if (name.equals("period")) { this.period = new Period(); return this.period; } else return super.addChild(name); } public ContactComponent copy() { ContactComponent dst = new ContactComponent(); copyValues(dst); if (relationship != null) { dst.relationship = new ArrayList<CodeableConcept>(); for (CodeableConcept i : relationship) dst.relationship.add(i.copy()); }; dst.name = name == null ? null : name.copy(); if (telecom != null) { dst.telecom = new ArrayList<ContactPoint>(); for (ContactPoint i : telecom) dst.telecom.add(i.copy()); }; dst.address = address == null ? null : address.copy(); dst.gender = gender == null ? null : gender.copy(); dst.organization = organization == null ? null : organization.copy(); dst.period = period == null ? null : period.copy(); return dst; } @Override public boolean equalsDeep(Base other) { if (!super.equalsDeep(other)) return false; if (!(other instanceof ContactComponent)) return false; ContactComponent o = (ContactComponent) other; return compareDeep(relationship, o.relationship, true) && compareDeep(name, o.name, true) && compareDeep(telecom, o.telecom, true) && compareDeep(address, o.address, true) && compareDeep(gender, o.gender, true) && compareDeep(organization, o.organization, true) && compareDeep(period, o.period, true); } @Override public boolean equalsShallow(Base other) { if (!super.equalsShallow(other)) return false; if (!(other instanceof ContactComponent)) return false; ContactComponent o = (ContactComponent) other; return compareValues(gender, o.gender, true); } public boolean isEmpty() { return super.isEmpty() && ca.uhn.fhir.util.ElementUtil.isEmpty(relationship, name, telecom , address, gender, organization, period); } public String fhirType() { return "Patient.contact"; } } @Block() public static class AnimalComponent extends BackboneElement implements IBaseBackboneElement { /** * Identifies the high level taxonomic categorization of the kind of animal. */ @Child(name = "species", type = {CodeableConcept.class}, order=1, min=1, max=1, modifier=false, summary=true) @Description(shortDefinition="E.g. Dog, Cow", formalDefinition="Identifies the high level taxonomic categorization of the kind of animal." ) @ca.uhn.fhir.model.api.annotation.Binding(valueSet="http://hl7.org/fhir/ValueSet/animal-species") protected CodeableConcept species; /** * Identifies the detailed categorization of the kind of animal. */ @Child(name = "breed", type = {CodeableConcept.class}, order=2, min=0, max=1, modifier=false, summary=true) @Description(shortDefinition="E.g. Poodle, Angus", formalDefinition="Identifies the detailed categorization of the kind of animal." ) @ca.uhn.fhir.model.api.annotation.Binding(valueSet="http://hl7.org/fhir/ValueSet/animal-breeds") protected CodeableConcept breed; /** * Indicates the current state of the animal's reproductive organs. */ @Child(name = "genderStatus", type = {CodeableConcept.class}, order=3, min=0, max=1, modifier=false, summary=true) @Description(shortDefinition="E.g. Neutered, Intact", formalDefinition="Indicates the current state of the animal's reproductive organs." ) @ca.uhn.fhir.model.api.annotation.Binding(valueSet="http://hl7.org/fhir/ValueSet/animal-genderstatus") protected CodeableConcept genderStatus; private static final long serialVersionUID = -549738382L; /** * Constructor */ public AnimalComponent() { super(); } /** * Constructor */ public AnimalComponent(CodeableConcept species) { super(); this.species = species; } /** * @return {@link #species} (Identifies the high level taxonomic categorization of the kind of animal.) */ public CodeableConcept getSpecies() { if (this.species == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create AnimalComponent.species"); else if (Configuration.doAutoCreate()) this.species = new CodeableConcept(); // cc return this.species; } public boolean hasSpecies() { return this.species != null && !this.species.isEmpty(); } /** * @param value {@link #species} (Identifies the high level taxonomic categorization of the kind of animal.) */ public AnimalComponent setSpecies(CodeableConcept value) { this.species = value; return this; } /** * @return {@link #breed} (Identifies the detailed categorization of the kind of animal.) */ public CodeableConcept getBreed() { if (this.breed == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create AnimalComponent.breed"); else if (Configuration.doAutoCreate()) this.breed = new CodeableConcept(); // cc return this.breed; } public boolean hasBreed() { return this.breed != null && !this.breed.isEmpty(); } /** * @param value {@link #breed} (Identifies the detailed categorization of the kind of animal.) */ public AnimalComponent setBreed(CodeableConcept value) { this.breed = value; return this; } /** * @return {@link #genderStatus} (Indicates the current state of the animal's reproductive organs.) */ public CodeableConcept getGenderStatus() { if (this.genderStatus == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create AnimalComponent.genderStatus"); else if (Configuration.doAutoCreate()) this.genderStatus = new CodeableConcept(); // cc return this.genderStatus; } public boolean hasGenderStatus() { return this.genderStatus != null && !this.genderStatus.isEmpty(); } /** * @param value {@link #genderStatus} (Indicates the current state of the animal's reproductive organs.) */ public AnimalComponent setGenderStatus(CodeableConcept value) { this.genderStatus = value; return this; } protected void listChildren(List<Property> childrenList) { super.listChildren(childrenList); childrenList.add(new Property("species", "CodeableConcept", "Identifies the high level taxonomic categorization of the kind of animal.", 0, java.lang.Integer.MAX_VALUE, species)); childrenList.add(new Property("breed", "CodeableConcept", "Identifies the detailed categorization of the kind of animal.", 0, java.lang.Integer.MAX_VALUE, breed)); childrenList.add(new Property("genderStatus", "CodeableConcept", "Indicates the current state of the animal's reproductive organs.", 0, java.lang.Integer.MAX_VALUE, genderStatus)); } @Override public Base[] getProperty(int hash, String name, boolean checkValid) throws FHIRException { switch (hash) { case -2008465092: /*species*/ return this.species == null ? new Base[0] : new Base[] {this.species}; // CodeableConcept case 94001524: /*breed*/ return this.breed == null ? new Base[0] : new Base[] {this.breed}; // CodeableConcept case -678569453: /*genderStatus*/ return this.genderStatus == null ? new Base[0] : new Base[] {this.genderStatus}; // CodeableConcept default: return super.getProperty(hash, name, checkValid); } } @Override public void setProperty(int hash, String name, Base value) throws FHIRException { switch (hash) { case -2008465092: // species this.species = castToCodeableConcept(value); // CodeableConcept break; case 94001524: // breed this.breed = castToCodeableConcept(value); // CodeableConcept break; case -678569453: // genderStatus this.genderStatus = castToCodeableConcept(value); // CodeableConcept break; default: super.setProperty(hash, name, value); } } @Override public void setProperty(String name, Base value) throws FHIRException { if (name.equals("species")) this.species = castToCodeableConcept(value); // CodeableConcept else if (name.equals("breed")) this.breed = castToCodeableConcept(value); // CodeableConcept else if (name.equals("genderStatus")) this.genderStatus = castToCodeableConcept(value); // CodeableConcept else super.setProperty(name, value); } @Override public Base makeProperty(int hash, String name) throws FHIRException { switch (hash) { case -2008465092: return getSpecies(); // CodeableConcept case 94001524: return getBreed(); // CodeableConcept case -678569453: return getGenderStatus(); // CodeableConcept default: return super.makeProperty(hash, name); } } @Override public Base addChild(String name) throws FHIRException { if (name.equals("species")) { this.species = new CodeableConcept(); return this.species; } else if (name.equals("breed")) { this.breed = new CodeableConcept(); return this.breed; } else if (name.equals("genderStatus")) { this.genderStatus = new CodeableConcept(); return this.genderStatus; } else return super.addChild(name); } public AnimalComponent copy() { AnimalComponent dst = new AnimalComponent(); copyValues(dst); dst.species = species == null ? null : species.copy(); dst.breed = breed == null ? null : breed.copy(); dst.genderStatus = genderStatus == null ? null : genderStatus.copy(); return dst; } @Override public boolean equalsDeep(Base other) { if (!super.equalsDeep(other)) return false; if (!(other instanceof AnimalComponent)) return false; AnimalComponent o = (AnimalComponent) other; return compareDeep(species, o.species, true) && compareDeep(breed, o.breed, true) && compareDeep(genderStatus, o.genderStatus, true) ; } @Override public boolean equalsShallow(Base other) { if (!super.equalsShallow(other)) return false; if (!(other instanceof AnimalComponent)) return false; AnimalComponent o = (AnimalComponent) other; return true; } public boolean isEmpty() { return super.isEmpty() && ca.uhn.fhir.util.ElementUtil.isEmpty(species, breed, genderStatus ); } public String fhirType() { return "Patient.animal"; } } @Block() public static class PatientCommunicationComponent extends BackboneElement implements IBaseBackboneElement { /** * The ISO-639-1 alpha 2 code in lower case for the language, optionally followed by a hyphen and the ISO-3166-1 alpha 2 code for the region in upper case; e.g. "en" for English, or "en-US" for American English versus "en-EN" for England English. */ @Child(name = "language", type = {CodeableConcept.class}, order=1, min=1, max=1, modifier=false, summary=false) @Description(shortDefinition="The language which can be used to communicate with the patient about his or her health", formalDefinition="The ISO-639-1 alpha 2 code in lower case for the language, optionally followed by a hyphen and the ISO-3166-1 alpha 2 code for the region in upper case; e.g. \"en\" for English, or \"en-US\" for American English versus \"en-EN\" for England English." ) @ca.uhn.fhir.model.api.annotation.Binding(valueSet="http://hl7.org/fhir/ValueSet/languages") protected CodeableConcept language; /** * Indicates whether or not the patient prefers this language (over other languages he masters up a certain level). */ @Child(name = "preferred", type = {BooleanType.class}, order=2, min=0, max=1, modifier=false, summary=false) @Description(shortDefinition="Language preference indicator", formalDefinition="Indicates whether or not the patient prefers this language (over other languages he masters up a certain level)." ) protected BooleanType preferred; private static final long serialVersionUID = 633792918L; /** * Constructor */ public PatientCommunicationComponent() { super(); } /** * Constructor */ public PatientCommunicationComponent(CodeableConcept language) { super(); this.language = language; } /** * @return {@link #language} (The ISO-639-1 alpha 2 code in lower case for the language, optionally followed by a hyphen and the ISO-3166-1 alpha 2 code for the region in upper case; e.g. "en" for English, or "en-US" for American English versus "en-EN" for England English.) */ public CodeableConcept getLanguage() { if (this.language == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create PatientCommunicationComponent.language"); else if (Configuration.doAutoCreate()) this.language = new CodeableConcept(); // cc return this.language; } public boolean hasLanguage() { return this.language != null && !this.language.isEmpty(); } /** * @param value {@link #language} (The ISO-639-1 alpha 2 code in lower case for the language, optionally followed by a hyphen and the ISO-3166-1 alpha 2 code for the region in upper case; e.g. "en" for English, or "en-US" for American English versus "en-EN" for England English.) */ public PatientCommunicationComponent setLanguage(CodeableConcept value) { this.language = value; return this; } /** * @return {@link #preferred} (Indicates whether or not the patient prefers this language (over other languages he masters up a certain level).). This is the underlying object with id, value and extensions. The accessor "getPreferred" gives direct access to the value */ public BooleanType getPreferredElement() { if (this.preferred == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create PatientCommunicationComponent.preferred"); else if (Configuration.doAutoCreate()) this.preferred = new BooleanType(); // bb return this.preferred; } public boolean hasPreferredElement() { return this.preferred != null && !this.preferred.isEmpty(); } public boolean hasPreferred() { return this.preferred != null && !this.preferred.isEmpty(); } /** * @param value {@link #preferred} (Indicates whether or not the patient prefers this language (over other languages he masters up a certain level).). This is the underlying object with id, value and extensions. The accessor "getPreferred" gives direct access to the value */ public PatientCommunicationComponent setPreferredElement(BooleanType value) { this.preferred = value; return this; } /** * @return Indicates whether or not the patient prefers this language (over other languages he masters up a certain level). */ public boolean getPreferred() { return this.preferred == null || this.preferred.isEmpty() ? false : this.preferred.getValue(); } /** * @param value Indicates whether or not the patient prefers this language (over other languages he masters up a certain level). */ public PatientCommunicationComponent setPreferred(boolean value) { if (this.preferred == null) this.preferred = new BooleanType(); this.preferred.setValue(value); return this; } protected void listChildren(List<Property> childrenList) { super.listChildren(childrenList); childrenList.add(new Property("language", "CodeableConcept", "The ISO-639-1 alpha 2 code in lower case for the language, optionally followed by a hyphen and the ISO-3166-1 alpha 2 code for the region in upper case; e.g. \"en\" for English, or \"en-US\" for American English versus \"en-EN\" for England English.", 0, java.lang.Integer.MAX_VALUE, language)); childrenList.add(new Property("preferred", "boolean", "Indicates whether or not the patient prefers this language (over other languages he masters up a certain level).", 0, java.lang.Integer.MAX_VALUE, preferred)); } @Override public Base[] getProperty(int hash, String name, boolean checkValid) throws FHIRException { switch (hash) { case -1613589672: /*language*/ return this.language == null ? new Base[0] : new Base[] {this.language}; // CodeableConcept case -1294005119: /*preferred*/ return this.preferred == null ? new Base[0] : new Base[] {this.preferred}; // BooleanType default: return super.getProperty(hash, name, checkValid); } } @Override public void setProperty(int hash, String name, Base value) throws FHIRException { switch (hash) { case -1613589672: // language this.language = castToCodeableConcept(value); // CodeableConcept break; case -1294005119: // preferred this.preferred = castToBoolean(value); // BooleanType break; default: super.setProperty(hash, name, value); } } @Override public void setProperty(String name, Base value) throws FHIRException { if (name.equals("language")) this.language = castToCodeableConcept(value); // CodeableConcept else if (name.equals("preferred")) this.preferred = castToBoolean(value); // BooleanType else super.setProperty(name, value); } @Override public Base makeProperty(int hash, String name) throws FHIRException { switch (hash) { case -1613589672: return getLanguage(); // CodeableConcept case -1294005119: throw new FHIRException("Cannot make property preferred as it is not a complex type"); // BooleanType default: return super.makeProperty(hash, name); } } @Override public Base addChild(String name) throws FHIRException { if (name.equals("language")) { this.language = new CodeableConcept(); return this.language; } else if (name.equals("preferred")) { throw new FHIRException("Cannot call addChild on a primitive type Patient.preferred"); } else return super.addChild(name); } public PatientCommunicationComponent copy() { PatientCommunicationComponent dst = new PatientCommunicationComponent(); copyValues(dst); dst.language = language == null ? null : language.copy(); dst.preferred = preferred == null ? null : preferred.copy(); return dst; } @Override public boolean equalsDeep(Base other) { if (!super.equalsDeep(other)) return false; if (!(other instanceof PatientCommunicationComponent)) return false; PatientCommunicationComponent o = (PatientCommunicationComponent) other; return compareDeep(language, o.language, true) && compareDeep(preferred, o.preferred, true); } @Override public boolean equalsShallow(Base other) { if (!super.equalsShallow(other)) return false; if (!(other instanceof PatientCommunicationComponent)) return false; PatientCommunicationComponent o = (PatientCommunicationComponent) other; return compareValues(preferred, o.preferred, true); } public boolean isEmpty() { return super.isEmpty() && ca.uhn.fhir.util.ElementUtil.isEmpty(language, preferred); } public String fhirType() { return "Patient.communication"; } } @Block() public static class PatientLinkComponent extends BackboneElement implements IBaseBackboneElement { /** * The other patient resource that the link refers to. */ @Child(name = "other", type = {Patient.class, RelatedPerson.class}, order=1, min=1, max=1, modifier=true, summary=true) @Description(shortDefinition="The other patient or related person resource that the link refers to", formalDefinition="The other patient resource that the link refers to." ) protected Reference other; /** * The actual object that is the target of the reference (The other patient resource that the link refers to.) */ protected Resource otherTarget; /** * The type of link between this patient resource and another patient resource. */ @Child(name = "type", type = {CodeType.class}, order=2, min=1, max=1, modifier=true, summary=true) @Description(shortDefinition="replace | refer | seealso - type of link", formalDefinition="The type of link between this patient resource and another patient resource." ) @ca.uhn.fhir.model.api.annotation.Binding(valueSet="http://hl7.org/fhir/ValueSet/link-type") protected Enumeration<LinkType> type; private static final long serialVersionUID = 1083576633L; /** * Constructor */ public PatientLinkComponent() { super(); } /** * Constructor */ public PatientLinkComponent(Reference other, Enumeration<LinkType> type) { super(); this.other = other; this.type = type; } /** * @return {@link #other} (The other patient resource that the link refers to.) */ public Reference getOther() { if (this.other == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create PatientLinkComponent.other"); else if (Configuration.doAutoCreate()) this.other = new Reference(); // cc return this.other; } public boolean hasOther() { return this.other != null && !this.other.isEmpty(); } /** * @param value {@link #other} (The other patient resource that the link refers to.) */ public PatientLinkComponent setOther(Reference value) { this.other = value; return this; } /** * @return {@link #other} The actual object that is the target of the reference. The reference library doesn't populate this, but you can use it to hold the resource if you resolve it. (The other patient resource that the link refers to.) */ public Resource getOtherTarget() { return this.otherTarget; } /** * @param value {@link #other} The actual object that is the target of the reference. The reference library doesn't use these, but you can use it to hold the resource if you resolve it. (The other patient resource that the link refers to.) */ public PatientLinkComponent setOtherTarget(Resource value) { this.otherTarget = value; return this; } /** * @return {@link #type} (The type of link between this patient resource and another patient resource.). This is the underlying object with id, value and extensions. The accessor "getType" gives direct access to the value */ public Enumeration<LinkType> getTypeElement() { if (this.type == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create PatientLinkComponent.type"); else if (Configuration.doAutoCreate()) this.type = new Enumeration<LinkType>(new LinkTypeEnumFactory()); // bb return this.type; } public boolean hasTypeElement() { return this.type != null && !this.type.isEmpty(); } public boolean hasType() { return this.type != null && !this.type.isEmpty(); } /** * @param value {@link #type} (The type of link between this patient resource and another patient resource.). This is the underlying object with id, value and extensions. The accessor "getType" gives direct access to the value */ public PatientLinkComponent setTypeElement(Enumeration<LinkType> value) { this.type = value; return this; } /** * @return The type of link between this patient resource and another patient resource. */ public LinkType getType() { return this.type == null ? null : this.type.getValue(); } /** * @param value The type of link between this patient resource and another patient resource. */ public PatientLinkComponent setType(LinkType value) { if (this.type == null) this.type = new Enumeration<LinkType>(new LinkTypeEnumFactory()); this.type.setValue(value); return this; } protected void listChildren(List<Property> childrenList) { super.listChildren(childrenList); childrenList.add(new Property("other", "Reference(Patient|RelatedPerson)", "The other patient resource that the link refers to.", 0, java.lang.Integer.MAX_VALUE, other)); childrenList.add(new Property("type", "code", "The type of link between this patient resource and another patient resource.", 0, java.lang.Integer.MAX_VALUE, type)); } @Override public Base[] getProperty(int hash, String name, boolean checkValid) throws FHIRException { switch (hash) { case 106069776: /*other*/ return this.other == null ? new Base[0] : new Base[] {this.other}; // Reference case 3575610: /*type*/ return this.type == null ? new Base[0] : new Base[] {this.type}; // Enumeration<LinkType> default: return super.getProperty(hash, name, checkValid); } } @Override public void setProperty(int hash, String name, Base value) throws FHIRException { switch (hash) { case 106069776: // other this.other = castToReference(value); // Reference break; case 3575610: // type this.type = new LinkTypeEnumFactory().fromType(value); // Enumeration<LinkType> break; default: super.setProperty(hash, name, value); } } @Override public void setProperty(String name, Base value) throws FHIRException { if (name.equals("other")) this.other = castToReference(value); // Reference else if (name.equals("type")) this.type = new LinkTypeEnumFactory().fromType(value); // Enumeration<LinkType> else super.setProperty(name, value); } @Override public Base makeProperty(int hash, String name) throws FHIRException { switch (hash) { case 106069776: return getOther(); // Reference case 3575610: throw new FHIRException("Cannot make property type as it is not a complex type"); // Enumeration<LinkType> default: return super.makeProperty(hash, name); } } @Override public Base addChild(String name) throws FHIRException { if (name.equals("other")) { this.other = new Reference(); return this.other; } else if (name.equals("type")) { throw new FHIRException("Cannot call addChild on a primitive type Patient.type"); } else return super.addChild(name); } public PatientLinkComponent copy() { PatientLinkComponent dst = new PatientLinkComponent(); copyValues(dst); dst.other = other == null ? null : other.copy(); dst.type = type == null ? null : type.copy(); return dst; } @Override public boolean equalsDeep(Base other) { if (!super.equalsDeep(other)) return false; if (!(other instanceof PatientLinkComponent)) return false; PatientLinkComponent o = (PatientLinkComponent) other; return compareDeep(other, o.other, true) && compareDeep(type, o.type, true); } @Override public boolean equalsShallow(Base other) { if (!super.equalsShallow(other)) return false; if (!(other instanceof PatientLinkComponent)) return false; PatientLinkComponent o = (PatientLinkComponent) other; return compareValues(type, o.type, true); } public boolean isEmpty() { return super.isEmpty() && ca.uhn.fhir.util.ElementUtil.isEmpty(other, type); } public String fhirType() { return "Patient.link"; } } /** * An identifier for this patient. */ @Child(name = "identifier", type = {Identifier.class}, order=0, min=0, max=Child.MAX_UNLIMITED, modifier=false, summary=true) @Description(shortDefinition="An identifier for this patient", formalDefinition="An identifier for this patient." ) protected List<Identifier> identifier; /** * Whether this patient record is in active use. */ @Child(name = "active", type = {BooleanType.class}, order=1, min=0, max=1, modifier=true, summary=true) @Description(shortDefinition="Whether this patient's record is in active use", formalDefinition="Whether this patient record is in active use." ) protected BooleanType active; /** * A name associated with the individual. */ @Child(name = "name", type = {HumanName.class}, order=2, min=0, max=Child.MAX_UNLIMITED, modifier=false, summary=true) @Description(shortDefinition="A name associated with the patient", formalDefinition="A name associated with the individual." ) protected List<HumanName> name; /** * A contact detail (e.g. a telephone number or an email address) by which the individual may be contacted. */ @Child(name = "telecom", type = {ContactPoint.class}, order=3, min=0, max=Child.MAX_UNLIMITED, modifier=false, summary=true) @Description(shortDefinition="A contact detail for the individual", formalDefinition="A contact detail (e.g. a telephone number or an email address) by which the individual may be contacted." ) protected List<ContactPoint> telecom; /** * Administrative Gender - the gender that the patient is considered to have for administration and record keeping purposes. */ @Child(name = "gender", type = {CodeType.class}, order=4, min=0, max=1, modifier=false, summary=true) @Description(shortDefinition="male | female | other | unknown", formalDefinition="Administrative Gender - the gender that the patient is considered to have for administration and record keeping purposes." ) @ca.uhn.fhir.model.api.annotation.Binding(valueSet="http://hl7.org/fhir/ValueSet/administrative-gender") protected Enumeration<AdministrativeGender> gender; /** * The date of birth for the individual. */ @Child(name = "birthDate", type = {DateType.class}, order=5, min=0, max=1, modifier=false, summary=true) @Description(shortDefinition="The date of birth for the individual", formalDefinition="The date of birth for the individual." ) protected DateType birthDate; /** * Indicates if the individual is deceased or not. */ @Child(name = "deceased", type = {BooleanType.class, DateTimeType.class}, order=6, min=0, max=1, modifier=true, summary=true) @Description(shortDefinition="Indicates if the individual is deceased or not", formalDefinition="Indicates if the individual is deceased or not." ) protected Type deceased; /** * Addresses for the individual. */ @Child(name = "address", type = {Address.class}, order=7, min=0, max=Child.MAX_UNLIMITED, modifier=false, summary=true) @Description(shortDefinition="Addresses for the individual", formalDefinition="Addresses for the individual." ) protected List<Address> address; /** * This field contains a patient's most recent marital (civil) status. */ @Child(name = "maritalStatus", type = {CodeableConcept.class}, order=8, min=0, max=1, modifier=false, summary=false) @Description(shortDefinition="Marital (civil) status of a patient", formalDefinition="This field contains a patient's most recent marital (civil) status." ) @ca.uhn.fhir.model.api.annotation.Binding(valueSet="http://hl7.org/fhir/ValueSet/marital-status") protected CodeableConcept maritalStatus; /** * Indicates whether the patient is part of a multiple (bool) or indicates the actual birth order (integer). */ @Child(name = "multipleBirth", type = {BooleanType.class, IntegerType.class}, order=9, min=0, max=1, modifier=false, summary=false) @Description(shortDefinition="Whether patient is part of a multiple birth", formalDefinition="Indicates whether the patient is part of a multiple (bool) or indicates the actual birth order (integer)." ) protected Type multipleBirth; /** * Image of the patient. */ @Child(name = "photo", type = {Attachment.class}, order=10, min=0, max=Child.MAX_UNLIMITED, modifier=false, summary=false) @Description(shortDefinition="Image of the patient", formalDefinition="Image of the patient." ) protected List<Attachment> photo; /** * A contact party (e.g. guardian, partner, friend) for the patient. */ @Child(name = "contact", type = {}, order=11, min=0, max=Child.MAX_UNLIMITED, modifier=false, summary=false) @Description(shortDefinition="A contact party (e.g. guardian, partner, friend) for the patient", formalDefinition="A contact party (e.g. guardian, partner, friend) for the patient." ) protected List<ContactComponent> contact; /** * This patient is known to be an animal. */ @Child(name = "animal", type = {}, order=12, min=0, max=1, modifier=true, summary=true) @Description(shortDefinition="This patient is known to be an animal (non-human)", formalDefinition="This patient is known to be an animal." ) protected AnimalComponent animal; /** * Languages which may be used to communicate with the patient about his or her health. */ @Child(name = "communication", type = {}, order=13, min=0, max=Child.MAX_UNLIMITED, modifier=false, summary=false) @Description(shortDefinition="A list of Languages which may be used to communicate with the patient about his or her health", formalDefinition="Languages which may be used to communicate with the patient about his or her health." ) protected List<PatientCommunicationComponent> communication; /** * Patient's nominated care provider. */ @Child(name = "generalPractitioner", type = {Organization.class, Practitioner.class}, order=14, min=0, max=Child.MAX_UNLIMITED, modifier=false, summary=false) @Description(shortDefinition="Patient's nominated primary care provider", formalDefinition="Patient's nominated care provider." ) protected List<Reference> generalPractitioner; /** * The actual objects that are the target of the reference (Patient's nominated care provider.) */ protected List<Resource> generalPractitionerTarget; /** * Organization that is the custodian of the patient record. */ @Child(name = "managingOrganization", type = {Organization.class}, order=15, min=0, max=1, modifier=false, summary=true) @Description(shortDefinition="Organization that is the custodian of the patient record", formalDefinition="Organization that is the custodian of the patient record." ) protected Reference managingOrganization; /** * The actual object that is the target of the reference (Organization that is the custodian of the patient record.) */ protected Organization managingOrganizationTarget; /** * Link to another patient resource that concerns the same actual patient. */ @Child(name = "link", type = {}, order=16, min=0, max=Child.MAX_UNLIMITED, modifier=true, summary=true) @Description(shortDefinition="Link to another patient resource that concerns the same actual person", formalDefinition="Link to another patient resource that concerns the same actual patient." ) protected List<PatientLinkComponent> link; private static final long serialVersionUID = -1985061666L; /** * Constructor */ public Patient() { super(); } /** * @return {@link #identifier} (An identifier for this patient.) */ public List<Identifier> getIdentifier() { if (this.identifier == null) this.identifier = new ArrayList<Identifier>(); return this.identifier; } /** * @return Returns a reference to <code>this</code> for easy method chaining */ public Patient setIdentifier(List<Identifier> theIdentifier) { this.identifier = theIdentifier; return this; } public boolean hasIdentifier() { if (this.identifier == null) return false; for (Identifier item : this.identifier) if (!item.isEmpty()) return true; return false; } public Identifier addIdentifier() { //3 Identifier t = new Identifier(); if (this.identifier == null) this.identifier = new ArrayList<Identifier>(); this.identifier.add(t); return t; } public Patient addIdentifier(Identifier t) { //3 if (t == null) return this; if (this.identifier == null) this.identifier = new ArrayList<Identifier>(); this.identifier.add(t); return this; } /** * @return The first repetition of repeating field {@link #identifier}, creating it if it does not already exist */ public Identifier getIdentifierFirstRep() { if (getIdentifier().isEmpty()) { addIdentifier(); } return getIdentifier().get(0); } /** * @return {@link #active} (Whether this patient record is in active use.). This is the underlying object with id, value and extensions. The accessor "getActive" gives direct access to the value */ public BooleanType getActiveElement() { if (this.active == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create Patient.active"); else if (Configuration.doAutoCreate()) this.active = new BooleanType(); // bb return this.active; } public boolean hasActiveElement() { return this.active != null && !this.active.isEmpty(); } public boolean hasActive() { return this.active != null && !this.active.isEmpty(); } /** * @param value {@link #active} (Whether this patient record is in active use.). This is the underlying object with id, value and extensions. The accessor "getActive" gives direct access to the value */ public Patient setActiveElement(BooleanType value) { this.active = value; return this; } /** * @return Whether this patient record is in active use. */ public boolean getActive() { return this.active == null || this.active.isEmpty() ? false : this.active.getValue(); } /** * @param value Whether this patient record is in active use. */ public Patient setActive(boolean value) { if (this.active == null) this.active = new BooleanType(); this.active.setValue(value); return this; } /** * @return {@link #name} (A name associated with the individual.) */ public List<HumanName> getName() { if (this.name == null) this.name = new ArrayList<HumanName>(); return this.name; } /** * @return Returns a reference to <code>this</code> for easy method chaining */ public Patient setName(List<HumanName> theName) { this.name = theName; return this; } public boolean hasName() { if (this.name == null) return false; for (HumanName item : this.name) if (!item.isEmpty()) return true; return false; } public HumanName addName() { //3 HumanName t = new HumanName(); if (this.name == null) this.name = new ArrayList<HumanName>(); this.name.add(t); return t; } public Patient addName(HumanName t) { //3 if (t == null) return this; if (this.name == null) this.name = new ArrayList<HumanName>(); this.name.add(t); return this; } /** * @return The first repetition of repeating field {@link #name}, creating it if it does not already exist */ public HumanName getNameFirstRep() { if (getName().isEmpty()) { addName(); } return getName().get(0); } /** * @return {@link #telecom} (A contact detail (e.g. a telephone number or an email address) by which the individual may be contacted.) */ public List<ContactPoint> getTelecom() { if (this.telecom == null) this.telecom = new ArrayList<ContactPoint>(); return this.telecom; } /** * @return Returns a reference to <code>this</code> for easy method chaining */ public Patient setTelecom(List<ContactPoint> theTelecom) { this.telecom = theTelecom; return this; } public boolean hasTelecom() { if (this.telecom == null) return false; for (ContactPoint item : this.telecom) if (!item.isEmpty()) return true; return false; } public ContactPoint addTelecom() { //3 ContactPoint t = new ContactPoint(); if (this.telecom == null) this.telecom = new ArrayList<ContactPoint>(); this.telecom.add(t); return t; } public Patient addTelecom(ContactPoint t) { //3 if (t == null) return this; if (this.telecom == null) this.telecom = new ArrayList<ContactPoint>(); this.telecom.add(t); return this; } /** * @return The first repetition of repeating field {@link #telecom}, creating it if it does not already exist */ public ContactPoint getTelecomFirstRep() { if (getTelecom().isEmpty()) { addTelecom(); } return getTelecom().get(0); } /** * @return {@link #gender} (Administrative Gender - the gender that the patient is considered to have for administration and record keeping purposes.). This is the underlying object with id, value and extensions. The accessor "getGender" gives direct access to the value */ public Enumeration<AdministrativeGender> getGenderElement() { if (this.gender == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create Patient.gender"); else if (Configuration.doAutoCreate()) this.gender = new Enumeration<AdministrativeGender>(new AdministrativeGenderEnumFactory()); // bb return this.gender; } public boolean hasGenderElement() { return this.gender != null && !this.gender.isEmpty(); } public boolean hasGender() { return this.gender != null && !this.gender.isEmpty(); } /** * @param value {@link #gender} (Administrative Gender - the gender that the patient is considered to have for administration and record keeping purposes.). This is the underlying object with id, value and extensions. The accessor "getGender" gives direct access to the value */ public Patient setGenderElement(Enumeration<AdministrativeGender> value) { this.gender = value; return this; } /** * @return Administrative Gender - the gender that the patient is considered to have for administration and record keeping purposes. */ public AdministrativeGender getGender() { return this.gender == null ? null : this.gender.getValue(); } /** * @param value Administrative Gender - the gender that the patient is considered to have for administration and record keeping purposes. */ public Patient setGender(AdministrativeGender value) { if (value == null) this.gender = null; else { if (this.gender == null) this.gender = new Enumeration<AdministrativeGender>(new AdministrativeGenderEnumFactory()); this.gender.setValue(value); } return this; } /** * @return {@link #birthDate} (The date of birth for the individual.). This is the underlying object with id, value and extensions. The accessor "getBirthDate" gives direct access to the value */ public DateType getBirthDateElement() { if (this.birthDate == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create Patient.birthDate"); else if (Configuration.doAutoCreate()) this.birthDate = new DateType(); // bb return this.birthDate; } public boolean hasBirthDateElement() { return this.birthDate != null && !this.birthDate.isEmpty(); } public boolean hasBirthDate() { return this.birthDate != null && !this.birthDate.isEmpty(); } /** * @param value {@link #birthDate} (The date of birth for the individual.). This is the underlying object with id, value and extensions. The accessor "getBirthDate" gives direct access to the value */ public Patient setBirthDateElement(DateType value) { this.birthDate = value; return this; } /** * @return The date of birth for the individual. */ public Date getBirthDate() { return this.birthDate == null ? null : this.birthDate.getValue(); } /** * @param value The date of birth for the individual. */ public Patient setBirthDate(Date value) { if (value == null) this.birthDate = null; else { if (this.birthDate == null) this.birthDate = new DateType(); this.birthDate.setValue(value); } return this; } /** * @return {@link #deceased} (Indicates if the individual is deceased or not.) */ public Type getDeceased() { return this.deceased; } /** * @return {@link #deceased} (Indicates if the individual is deceased or not.) */ public BooleanType getDeceasedBooleanType() throws FHIRException { if (!(this.deceased instanceof BooleanType)) throw new FHIRException("Type mismatch: the type BooleanType was expected, but "+this.deceased.getClass().getName()+" was encountered"); return (BooleanType) this.deceased; } public boolean hasDeceasedBooleanType() { return this.deceased instanceof BooleanType; } /** * @return {@link #deceased} (Indicates if the individual is deceased or not.) */ public DateTimeType getDeceasedDateTimeType() throws FHIRException { if (!(this.deceased instanceof DateTimeType)) throw new FHIRException("Type mismatch: the type DateTimeType was expected, but "+this.deceased.getClass().getName()+" was encountered"); return (DateTimeType) this.deceased; } public boolean hasDeceasedDateTimeType() { return this.deceased instanceof DateTimeType; } public boolean hasDeceased() { return this.deceased != null && !this.deceased.isEmpty(); } /** * @param value {@link #deceased} (Indicates if the individual is deceased or not.) */ public Patient setDeceased(Type value) { this.deceased = value; return this; } /** * @return {@link #address} (Addresses for the individual.) */ public List<Address> getAddress() { if (this.address == null) this.address = new ArrayList<Address>(); return this.address; } /** * @return Returns a reference to <code>this</code> for easy method chaining */ public Patient setAddress(List<Address> theAddress) { this.address = theAddress; return this; } public boolean hasAddress() { if (this.address == null) return false; for (Address item : this.address) if (!item.isEmpty()) return true; return false; } public Address addAddress() { //3 Address t = new Address(); if (this.address == null) this.address = new ArrayList<Address>(); this.address.add(t); return t; } public Patient addAddress(Address t) { //3 if (t == null) return this; if (this.address == null) this.address = new ArrayList<Address>(); this.address.add(t); return this; } /** * @return The first repetition of repeating field {@link #address}, creating it if it does not already exist */ public Address getAddressFirstRep() { if (getAddress().isEmpty()) { addAddress(); } return getAddress().get(0); } /** * @return {@link #maritalStatus} (This field contains a patient's most recent marital (civil) status.) */ public CodeableConcept getMaritalStatus() { if (this.maritalStatus == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create Patient.maritalStatus"); else if (Configuration.doAutoCreate()) this.maritalStatus = new CodeableConcept(); // cc return this.maritalStatus; } public boolean hasMaritalStatus() { return this.maritalStatus != null && !this.maritalStatus.isEmpty(); } /** * @param value {@link #maritalStatus} (This field contains a patient's most recent marital (civil) status.) */ public Patient setMaritalStatus(CodeableConcept value) { this.maritalStatus = value; return this; } /** * @return {@link #multipleBirth} (Indicates whether the patient is part of a multiple (bool) or indicates the actual birth order (integer).) */ public Type getMultipleBirth() { return this.multipleBirth; } /** * @return {@link #multipleBirth} (Indicates whether the patient is part of a multiple (bool) or indicates the actual birth order (integer).) */ public BooleanType getMultipleBirthBooleanType() throws FHIRException { if (!(this.multipleBirth instanceof BooleanType)) throw new FHIRException("Type mismatch: the type BooleanType was expected, but "+this.multipleBirth.getClass().getName()+" was encountered"); return (BooleanType) this.multipleBirth; } public boolean hasMultipleBirthBooleanType() { return this.multipleBirth instanceof BooleanType; } /** * @return {@link #multipleBirth} (Indicates whether the patient is part of a multiple (bool) or indicates the actual birth order (integer).) */ public IntegerType getMultipleBirthIntegerType() throws FHIRException { if (!(this.multipleBirth instanceof IntegerType)) throw new FHIRException("Type mismatch: the type IntegerType was expected, but "+this.multipleBirth.getClass().getName()+" was encountered"); return (IntegerType) this.multipleBirth; } public boolean hasMultipleBirthIntegerType() { return this.multipleBirth instanceof IntegerType; } public boolean hasMultipleBirth() { return this.multipleBirth != null && !this.multipleBirth.isEmpty(); } /** * @param value {@link #multipleBirth} (Indicates whether the patient is part of a multiple (bool) or indicates the actual birth order (integer).) */ public Patient setMultipleBirth(Type value) { this.multipleBirth = value; return this; } /** * @return {@link #photo} (Image of the patient.) */ public List<Attachment> getPhoto() { if (this.photo == null) this.photo = new ArrayList<Attachment>(); return this.photo; } /** * @return Returns a reference to <code>this</code> for easy method chaining */ public Patient setPhoto(List<Attachment> thePhoto) { this.photo = thePhoto; return this; } public boolean hasPhoto() { if (this.photo == null) return false; for (Attachment item : this.photo) if (!item.isEmpty()) return true; return false; } public Attachment addPhoto() { //3 Attachment t = new Attachment(); if (this.photo == null) this.photo = new ArrayList<Attachment>(); this.photo.add(t); return t; } public Patient addPhoto(Attachment t) { //3 if (t == null) return this; if (this.photo == null) this.photo = new ArrayList<Attachment>(); this.photo.add(t); return this; } /** * @return The first repetition of repeating field {@link #photo}, creating it if it does not already exist */ public Attachment getPhotoFirstRep() { if (getPhoto().isEmpty()) { addPhoto(); } return getPhoto().get(0); } /** * @return {@link #contact} (A contact party (e.g. guardian, partner, friend) for the patient.) */ public List<ContactComponent> getContact() { if (this.contact == null) this.contact = new ArrayList<ContactComponent>(); return this.contact; } /** * @return Returns a reference to <code>this</code> for easy method chaining */ public Patient setContact(List<ContactComponent> theContact) { this.contact = theContact; return this; } public boolean hasContact() { if (this.contact == null) return false; for (ContactComponent item : this.contact) if (!item.isEmpty()) return true; return false; } public ContactComponent addContact() { //3 ContactComponent t = new ContactComponent(); if (this.contact == null) this.contact = new ArrayList<ContactComponent>(); this.contact.add(t); return t; } public Patient addContact(ContactComponent t) { //3 if (t == null) return this; if (this.contact == null) this.contact = new ArrayList<ContactComponent>(); this.contact.add(t); return this; } /** * @return The first repetition of repeating field {@link #contact}, creating it if it does not already exist */ public ContactComponent getContactFirstRep() { if (getContact().isEmpty()) { addContact(); } return getContact().get(0); } /** * @return {@link #animal} (This patient is known to be an animal.) */ public AnimalComponent getAnimal() { if (this.animal == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create Patient.animal"); else if (Configuration.doAutoCreate()) this.animal = new AnimalComponent(); // cc return this.animal; } public boolean hasAnimal() { return this.animal != null && !this.animal.isEmpty(); } /** * @param value {@link #animal} (This patient is known to be an animal.) */ public Patient setAnimal(AnimalComponent value) { this.animal = value; return this; } /** * @return {@link #communication} (Languages which may be used to communicate with the patient about his or her health.) */ public List<PatientCommunicationComponent> getCommunication() { if (this.communication == null) this.communication = new ArrayList<PatientCommunicationComponent>(); return this.communication; } /** * @return Returns a reference to <code>this</code> for easy method chaining */ public Patient setCommunication(List<PatientCommunicationComponent> theCommunication) { this.communication = theCommunication; return this; } public boolean hasCommunication() { if (this.communication == null) return false; for (PatientCommunicationComponent item : this.communication) if (!item.isEmpty()) return true; return false; } public PatientCommunicationComponent addCommunication() { //3 PatientCommunicationComponent t = new PatientCommunicationComponent(); if (this.communication == null) this.communication = new ArrayList<PatientCommunicationComponent>(); this.communication.add(t); return t; } public Patient addCommunication(PatientCommunicationComponent t) { //3 if (t == null) return this; if (this.communication == null) this.communication = new ArrayList<PatientCommunicationComponent>(); this.communication.add(t); return this; } /** * @return The first repetition of repeating field {@link #communication}, creating it if it does not already exist */ public PatientCommunicationComponent getCommunicationFirstRep() { if (getCommunication().isEmpty()) { addCommunication(); } return getCommunication().get(0); } /** * @return {@link #generalPractitioner} (Patient's nominated care provider.) */ public List<Reference> getGeneralPractitioner() { if (this.generalPractitioner == null) this.generalPractitioner = new ArrayList<Reference>(); return this.generalPractitioner; } /** * @return Returns a reference to <code>this</code> for easy method chaining */ public Patient setGeneralPractitioner(List<Reference> theGeneralPractitioner) { this.generalPractitioner = theGeneralPractitioner; return this; } public boolean hasGeneralPractitioner() { if (this.generalPractitioner == null) return false; for (Reference item : this.generalPractitioner) if (!item.isEmpty()) return true; return false; } public Reference addGeneralPractitioner() { //3 Reference t = new Reference(); if (this.generalPractitioner == null) this.generalPractitioner = new ArrayList<Reference>(); this.generalPractitioner.add(t); return t; } public Patient addGeneralPractitioner(Reference t) { //3 if (t == null) return this; if (this.generalPractitioner == null) this.generalPractitioner = new ArrayList<Reference>(); this.generalPractitioner.add(t); return this; } /** * @return The first repetition of repeating field {@link #generalPractitioner}, creating it if it does not already exist */ public Reference getGeneralPractitionerFirstRep() { if (getGeneralPractitioner().isEmpty()) { addGeneralPractitioner(); } return getGeneralPractitioner().get(0); } /** * @deprecated Use Reference#setResource(IBaseResource) instead */ @Deprecated public List<Resource> getGeneralPractitionerTarget() { if (this.generalPractitionerTarget == null) this.generalPractitionerTarget = new ArrayList<Resource>(); return this.generalPractitionerTarget; } /** * @return {@link #managingOrganization} (Organization that is the custodian of the patient record.) */ public Reference getManagingOrganization() { if (this.managingOrganization == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create Patient.managingOrganization"); else if (Configuration.doAutoCreate()) this.managingOrganization = new Reference(); // cc return this.managingOrganization; } public boolean hasManagingOrganization() { return this.managingOrganization != null && !this.managingOrganization.isEmpty(); } /** * @param value {@link #managingOrganization} (Organization that is the custodian of the patient record.) */ public Patient setManagingOrganization(Reference value) { this.managingOrganization = value; return this; } /** * @return {@link #managingOrganization} The actual object that is the target of the reference. The reference library doesn't populate this, but you can use it to hold the resource if you resolve it. (Organization that is the custodian of the patient record.) */ public Organization getManagingOrganizationTarget() { if (this.managingOrganizationTarget == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create Patient.managingOrganization"); else if (Configuration.doAutoCreate()) this.managingOrganizationTarget = new Organization(); // aa return this.managingOrganizationTarget; } /** * @param value {@link #managingOrganization} The actual object that is the target of the reference. The reference library doesn't use these, but you can use it to hold the resource if you resolve it. (Organization that is the custodian of the patient record.) */ public Patient setManagingOrganizationTarget(Organization value) { this.managingOrganizationTarget = value; return this; } /** * @return {@link #link} (Link to another patient resource that concerns the same actual patient.) */ public List<PatientLinkComponent> getLink() { if (this.link == null) this.link = new ArrayList<PatientLinkComponent>(); return this.link; } /** * @return Returns a reference to <code>this</code> for easy method chaining */ public Patient setLink(List<PatientLinkComponent> theLink) { this.link = theLink; return this; } public boolean hasLink() { if (this.link == null) return false; for (PatientLinkComponent item : this.link) if (!item.isEmpty()) return true; return false; } public PatientLinkComponent addLink() { //3 PatientLinkComponent t = new PatientLinkComponent(); if (this.link == null) this.link = new ArrayList<PatientLinkComponent>(); this.link.add(t); return t; } public Patient addLink(PatientLinkComponent t) { //3 if (t == null) return this; if (this.link == null) this.link = new ArrayList<PatientLinkComponent>(); this.link.add(t); return this; } /** * @return The first repetition of repeating field {@link #link}, creating it if it does not already exist */ public PatientLinkComponent getLinkFirstRep() { if (getLink().isEmpty()) { addLink(); } return getLink().get(0); } protected void listChildren(List<Property> childrenList) { super.listChildren(childrenList); childrenList.add(new Property("identifier", "Identifier", "An identifier for this patient.", 0, java.lang.Integer.MAX_VALUE, identifier)); childrenList.add(new Property("active", "boolean", "Whether this patient record is in active use.", 0, java.lang.Integer.MAX_VALUE, active)); childrenList.add(new Property("name", "HumanName", "A name associated with the individual.", 0, java.lang.Integer.MAX_VALUE, name)); childrenList.add(new Property("telecom", "ContactPoint", "A contact detail (e.g. a telephone number or an email address) by which the individual may be contacted.", 0, java.lang.Integer.MAX_VALUE, telecom)); childrenList.add(new Property("gender", "code", "Administrative Gender - the gender that the patient is considered to have for administration and record keeping purposes.", 0, java.lang.Integer.MAX_VALUE, gender)); childrenList.add(new Property("birthDate", "date", "The date of birth for the individual.", 0, java.lang.Integer.MAX_VALUE, birthDate)); childrenList.add(new Property("deceased[x]", "boolean|dateTime", "Indicates if the individual is deceased or not.", 0, java.lang.Integer.MAX_VALUE, deceased)); childrenList.add(new Property("address", "Address", "Addresses for the individual.", 0, java.lang.Integer.MAX_VALUE, address)); childrenList.add(new Property("maritalStatus", "CodeableConcept", "This field contains a patient's most recent marital (civil) status.", 0, java.lang.Integer.MAX_VALUE, maritalStatus)); childrenList.add(new Property("multipleBirth[x]", "boolean|integer", "Indicates whether the patient is part of a multiple (bool) or indicates the actual birth order (integer).", 0, java.lang.Integer.MAX_VALUE, multipleBirth)); childrenList.add(new Property("photo", "Attachment", "Image of the patient.", 0, java.lang.Integer.MAX_VALUE, photo)); childrenList.add(new Property("contact", "", "A contact party (e.g. guardian, partner, friend) for the patient.", 0, java.lang.Integer.MAX_VALUE, contact)); childrenList.add(new Property("animal", "", "This patient is known to be an animal.", 0, java.lang.Integer.MAX_VALUE, animal)); childrenList.add(new Property("communication", "", "Languages which may be used to communicate with the patient about his or her health.", 0, java.lang.Integer.MAX_VALUE, communication)); childrenList.add(new Property("generalPractitioner", "Reference(Organization|Practitioner)", "Patient's nominated care provider.", 0, java.lang.Integer.MAX_VALUE, generalPractitioner)); childrenList.add(new Property("managingOrganization", "Reference(Organization)", "Organization that is the custodian of the patient record.", 0, java.lang.Integer.MAX_VALUE, managingOrganization)); childrenList.add(new Property("link", "", "Link to another patient resource that concerns the same actual patient.", 0, java.lang.Integer.MAX_VALUE, link)); } @Override public Base[] getProperty(int hash, String name, boolean checkValid) throws FHIRException { switch (hash) { case -1618432855: /*identifier*/ return this.identifier == null ? new Base[0] : this.identifier.toArray(new Base[this.identifier.size()]); // Identifier case -1422950650: /*active*/ return this.active == null ? new Base[0] : new Base[] {this.active}; // BooleanType case 3373707: /*name*/ return this.name == null ? new Base[0] : this.name.toArray(new Base[this.name.size()]); // HumanName case -1429363305: /*telecom*/ return this.telecom == null ? new Base[0] : this.telecom.toArray(new Base[this.telecom.size()]); // ContactPoint case -1249512767: /*gender*/ return this.gender == null ? new Base[0] : new Base[] {this.gender}; // Enumeration<AdministrativeGender> case -1210031859: /*birthDate*/ return this.birthDate == null ? new Base[0] : new Base[] {this.birthDate}; // DateType case 561497972: /*deceased*/ return this.deceased == null ? new Base[0] : new Base[] {this.deceased}; // Type case -1147692044: /*address*/ return this.address == null ? new Base[0] : this.address.toArray(new Base[this.address.size()]); // Address case 1756919302: /*maritalStatus*/ return this.maritalStatus == null ? new Base[0] : new Base[] {this.maritalStatus}; // CodeableConcept case -677369713: /*multipleBirth*/ return this.multipleBirth == null ? new Base[0] : new Base[] {this.multipleBirth}; // Type case 106642994: /*photo*/ return this.photo == null ? new Base[0] : this.photo.toArray(new Base[this.photo.size()]); // Attachment case 951526432: /*contact*/ return this.contact == null ? new Base[0] : this.contact.toArray(new Base[this.contact.size()]); // ContactComponent case -1413116420: /*animal*/ return this.animal == null ? new Base[0] : new Base[] {this.animal}; // AnimalComponent case -1035284522: /*communication*/ return this.communication == null ? new Base[0] : this.communication.toArray(new Base[this.communication.size()]); // PatientCommunicationComponent case 1488292898: /*generalPractitioner*/ return this.generalPractitioner == null ? new Base[0] : this.generalPractitioner.toArray(new Base[this.generalPractitioner.size()]); // Reference case -2058947787: /*managingOrganization*/ return this.managingOrganization == null ? new Base[0] : new Base[] {this.managingOrganization}; // Reference case 3321850: /*link*/ return this.link == null ? new Base[0] : this.link.toArray(new Base[this.link.size()]); // PatientLinkComponent default: return super.getProperty(hash, name, checkValid); } } @Override public void setProperty(int hash, String name, Base value) throws FHIRException { switch (hash) { case -1618432855: // identifier this.getIdentifier().add(castToIdentifier(value)); // Identifier break; case -1422950650: // active this.active = castToBoolean(value); // BooleanType break; case 3373707: // name this.getName().add(castToHumanName(value)); // HumanName break; case -1429363305: // telecom this.getTelecom().add(castToContactPoint(value)); // ContactPoint break; case -1249512767: // gender this.gender = new AdministrativeGenderEnumFactory().fromType(value); // Enumeration<AdministrativeGender> break; case -1210031859: // birthDate this.birthDate = castToDate(value); // DateType break; case 561497972: // deceased this.deceased = castToType(value); // Type break; case -1147692044: // address this.getAddress().add(castToAddress(value)); // Address break; case 1756919302: // maritalStatus this.maritalStatus = castToCodeableConcept(value); // CodeableConcept break; case -677369713: // multipleBirth this.multipleBirth = castToType(value); // Type break; case 106642994: // photo this.getPhoto().add(castToAttachment(value)); // Attachment break; case 951526432: // contact this.getContact().add((ContactComponent) value); // ContactComponent break; case -1413116420: // animal this.animal = (AnimalComponent) value; // AnimalComponent break; case -1035284522: // communication this.getCommunication().add((PatientCommunicationComponent) value); // PatientCommunicationComponent break; case 1488292898: // generalPractitioner this.getGeneralPractitioner().add(castToReference(value)); // Reference break; case -2058947787: // managingOrganization this.managingOrganization = castToReference(value); // Reference break; case 3321850: // link this.getLink().add((PatientLinkComponent) value); // PatientLinkComponent break; default: super.setProperty(hash, name, value); } } @Override public void setProperty(String name, Base value) throws FHIRException { if (name.equals("identifier")) this.getIdentifier().add(castToIdentifier(value)); else if (name.equals("active")) this.active = castToBoolean(value); // BooleanType else if (name.equals("name")) this.getName().add(castToHumanName(value)); else if (name.equals("telecom")) this.getTelecom().add(castToContactPoint(value)); else if (name.equals("gender")) this.gender = new AdministrativeGenderEnumFactory().fromType(value); // Enumeration<AdministrativeGender> else if (name.equals("birthDate")) this.birthDate = castToDate(value); // DateType else if (name.equals("deceased[x]")) this.deceased = castToType(value); // Type else if (name.equals("address")) this.getAddress().add(castToAddress(value)); else if (name.equals("maritalStatus")) this.maritalStatus = castToCodeableConcept(value); // CodeableConcept else if (name.equals("multipleBirth[x]")) this.multipleBirth = castToType(value); // Type else if (name.equals("photo")) this.getPhoto().add(castToAttachment(value)); else if (name.equals("contact")) this.getContact().add((ContactComponent) value); else if (name.equals("animal")) this.animal = (AnimalComponent) value; // AnimalComponent else if (name.equals("communication")) this.getCommunication().add((PatientCommunicationComponent) value); else if (name.equals("generalPractitioner")) this.getGeneralPractitioner().add(castToReference(value)); else if (name.equals("managingOrganization")) this.managingOrganization = castToReference(value); // Reference else if (name.equals("link")) this.getLink().add((PatientLinkComponent) value); else super.setProperty(name, value); } @Override public Base makeProperty(int hash, String name) throws FHIRException { switch (hash) { case -1618432855: return addIdentifier(); // Identifier case -1422950650: throw new FHIRException("Cannot make property active as it is not a complex type"); // BooleanType case 3373707: return addName(); // HumanName case -1429363305: return addTelecom(); // ContactPoint case -1249512767: throw new FHIRException("Cannot make property gender as it is not a complex type"); // Enumeration<AdministrativeGender> case -1210031859: throw new FHIRException("Cannot make property birthDate as it is not a complex type"); // DateType case -1311442804: return getDeceased(); // Type case -1147692044: return addAddress(); // Address case 1756919302: return getMaritalStatus(); // CodeableConcept case -1764672111: return getMultipleBirth(); // Type case 106642994: return addPhoto(); // Attachment case 951526432: return addContact(); // ContactComponent case -1413116420: return getAnimal(); // AnimalComponent case -1035284522: return addCommunication(); // PatientCommunicationComponent case 1488292898: return addGeneralPractitioner(); // Reference case -2058947787: return getManagingOrganization(); // Reference case 3321850: return addLink(); // PatientLinkComponent default: return super.makeProperty(hash, name); } } @Override public Base addChild(String name) throws FHIRException { if (name.equals("identifier")) { return addIdentifier(); } else if (name.equals("active")) { throw new FHIRException("Cannot call addChild on a primitive type Patient.active"); } else if (name.equals("name")) { return addName(); } else if (name.equals("telecom")) { return addTelecom(); } else if (name.equals("gender")) { throw new FHIRException("Cannot call addChild on a primitive type Patient.gender"); } else if (name.equals("birthDate")) { throw new FHIRException("Cannot call addChild on a primitive type Patient.birthDate"); } else if (name.equals("deceasedBoolean")) { this.deceased = new BooleanType(); return this.deceased; } else if (name.equals("deceasedDateTime")) { this.deceased = new DateTimeType(); return this.deceased; } else if (name.equals("address")) { return addAddress(); } else if (name.equals("maritalStatus")) { this.maritalStatus = new CodeableConcept(); return this.maritalStatus; } else if (name.equals("multipleBirthBoolean")) { this.multipleBirth = new BooleanType(); return this.multipleBirth; } else if (name.equals("multipleBirthInteger")) { this.multipleBirth = new IntegerType(); return this.multipleBirth; } else if (name.equals("photo")) { return addPhoto(); } else if (name.equals("contact")) { return addContact(); } else if (name.equals("animal")) { this.animal = new AnimalComponent(); return this.animal; } else if (name.equals("communication")) { return addCommunication(); } else if (name.equals("generalPractitioner")) { return addGeneralPractitioner(); } else if (name.equals("managingOrganization")) { this.managingOrganization = new Reference(); return this.managingOrganization; } else if (name.equals("link")) { return addLink(); } else return super.addChild(name); } public String fhirType() { return "Patient"; } public Patient copy() { Patient dst = new Patient(); copyValues(dst); if (identifier != null) { dst.identifier = new ArrayList<Identifier>(); for (Identifier i : identifier) dst.identifier.add(i.copy()); }; dst.active = active == null ? null : active.copy(); if (name != null) { dst.name = new ArrayList<HumanName>(); for (HumanName i : name) dst.name.add(i.copy()); }; if (telecom != null) { dst.telecom = new ArrayList<ContactPoint>(); for (ContactPoint i : telecom) dst.telecom.add(i.copy()); }; dst.gender = gender == null ? null : gender.copy(); dst.birthDate = birthDate == null ? null : birthDate.copy(); dst.deceased = deceased == null ? null : deceased.copy(); if (address != null) { dst.address = new ArrayList<Address>(); for (Address i : address) dst.address.add(i.copy()); }; dst.maritalStatus = maritalStatus == null ? null : maritalStatus.copy(); dst.multipleBirth = multipleBirth == null ? null : multipleBirth.copy(); if (photo != null) { dst.photo = new ArrayList<Attachment>(); for (Attachment i : photo) dst.photo.add(i.copy()); }; if (contact != null) { dst.contact = new ArrayList<ContactComponent>(); for (ContactComponent i : contact) dst.contact.add(i.copy()); }; dst.animal = animal == null ? null : animal.copy(); if (communication != null) { dst.communication = new ArrayList<PatientCommunicationComponent>(); for (PatientCommunicationComponent i : communication) dst.communication.add(i.copy()); }; if (generalPractitioner != null) { dst.generalPractitioner = new ArrayList<Reference>(); for (Reference i : generalPractitioner) dst.generalPractitioner.add(i.copy()); }; dst.managingOrganization = managingOrganization == null ? null : managingOrganization.copy(); if (link != null) { dst.link = new ArrayList<PatientLinkComponent>(); for (PatientLinkComponent i : link) dst.link.add(i.copy()); }; return dst; } protected Patient typedCopy() { return copy(); } @Override public boolean equalsDeep(Base other) { if (!super.equalsDeep(other)) return false; if (!(other instanceof Patient)) return false; Patient o = (Patient) other; return compareDeep(identifier, o.identifier, true) && compareDeep(active, o.active, true) && compareDeep(name, o.name, true) && compareDeep(telecom, o.telecom, true) && compareDeep(gender, o.gender, true) && compareDeep(birthDate, o.birthDate, true) && compareDeep(deceased, o.deceased, true) && compareDeep(address, o.address, true) && compareDeep(maritalStatus, o.maritalStatus, true) && compareDeep(multipleBirth, o.multipleBirth, true) && compareDeep(photo, o.photo, true) && compareDeep(contact, o.contact, true) && compareDeep(animal, o.animal, true) && compareDeep(communication, o.communication, true) && compareDeep(generalPractitioner, o.generalPractitioner, true) && compareDeep(managingOrganization, o.managingOrganization, true) && compareDeep(link, o.link, true) ; } @Override public boolean equalsShallow(Base other) { if (!super.equalsShallow(other)) return false; if (!(other instanceof Patient)) return false; Patient o = (Patient) other; return compareValues(active, o.active, true) && compareValues(gender, o.gender, true) && compareValues(birthDate, o.birthDate, true) ; } public boolean isEmpty() { return super.isEmpty() && ca.uhn.fhir.util.ElementUtil.isEmpty(identifier, active, name , telecom, gender, birthDate, deceased, address, maritalStatus, multipleBirth , photo, contact, animal, communication, generalPractitioner, managingOrganization , link); } @Override public ResourceType getResourceType() { return ResourceType.Patient; } /** * Search parameter: <b>birthdate</b> * <p> * Description: <b>The patient's date of birth</b><br> * Type: <b>date</b><br> * Path: <b>Patient.birthDate</b><br> * </p> */ @SearchParamDefinition(name="birthdate", path="Patient.birthDate", description="The patient's date of birth", type="date" ) public static final String SP_BIRTHDATE = "birthdate"; /** * <b>Fluent Client</b> search parameter constant for <b>birthdate</b> * <p> * Description: <b>The patient's date of birth</b><br> * Type: <b>date</b><br> * Path: <b>Patient.birthDate</b><br> * </p> */ public static final ca.uhn.fhir.rest.gclient.DateClientParam BIRTHDATE = new ca.uhn.fhir.rest.gclient.DateClientParam(SP_BIRTHDATE); /** * Search parameter: <b>deceased</b> * <p> * Description: <b>This patient has been marked as deceased, or as a death date entered</b><br> * Type: <b>token</b><br> * Path: <b>Patient.deceased[x]</b><br> * </p> */ @SearchParamDefinition(name="deceased", path="Patient.deceased.exists()", description="This patient has been marked as deceased, or as a death date entered", type="token" ) public static final String SP_DECEASED = "deceased"; /** * <b>Fluent Client</b> search parameter constant for <b>deceased</b> * <p> * Description: <b>This patient has been marked as deceased, or as a death date entered</b><br> * Type: <b>token</b><br> * Path: <b>Patient.deceased[x]</b><br> * </p> */ public static final ca.uhn.fhir.rest.gclient.TokenClientParam DECEASED = new ca.uhn.fhir.rest.gclient.TokenClientParam(SP_DECEASED); /** * Search parameter: <b>address-state</b> * <p> * Description: <b>A state specified in an address</b><br> * Type: <b>string</b><br> * Path: <b>Patient.address.state</b><br> * </p> */ @SearchParamDefinition(name="address-state", path="Patient.address.state", description="A state specified in an address", type="string" ) public static final String SP_ADDRESS_STATE = "address-state"; /** * <b>Fluent Client</b> search parameter constant for <b>address-state</b> * <p> * Description: <b>A state specified in an address</b><br> * Type: <b>string</b><br> * Path: <b>Patient.address.state</b><br> * </p> */ public static final ca.uhn.fhir.rest.gclient.StringClientParam ADDRESS_STATE = new ca.uhn.fhir.rest.gclient.StringClientParam(SP_ADDRESS_STATE); /** * Search parameter: <b>gender</b> * <p> * Description: <b>Gender of the patient</b><br> * Type: <b>token</b><br> * Path: <b>Patient.gender</b><br> * </p> */ @SearchParamDefinition(name="gender", path="Patient.gender", description="Gender of the patient", type="token" ) public static final String SP_GENDER = "gender"; /** * <b>Fluent Client</b> search parameter constant for <b>gender</b> * <p> * Description: <b>Gender of the patient</b><br> * Type: <b>token</b><br> * Path: <b>Patient.gender</b><br> * </p> */ public static final ca.uhn.fhir.rest.gclient.TokenClientParam GENDER = new ca.uhn.fhir.rest.gclient.TokenClientParam(SP_GENDER); /** * Search parameter: <b>animal-species</b> * <p> * Description: <b>The species for animal patients</b><br> * Type: <b>token</b><br> * Path: <b>Patient.animal.species</b><br> * </p> */ @SearchParamDefinition(name="animal-species", path="Patient.animal.species", description="The species for animal patients", type="token" ) public static final String SP_ANIMAL_SPECIES = "animal-species"; /** * <b>Fluent Client</b> search parameter constant for <b>animal-species</b> * <p> * Description: <b>The species for animal patients</b><br> * Type: <b>token</b><br> * Path: <b>Patient.animal.species</b><br> * </p> */ public static final ca.uhn.fhir.rest.gclient.TokenClientParam ANIMAL_SPECIES = new ca.uhn.fhir.rest.gclient.TokenClientParam(SP_ANIMAL_SPECIES); /** * Search parameter: <b>link</b> * <p> * Description: <b>All patients linked to the given patient</b><br> * Type: <b>reference</b><br> * Path: <b>Patient.link.other</b><br> * </p> */ @SearchParamDefinition(name="link", path="Patient.link.other", description="All patients linked to the given patient", type="reference", providesMembershipIn={ @ca.uhn.fhir.model.api.annotation.Compartment(name="Patient"), @ca.uhn.fhir.model.api.annotation.Compartment(name="RelatedPerson") }, target={Patient.class, RelatedPerson.class } ) public static final String SP_LINK = "link"; /** * <b>Fluent Client</b> search parameter constant for <b>link</b> * <p> * Description: <b>All patients linked to the given patient</b><br> * Type: <b>reference</b><br> * Path: <b>Patient.link.other</b><br> * </p> */ public static final ca.uhn.fhir.rest.gclient.ReferenceClientParam LINK = new ca.uhn.fhir.rest.gclient.ReferenceClientParam(SP_LINK); /** * Constant for fluent queries to be used to add include statements. Specifies * the path value of "<b>Patient:link</b>". */ public static final ca.uhn.fhir.model.api.Include INCLUDE_LINK = new ca.uhn.fhir.model.api.Include("Patient:link").toLocked(); /** * Search parameter: <b>language</b> * <p> * Description: <b>Language code (irrespective of use value)</b><br> * Type: <b>token</b><br> * Path: <b>Patient.communication.language</b><br> * </p> */ @SearchParamDefinition(name="language", path="Patient.communication.language", description="Language code (irrespective of use value)", type="token" ) public static final String SP_LANGUAGE = "language"; /** * <b>Fluent Client</b> search parameter constant for <b>language</b> * <p> * Description: <b>Language code (irrespective of use value)</b><br> * Type: <b>token</b><br> * Path: <b>Patient.communication.language</b><br> * </p> */ public static final ca.uhn.fhir.rest.gclient.TokenClientParam LANGUAGE = new ca.uhn.fhir.rest.gclient.TokenClientParam(SP_LANGUAGE); /** * Search parameter: <b>animal-breed</b> * <p> * Description: <b>The breed for animal patients</b><br> * Type: <b>token</b><br> * Path: <b>Patient.animal.breed</b><br> * </p> */ @SearchParamDefinition(name="animal-breed", path="Patient.animal.breed", description="The breed for animal patients", type="token" ) public static final String SP_ANIMAL_BREED = "animal-breed"; /** * <b>Fluent Client</b> search parameter constant for <b>animal-breed</b> * <p> * Description: <b>The breed for animal patients</b><br> * Type: <b>token</b><br> * Path: <b>Patient.animal.breed</b><br> * </p> */ public static final ca.uhn.fhir.rest.gclient.TokenClientParam ANIMAL_BREED = new ca.uhn.fhir.rest.gclient.TokenClientParam(SP_ANIMAL_BREED); /** * Search parameter: <b>address-country</b> * <p> * Description: <b>A country specified in an address</b><br> * Type: <b>string</b><br> * Path: <b>Patient.address.country</b><br> * </p> */ @SearchParamDefinition(name="address-country", path="Patient.address.country", description="A country specified in an address", type="string" ) public static final String SP_ADDRESS_COUNTRY = "address-country"; /** * <b>Fluent Client</b> search parameter constant for <b>address-country</b> * <p> * Description: <b>A country specified in an address</b><br> * Type: <b>string</b><br> * Path: <b>Patient.address.country</b><br> * </p> */ public static final ca.uhn.fhir.rest.gclient.StringClientParam ADDRESS_COUNTRY = new ca.uhn.fhir.rest.gclient.StringClientParam(SP_ADDRESS_COUNTRY); /** * Search parameter: <b>death-date</b> * <p> * Description: <b>The date of death has been provided and satisfies this search value</b><br> * Type: <b>date</b><br> * Path: <b>Patient.deceasedDateTime</b><br> * </p> */ @SearchParamDefinition(name="death-date", path="Patient.deceased.as(DateTime)", description="The date of death has been provided and satisfies this search value", type="date" ) public static final String SP_DEATH_DATE = "death-date"; /** * <b>Fluent Client</b> search parameter constant for <b>death-date</b> * <p> * Description: <b>The date of death has been provided and satisfies this search value</b><br> * Type: <b>date</b><br> * Path: <b>Patient.deceasedDateTime</b><br> * </p> */ public static final ca.uhn.fhir.rest.gclient.DateClientParam DEATH_DATE = new ca.uhn.fhir.rest.gclient.DateClientParam(SP_DEATH_DATE); /** * Search parameter: <b>phonetic</b> * <p> * Description: <b>A portion of either family or given name using some kind of phonetic matching algorithm</b><br> * Type: <b>string</b><br> * Path: <b>Patient.name</b><br> * </p> */ @SearchParamDefinition(name="phonetic", path="Patient.name", description="A portion of either family or given name using some kind of phonetic matching algorithm", type="string" ) public static final String SP_PHONETIC = "phonetic"; /** * <b>Fluent Client</b> search parameter constant for <b>phonetic</b> * <p> * Description: <b>A portion of either family or given name using some kind of phonetic matching algorithm</b><br> * Type: <b>string</b><br> * Path: <b>Patient.name</b><br> * </p> */ public static final ca.uhn.fhir.rest.gclient.StringClientParam PHONETIC = new ca.uhn.fhir.rest.gclient.StringClientParam(SP_PHONETIC); /** * Search parameter: <b>telecom</b> * <p> * Description: <b>The value in any kind of telecom details of the patient</b><br> * Type: <b>token</b><br> * Path: <b>Patient.telecom</b><br> * </p> */ @SearchParamDefinition(name="telecom", path="Patient.telecom", description="The value in any kind of telecom details of the patient", type="token" ) public static final String SP_TELECOM = "telecom"; /** * <b>Fluent Client</b> search parameter constant for <b>telecom</b> * <p> * Description: <b>The value in any kind of telecom details of the patient</b><br> * Type: <b>token</b><br> * Path: <b>Patient.telecom</b><br> * </p> */ public static final ca.uhn.fhir.rest.gclient.TokenClientParam TELECOM = new ca.uhn.fhir.rest.gclient.TokenClientParam(SP_TELECOM); /** * Search parameter: <b>address-city</b> * <p> * Description: <b>A city specified in an address</b><br> * Type: <b>string</b><br> * Path: <b>Patient.address.city</b><br> * </p> */ @SearchParamDefinition(name="address-city", path="Patient.address.city", description="A city specified in an address", type="string" ) public static final String SP_ADDRESS_CITY = "address-city"; /** * <b>Fluent Client</b> search parameter constant for <b>address-city</b> * <p> * Description: <b>A city specified in an address</b><br> * Type: <b>string</b><br> * Path: <b>Patient.address.city</b><br> * </p> */ public static final ca.uhn.fhir.rest.gclient.StringClientParam ADDRESS_CITY = new ca.uhn.fhir.rest.gclient.StringClientParam(SP_ADDRESS_CITY); /** * Search parameter: <b>email</b> * <p> * Description: <b>A value in an email contact</b><br> * Type: <b>token</b><br> * Path: <b>Patient.telecom(system=email)</b><br> * </p> */ @SearchParamDefinition(name="email", path="Patient.telecom.where(system='email')", description="A value in an email contact", type="token" ) public static final String SP_EMAIL = "email"; /** * <b>Fluent Client</b> search parameter constant for <b>email</b> * <p> * Description: <b>A value in an email contact</b><br> * Type: <b>token</b><br> * Path: <b>Patient.telecom(system=email)</b><br> * </p> */ public static final ca.uhn.fhir.rest.gclient.TokenClientParam EMAIL = new ca.uhn.fhir.rest.gclient.TokenClientParam(SP_EMAIL); /** * Search parameter: <b>identifier</b> * <p> * Description: <b>A patient identifier</b><br> * Type: <b>token</b><br> * Path: <b>Patient.identifier</b><br> * </p> */ @SearchParamDefinition(name="identifier", path="Patient.identifier", description="A patient identifier", type="token" ) public static final String SP_IDENTIFIER = "identifier"; /** * <b>Fluent Client</b> search parameter constant for <b>identifier</b> * <p> * Description: <b>A patient identifier</b><br> * Type: <b>token</b><br> * Path: <b>Patient.identifier</b><br> * </p> */ public static final ca.uhn.fhir.rest.gclient.TokenClientParam IDENTIFIER = new ca.uhn.fhir.rest.gclient.TokenClientParam(SP_IDENTIFIER); /** * Search parameter: <b>given</b> * <p> * Description: <b>A portion of the given name of the patient</b><br> * Type: <b>string</b><br> * Path: <b>Patient.name.given</b><br> * </p> */ @SearchParamDefinition(name="given", path="Patient.name.given", description="A portion of the given name of the patient", type="string" ) public static final String SP_GIVEN = "given"; /** * <b>Fluent Client</b> search parameter constant for <b>given</b> * <p> * Description: <b>A portion of the given name of the patient</b><br> * Type: <b>string</b><br> * Path: <b>Patient.name.given</b><br> * </p> */ public static final ca.uhn.fhir.rest.gclient.StringClientParam GIVEN = new ca.uhn.fhir.rest.gclient.StringClientParam(SP_GIVEN); /** * Search parameter: <b>address</b> * <p> * Description: <b>A server defined search that may match any of the string fields in the Address, including line, city, state, country, postalCode, and/or text</b><br> * Type: <b>string</b><br> * Path: <b>Patient.address</b><br> * </p> */ @SearchParamDefinition(name="address", path="Patient.address", description="A server defined search that may match any of the string fields in the Address, including line, city, state, country, postalCode, and/or text", type="string" ) public static final String SP_ADDRESS = "address"; /** * <b>Fluent Client</b> search parameter constant for <b>address</b> * <p> * Description: <b>A server defined search that may match any of the string fields in the Address, including line, city, state, country, postalCode, and/or text</b><br> * Type: <b>string</b><br> * Path: <b>Patient.address</b><br> * </p> */ public static final ca.uhn.fhir.rest.gclient.StringClientParam ADDRESS = new ca.uhn.fhir.rest.gclient.StringClientParam(SP_ADDRESS); /** * Search parameter: <b>general-practitioner</b> * <p> * Description: <b>Patient's nominated general practitioner, not the organization that manages the record</b><br> * Type: <b>reference</b><br> * Path: <b>Patient.generalPractitioner</b><br> * </p> */ @SearchParamDefinition(name="general-practitioner", path="Patient.generalPractitioner", description="Patient's nominated general practitioner, not the organization that manages the record", type="reference", providesMembershipIn={ @ca.uhn.fhir.model.api.annotation.Compartment(name="Practitioner") }, target={Organization.class, Practitioner.class } ) public static final String SP_GENERAL_PRACTITIONER = "general-practitioner"; /** * <b>Fluent Client</b> search parameter constant for <b>general-practitioner</b> * <p> * Description: <b>Patient's nominated general practitioner, not the organization that manages the record</b><br> * Type: <b>reference</b><br> * Path: <b>Patient.generalPractitioner</b><br> * </p> */ public static final ca.uhn.fhir.rest.gclient.ReferenceClientParam GENERAL_PRACTITIONER = new ca.uhn.fhir.rest.gclient.ReferenceClientParam(SP_GENERAL_PRACTITIONER); /** * Constant for fluent queries to be used to add include statements. Specifies * the path value of "<b>Patient:general-practitioner</b>". */ public static final ca.uhn.fhir.model.api.Include INCLUDE_GENERAL_PRACTITIONER = new ca.uhn.fhir.model.api.Include("Patient:general-practitioner").toLocked(); /** * Search parameter: <b>active</b> * <p> * Description: <b>Whether the patient record is active</b><br> * Type: <b>token</b><br> * Path: <b>Patient.active</b><br> * </p> */ @SearchParamDefinition(name="active", path="Patient.active", description="Whether the patient record is active", type="token" ) public static final String SP_ACTIVE = "active"; /** * <b>Fluent Client</b> search parameter constant for <b>active</b> * <p> * Description: <b>Whether the patient record is active</b><br> * Type: <b>token</b><br> * Path: <b>Patient.active</b><br> * </p> */ public static final ca.uhn.fhir.rest.gclient.TokenClientParam ACTIVE = new ca.uhn.fhir.rest.gclient.TokenClientParam(SP_ACTIVE); /** * Search parameter: <b>address-postalcode</b> * <p> * Description: <b>A postalCode specified in an address</b><br> * Type: <b>string</b><br> * Path: <b>Patient.address.postalCode</b><br> * </p> */ @SearchParamDefinition(name="address-postalcode", path="Patient.address.postalCode", description="A postalCode specified in an address", type="string" ) public static final String SP_ADDRESS_POSTALCODE = "address-postalcode"; /** * <b>Fluent Client</b> search parameter constant for <b>address-postalcode</b> * <p> * Description: <b>A postalCode specified in an address</b><br> * Type: <b>string</b><br> * Path: <b>Patient.address.postalCode</b><br> * </p> */ public static final ca.uhn.fhir.rest.gclient.StringClientParam ADDRESS_POSTALCODE = new ca.uhn.fhir.rest.gclient.StringClientParam(SP_ADDRESS_POSTALCODE); /** * Search parameter: <b>phone</b> * <p> * Description: <b>A value in a phone contact</b><br> * Type: <b>token</b><br> * Path: <b>Patient.telecom(system=phone)</b><br> * </p> */ @SearchParamDefinition(name="phone", path="Patient.telecom.where(system='phone')", description="A value in a phone contact", type="token" ) public static final String SP_PHONE = "phone"; /** * <b>Fluent Client</b> search parameter constant for <b>phone</b> * <p> * Description: <b>A value in a phone contact</b><br> * Type: <b>token</b><br> * Path: <b>Patient.telecom(system=phone)</b><br> * </p> */ public static final ca.uhn.fhir.rest.gclient.TokenClientParam PHONE = new ca.uhn.fhir.rest.gclient.TokenClientParam(SP_PHONE); /** * Search parameter: <b>organization</b> * <p> * Description: <b>The organization at which this person is a patient</b><br> * Type: <b>reference</b><br> * Path: <b>Patient.managingOrganization</b><br> * </p> */ @SearchParamDefinition(name="organization", path="Patient.managingOrganization", description="The organization at which this person is a patient", type="reference", target={Organization.class } ) public static final String SP_ORGANIZATION = "organization"; /** * <b>Fluent Client</b> search parameter constant for <b>organization</b> * <p> * Description: <b>The organization at which this person is a patient</b><br> * Type: <b>reference</b><br> * Path: <b>Patient.managingOrganization</b><br> * </p> */ public static final ca.uhn.fhir.rest.gclient.ReferenceClientParam ORGANIZATION = new ca.uhn.fhir.rest.gclient.ReferenceClientParam(SP_ORGANIZATION); /** * Constant for fluent queries to be used to add include statements. Specifies * the path value of "<b>Patient:organization</b>". */ public static final ca.uhn.fhir.model.api.Include INCLUDE_ORGANIZATION = new ca.uhn.fhir.model.api.Include("Patient:organization").toLocked(); /** * Search parameter: <b>name</b> * <p> * Description: <b>A server defined search that may match any of the string fields in the HumanName, including family, give, prefix, suffix, suffix, and/or text</b><br> * Type: <b>string</b><br> * Path: <b>Patient.name</b><br> * </p> */ @SearchParamDefinition(name="name", path="Patient.name", description="A server defined search that may match any of the string fields in the HumanName, including family, give, prefix, suffix, suffix, and/or text", type="string" ) public static final String SP_NAME = "name"; /** * <b>Fluent Client</b> search parameter constant for <b>name</b> * <p> * Description: <b>A server defined search that may match any of the string fields in the HumanName, including family, give, prefix, suffix, suffix, and/or text</b><br> * Type: <b>string</b><br> * Path: <b>Patient.name</b><br> * </p> */ public static final ca.uhn.fhir.rest.gclient.StringClientParam NAME = new ca.uhn.fhir.rest.gclient.StringClientParam(SP_NAME); /** * Search parameter: <b>address-use</b> * <p> * Description: <b>A use code specified in an address</b><br> * Type: <b>token</b><br> * Path: <b>Patient.address.use</b><br> * </p> */ @SearchParamDefinition(name="address-use", path="Patient.address.use", description="A use code specified in an address", type="token" ) public static final String SP_ADDRESS_USE = "address-use"; /** * <b>Fluent Client</b> search parameter constant for <b>address-use</b> * <p> * Description: <b>A use code specified in an address</b><br> * Type: <b>token</b><br> * Path: <b>Patient.address.use</b><br> * </p> */ public static final ca.uhn.fhir.rest.gclient.TokenClientParam ADDRESS_USE = new ca.uhn.fhir.rest.gclient.TokenClientParam(SP_ADDRESS_USE); /** * Search parameter: <b>family</b> * <p> * Description: <b>A portion of the family name of the patient</b><br> * Type: <b>string</b><br> * Path: <b>Patient.name.family</b><br> * </p> */ @SearchParamDefinition(name="family", path="Patient.name.family", description="A portion of the family name of the patient", type="string" ) public static final String SP_FAMILY = "family"; /** * <b>Fluent Client</b> search parameter constant for <b>family</b> * <p> * Description: <b>A portion of the family name of the patient</b><br> * Type: <b>string</b><br> * Path: <b>Patient.name.family</b><br> * </p> */ public static final ca.uhn.fhir.rest.gclient.StringClientParam FAMILY = new ca.uhn.fhir.rest.gclient.StringClientParam(SP_FAMILY); }
Gaduo/hapi-fhir
hapi-fhir-structures-dstu3/src/main/java/org/hl7/fhir/dstu3/model/Patient.java
Java
apache-2.0
135,364
# frozen_string_literal: true require 'spec_helper' require 'unit/vm_manager/create/shared_stuff.rb' describe Bosh::AzureCloud::VMManager do include_context 'shared stuff for vm manager' describe '#create' do let(:agent_util) { instance_double(Bosh::AzureCloud::BoshAgentUtil) } let(:network_spec) { {} } let(:config) { instance_double(Bosh::AzureCloud::Config) } before do allow(vm_manager).to receive(:_get_stemcell_info).and_return(stemcell_info) end context 'when the resource group name is not specified in the network spec' do context 'when subnet is not found in the default resource group' do before do allow(azure_client).to receive(:list_network_interfaces_by_keyword) .with(MOCK_RESOURCE_GROUP_NAME, vm_name) .and_return([]) allow(azure_client).to receive(:get_load_balancer_by_name) .with(vm_props.load_balancer.resource_group_name, vm_props.load_balancer.name) .and_return(load_balancer) allow(azure_client).to receive(:get_application_gateway_by_name) .with(vm_props.application_gateway) .and_return(application_gateway) allow(azure_client).to receive(:list_public_ips) .and_return([{ ip_address: 'public-ip' }]) allow(azure_client).to receive(:get_network_subnet_by_name) .with(MOCK_RESOURCE_GROUP_NAME, 'fake-virtual-network-name', 'fake-subnet-name') .and_return(nil) end it 'should raise an error' do expect do vm_manager.create(bosh_vm_meta, location, vm_props, disk_cids, network_configurator, env, agent_util, network_spec, config) end.to raise_error %r{Cannot find the subnet 'fake-virtual-network-name\/fake-subnet-name' in the resource group '#{MOCK_RESOURCE_GROUP_NAME}'} end end context 'when network security group is not found in the default resource group' do before do allow(azure_client).to receive(:list_network_interfaces_by_keyword) .with(MOCK_RESOURCE_GROUP_NAME, vm_name) .and_return([]) allow(azure_client).to receive(:get_load_balancer_by_name) .with(vm_props.load_balancer.resource_group_name, vm_props.load_balancer.name) .and_return(load_balancer) allow(azure_client).to receive(:get_application_gateway_by_name) .with(vm_props.application_gateway) .and_return(application_gateway) allow(azure_client).to receive(:list_public_ips) .and_return([{ ip_address: 'public-ip' }]) allow(azure_client).to receive(:get_network_security_group_by_name) .with(MOCK_RESOURCE_GROUP_NAME, MOCK_DEFAULT_SECURITY_GROUP) .and_return(nil) end it 'should raise an error' do expect do vm_manager.create(bosh_vm_meta, location, vm_props, disk_cids, network_configurator, env, agent_util, network_spec, config) end.to raise_error /Cannot find the network security group 'fake-default-nsg-name'/ end end end context 'when the resource group name is specified in the network spec' do before do allow(azure_client).to receive(:get_network_security_group_by_name) .with('fake-resource-group-name', MOCK_DEFAULT_SECURITY_GROUP) .and_return(default_security_group) allow(manual_network).to receive(:resource_group_name) .and_return('fake-resource-group-name') allow(azure_client).to receive(:get_load_balancer_by_name) .with(vm_props.load_balancer.resource_group_name, vm_props.load_balancer.name) .and_return(load_balancer) allow(azure_client).to receive(:get_application_gateway_by_name) .with(vm_props.application_gateway) .and_return(application_gateway) allow(azure_client).to receive(:list_public_ips) .and_return([{ ip_address: 'public-ip' }]) end context 'when subnet is not found in the specified resource group' do it 'should raise an error' do allow(azure_client).to receive(:list_network_interfaces_by_keyword) .with(MOCK_RESOURCE_GROUP_NAME, vm_name) .and_return([]) allow(azure_client).to receive(:get_network_subnet_by_name) .with('fake-resource-group-name', 'fake-virtual-network-name', 'fake-subnet-name') .and_return(nil) expect do vm_manager.create(bosh_vm_meta, location, vm_props, disk_cids, network_configurator, env, agent_util, network_spec, config) end.to raise_error %r{Cannot find the subnet 'fake-virtual-network-name\/fake-subnet-name' in the resource group 'fake-resource-group-name'} end end context 'when network security group is not found in the specified resource group nor the default resource group' do before do allow(azure_client).to receive(:list_network_interfaces_by_keyword) .with(MOCK_RESOURCE_GROUP_NAME, vm_name) .and_return([]) allow(azure_client).to receive(:get_network_security_group_by_name) .with(MOCK_RESOURCE_GROUP_NAME, MOCK_DEFAULT_SECURITY_GROUP) .and_return(nil) allow(azure_client).to receive(:get_network_security_group_by_name) .with('fake-resource-group-name', MOCK_DEFAULT_SECURITY_GROUP) .and_return(nil) end it 'should raise an error' do expect do vm_manager.create(bosh_vm_meta, location, vm_props, disk_cids, network_configurator, env, agent_util, network_spec, config) end.to raise_error /Cannot find the network security group 'fake-default-nsg-name'/ end end end context 'when public ip is not found' do before do allow(azure_client).to receive(:get_load_balancer_by_name) .with(vm_props.load_balancer.resource_group_name, vm_props.load_balancer.name) .and_return(load_balancer) allow(azure_client).to receive(:get_application_gateway_by_name) .with(vm_props.application_gateway) .and_return(application_gateway) end context 'when the public ip list azure returns is empty' do it 'should raise an error' do allow(azure_client).to receive(:list_network_interfaces_by_keyword) .with(MOCK_RESOURCE_GROUP_NAME, vm_name) .and_return([]) allow(azure_client).to receive(:list_public_ips) .and_return([]) expect(azure_client).not_to receive(:delete_virtual_machine) expect(azure_client).not_to receive(:delete_network_interface) expect do vm_manager.create(bosh_vm_meta, location, vm_props, disk_cids, network_configurator, env, agent_util, network_spec, config) end.to raise_error /Cannot find the public IP address/ end end context 'when the public ip list azure returns does not match the configured one' do let(:public_ips) do [ { ip_address: 'public-ip' }, { ip_address: 'not-public-ip' } ] end it 'should raise an error' do allow(azure_client).to receive(:list_network_interfaces_by_keyword) .with(MOCK_RESOURCE_GROUP_NAME, vm_name) .and_return([]) allow(azure_client).to receive(:list_public_ips) .and_return(public_ips) allow(vip_network).to receive(:public_ip) .and_return('not-exist-public-ip') expect(azure_client).not_to receive(:delete_virtual_machine) expect(azure_client).not_to receive(:delete_network_interface) expect do vm_manager.create(bosh_vm_meta, location, vm_props, disk_cids, network_configurator, env, agent_util, network_spec, config) end.to raise_error /Cannot find the public IP address/ end end end context 'when load balancer can not be found' do before do allow(azure_client).to receive(:list_network_interfaces_by_keyword) .with(MOCK_RESOURCE_GROUP_NAME, vm_name) .and_return([]) end it 'should raise an error' do allow(azure_client).to receive(:get_load_balancer_by_name) .with(vm_props.load_balancer.resource_group_name, vm_props.load_balancer.name) .and_return(nil) expect(azure_client).not_to receive(:delete_virtual_machine) expect(azure_client).not_to receive(:delete_network_interface) expect do vm_manager.create(bosh_vm_meta, location, vm_props, disk_cids, network_configurator, env, agent_util, network_spec, config) end.to raise_error /Cannot find the load balancer/ end end context 'when application gateway can not be found' do before do allow(azure_client).to receive(:list_network_interfaces_by_keyword) .with(MOCK_RESOURCE_GROUP_NAME, vm_name) .and_return([]) end it 'should raise an error' do allow(azure_client).to receive(:get_load_balancer_by_name) .with(vm_props.load_balancer.resource_group_name, vm_props.load_balancer.name) .and_return(load_balancer) allow(azure_client).to receive(:get_application_gateway_by_name) .with(vm_props.application_gateway) .and_return(nil) expect(azure_client).not_to receive(:delete_virtual_machine) expect(azure_client).not_to receive(:delete_network_interface) expect do vm_manager.create(bosh_vm_meta, location, vm_props, disk_cids, network_configurator, env, agent_util, network_spec, config) end.to raise_error /Cannot find the application gateway/ end end context 'when network interface is not created' do before do allow(azure_client).to receive(:get_network_subnet_by_name) .and_return(subnet) allow(azure_client).to receive(:get_load_balancer_by_name) .with(vm_props.load_balancer.resource_group_name, vm_props.load_balancer.name) .and_return(load_balancer) allow(azure_client).to receive(:get_application_gateway_by_name) .with(vm_props.application_gateway) .and_return(application_gateway) allow(azure_client).to receive(:list_public_ips) .and_return([{ ip_address: 'public-ip' }]) allow(azure_client).to receive(:create_network_interface) .and_raise('network interface is not created') end context 'when none of network interface is created' do before do allow(azure_client).to receive(:list_network_interfaces_by_keyword) .with(MOCK_RESOURCE_GROUP_NAME, vm_name) .and_return([]) end it 'should raise an error and do not delete any network interface' do expect(azure_client).not_to receive(:delete_virtual_machine) expect(azure_client).not_to receive(:delete_network_interface) expect do vm_manager.create(bosh_vm_meta, location, vm_props, disk_cids, network_configurator, env, agent_util, network_spec, config) end.to raise_error /network interface is not created/ end end context 'when one network interface is created and the another one is not' do let(:network_interface) do { id: "/subscriptions/fake-subscription/resourceGroups/fake-resource-group/providers/Microsoft.Network/networkInterfaces/#{vm_name}-x", name: "#{vm_name}-x" } end before do allow(azure_client).to receive(:list_network_interfaces_by_keyword) .with(MOCK_RESOURCE_GROUP_NAME, vm_name) .and_return([network_interface]) allow(azure_client).to receive(:get_network_subnet_by_name) .and_return(subnet) allow(azure_client).to receive(:get_load_balancer_by_name) .with(vm_props.load_balancer.resource_group_name, vm_props.load_balancer.name) .and_return(load_balancer) allow(azure_client).to receive(:get_application_gateway_by_name) .with(vm_props.application_gateway) .and_return(application_gateway) allow(azure_client).to receive(:list_public_ips) .and_return([{ ip_address: 'public-ip' }]) end it 'should delete the (possible) existing network interface and raise an error' do expect(azure_client).to receive(:delete_network_interface).once expect do vm_manager.create(bosh_vm_meta, location, vm_props, disk_cids, network_configurator, env, agent_util, network_spec, config) end.to raise_error /network interface is not created/ end end context 'when dynamic public IP is created' do let(:dynamic_public_ip) { 'fake-dynamic-public-ip' } before do vm_props.assign_dynamic_public_ip = true allow(azure_client).to receive(:get_public_ip_by_name) .with(MOCK_RESOURCE_GROUP_NAME, vm_name) .and_return(dynamic_public_ip) allow(azure_client).to receive(:list_network_interfaces_by_keyword) .with(MOCK_RESOURCE_GROUP_NAME, vm_name) .and_return([]) end it 'should delete the dynamic public IP' do expect(azure_client).to receive(:delete_public_ip).with(MOCK_RESOURCE_GROUP_NAME, vm_name) expect do vm_manager.create(bosh_vm_meta, location, vm_props, disk_cids, network_configurator, env, agent_util, network_spec, config) end.to raise_error /network interface is not created/ end end end end end
cloudfoundry-incubator/bosh-azure-cpi-release
src/bosh_azure_cpi/spec/unit/vm_manager/create/invalid_option_spec.rb
Ruby
apache-2.0
14,062
/* * Copyright (C) 2013 salesforce.com, inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.auraframework.builder; import java.util.Set; import org.auraframework.def.ClientLibraryDef; import org.auraframework.def.DefDescriptor; import org.auraframework.def.RootDefinition; import org.auraframework.system.AuraContext; /** * Builder for {@link ClientLibraryDef} */ public interface ClientLibraryDefBuilder extends DefBuilder<ClientLibraryDef, ClientLibraryDef> { ClientLibraryDefBuilder setParentDescriptor(DefDescriptor<? extends RootDefinition> parentDescriptor); ClientLibraryDefBuilder setName(String name); ClientLibraryDefBuilder setType(ClientLibraryDef.Type type); ClientLibraryDefBuilder setModes(Set<AuraContext.Mode> modes); ClientLibraryDefBuilder setShouldPrefetch(boolean shouldPrefetch); }
forcedotcom/aura
aura/src/main/java/org/auraframework/builder/ClientLibraryDefBuilder.java
Java
apache-2.0
1,366
package io.subutai.core.peer.impl; public class PeerInitializationError extends RuntimeException { public PeerInitializationError( final String message, final Throwable cause ) { super( message, cause ); } }
subutai-io/Subutai
management/server/core/peer-manager/peer-manager-impl/src/main/java/io/subutai/core/peer/impl/PeerInitializationError.java
Java
apache-2.0
230
<?php /* * This file is part of the Force Login module for Magento2. * * (c) bitExpert AG * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace BitExpert\ForceCustomerLogin\Validator; use BitExpert\ForceCustomerLogin\Model\WhitelistEntry as WhitelistEntryModel; /** * Class WhitelistEntry * * @package BitExpert\ForceCustomerLogin\Validator */ class WhitelistEntry { /** * @param WhitelistEntryModel $whitelistEntry * @return bool * @throw \InvalidArgumentException If validation fails */ public function validate( WhitelistEntryModel $whitelistEntry ) { $label = \strlen(\trim((string)$whitelistEntry->getLabel())); if (0 === $label) { throw new \InvalidArgumentException('Label value is too short.'); } if (255 < $label) { throw new \InvalidArgumentException('Label value is too long.'); } $urlRule = \strlen(\trim((string)$whitelistEntry->getUrlRule())); if (0 === $urlRule) { throw new \InvalidArgumentException('Url Rule value is too short.'); } if (255 < $urlRule) { throw new \InvalidArgumentException('Url Rule value is too long.'); } $strategy = \strlen(\trim((string)$whitelistEntry->getStrategy())); if (0 === $strategy) { throw new \InvalidArgumentException('Strategy value is too short.'); } if (255 < $strategy) { throw new \InvalidArgumentException('Strategy value is too long.'); } if (!\is_bool($whitelistEntry->getEditable())) { throw new \InvalidArgumentException('Editable is no boolean value.'); } return true; } }
bitExpert/magento2-force-login
Validator/WhitelistEntry.php
PHP
apache-2.0
1,813
// Copyright 2014 The Oppia Authors. 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. /** * @fileoverview Controller for the conversation skin. */ // Note: This file should be assumed to be in an IIFE, and the constants below // should only be used within this file. var TIME_FADEOUT_MSEC = 100; var TIME_HEIGHT_CHANGE_MSEC = 500; var TIME_FADEIN_MSEC = 100; var TIME_NUM_CARDS_CHANGE_MSEC = 500; oppia.animation('.conversation-skin-responses-animate-slide', function() { return { removeClass: function(element, className, done) { if (className !== 'ng-hide') { done(); return; } element.hide().slideDown(400, done); }, addClass: function(element, className, done) { if (className !== 'ng-hide') { done(); return; } element.slideUp(400, done); } }; }); oppia.animation('.conversation-skin-animate-tutor-card-on-narrow', function() { var tutorCardLeft, tutorCardWidth, tutorCardHeight, oppiaAvatarLeft; var tutorCardAnimatedLeft, tutorCardAnimatedWidth; var beforeAddClass = function(element, className, done) { if (className !== 'ng-hide') { done(); return; } var tutorCard = element; var supplementalCard = $('.conversation-skin-supplemental-card-container'); var oppiaAvatar = $('.conversation-skin-oppia-avatar.show-tutor-card'); oppiaAvatarLeft = supplementalCard.position().left + supplementalCard.width() - oppiaAvatar.width(); tutorCardLeft = tutorCard.position().left; tutorCardWidth = tutorCard.width(); tutorCardHeight = tutorCard.height(); if (tutorCard.offset().left + tutorCardWidth > oppiaAvatar.offset().left) { var animationLength = Math.min(oppiaAvatarLeft - tutorCard.offset().left, tutorCardWidth); tutorCardAnimatedLeft = tutorCardLeft + animationLength; tutorCardAnimatedWidth = tutorCardWidth - animationLength; } else { tutorCardAnimatedLeft = oppiaAvatarLeft; tutorCardAnimatedWidth = 0; } oppiaAvatar.hide(); tutorCard.css({ 'min-width': 0 }); tutorCard.animate({ left: tutorCardAnimatedLeft, width: tutorCardAnimatedWidth, height: 0, opacity: 1 }, 500, function() { oppiaAvatar.show(); tutorCard.css({ left: '', width: '', height: '', opacity: '', 'min-width': '' }); done(); }); }; var removeClass = function(element, className, done) { if (className !== 'ng-hide') { done(); return; } var tutorCard = element; $('.conversation-skin-oppia-avatar.show-tutor-card').hide(0, function() { tutorCard.css({ left: tutorCardAnimatedLeft, width: tutorCardAnimatedWidth, height: 0, opacity: 0, 'min-width': 0 }); tutorCard.animate({ left: tutorCardLeft, width: tutorCardWidth, height: tutorCardHeight, opacity: 1 }, 500, function() { tutorCard.css({ left: '', width: '', height: '', opacity: '', 'min-width': '' }); done(); }); }); }; return { beforeAddClass: beforeAddClass, removeClass: removeClass }; }); oppia.animation('.conversation-skin-animate-cards', function() { // This removes the newly-added class once the animation is finished. var animateCards = function(element, className, done) { var tutorCardElt = jQuery(element).find( '.conversation-skin-main-tutor-card'); var supplementalCardElt = jQuery(element).find( '.conversation-skin-supplemental-card-container'); if (className === 'animate-to-two-cards') { var supplementalWidth = supplementalCardElt.width(); supplementalCardElt.css({ width: 0, 'min-width': '0', opacity: '0' }); supplementalCardElt.animate({ width: supplementalWidth }, TIME_NUM_CARDS_CHANGE_MSEC, function() { supplementalCardElt.animate({ opacity: '1' }, TIME_FADEIN_MSEC, function() { supplementalCardElt.css({ width: '', 'min-width': '', opacity: '' }); jQuery(element).removeClass('animate-to-two-cards'); done(); }); }); return function(cancel) { if (cancel) { supplementalCardElt.css({ width: '', 'min-width': '', opacity: '' }); supplementalCardElt.stop(); jQuery(element).removeClass('animate-to-two-cards'); } }; } else if (className === 'animate-to-one-card') { supplementalCardElt.css({ opacity: 0, 'min-width': 0 }); supplementalCardElt.animate({ width: 0 }, TIME_NUM_CARDS_CHANGE_MSEC, function() { jQuery(element).removeClass('animate-to-one-card'); done(); }); return function(cancel) { if (cancel) { supplementalCardElt.css({ opacity: '', 'min-width': '', width: '' }); supplementalCardElt.stop(); jQuery(element).removeClass('animate-to-one-card'); } }; } else { return; } }; return { addClass: animateCards }; }); oppia.animation('.conversation-skin-animate-card-contents', function() { var animateCardChange = function(element, className, done) { if (className !== 'animate-card-change') { return; } var currentHeight = element.height(); var expectedNextHeight = $( '.conversation-skin-future-tutor-card ' + '.conversation-skin-tutor-card-content' ).height(); // Fix the current card height, so that it does not change during the // animation, even though its contents might. element.css('height', currentHeight); jQuery(element).animate({ opacity: 0 }, TIME_FADEOUT_MSEC).animate({ height: expectedNextHeight }, TIME_HEIGHT_CHANGE_MSEC).animate({ opacity: 1 }, TIME_FADEIN_MSEC, function() { element.css('height', ''); done(); }); return function(cancel) { if (cancel) { element.css('opacity', '1.0'); element.css('height', ''); element.stop(); } }; }; return { addClass: animateCardChange }; }); oppia.directive('conversationSkin', [function() { return { restrict: 'E', scope: {}, templateUrl: 'skins/Conversation', controller: [ '$scope', '$timeout', '$rootScope', '$window', '$translate', 'messengerService', 'oppiaPlayerService', 'urlService', 'focusService', 'LearnerViewRatingService', 'windowDimensionsService', 'playerTranscriptService', 'LearnerParamsService', 'playerPositionService', 'explorationRecommendationsService', 'StatsReportingService', 'UrlInterpolationService', function( $scope, $timeout, $rootScope, $window, $translate, messengerService, oppiaPlayerService, urlService, focusService, LearnerViewRatingService, windowDimensionsService, playerTranscriptService, LearnerParamsService, playerPositionService, explorationRecommendationsService, StatsReportingService, UrlInterpolationService) { $scope.CONTINUE_BUTTON_FOCUS_LABEL = 'continueButton'; // The exploration domain object. $scope.exploration = null; // The minimum width, in pixels, needed to be able to show two cards // side-by-side. var TWO_CARD_THRESHOLD_PX = 960; var TIME_PADDING_MSEC = 250; var TIME_SCROLL_MSEC = 600; var MIN_CARD_LOADING_DELAY_MSEC = 950; var CONTENT_FOCUS_LABEL_PREFIX = 'content-focus-label-'; var hasInteractedAtLeastOnce = false; var _answerIsBeingProcessed = false; var _nextFocusLabel = null; // This variable is used only when viewport is narrow. // Indicates whether the tutor card is displayed. var tutorCardIsDisplayedIfNarrow = true; $scope.explorationId = oppiaPlayerService.getExplorationId(); $scope.isInPreviewMode = oppiaPlayerService.isInPreviewMode(); $scope.isIframed = urlService.isIframed(); $rootScope.loadingMessage = 'Loading'; $scope.hasFullyLoaded = false; $scope.recommendedExplorationSummaries = []; $scope.OPPIA_AVATAR_IMAGE_URL = ( UrlInterpolationService.getStaticImageUrl( '/avatar/oppia_black_72px.png')); $scope.activeCard = null; $scope.numProgressDots = 0; $scope.arePreviousResponsesShown = false; $scope.upcomingStateName = null; $scope.upcomingContentHtml = null; $scope.upcomingInlineInteractionHtml = null; $scope.helpCardHtml = null; $scope.helpCardHasContinueButton = false; $scope.profilePicture = ( UrlInterpolationService.getStaticImageUrl( '/avatar/user_blue_72px.png')); $scope.DEFAULT_TWITTER_SHARE_MESSAGE_PLAYER = GLOBALS.DEFAULT_TWITTER_SHARE_MESSAGE_PLAYER; oppiaPlayerService.getUserProfileImage().then(function(result) { $scope.profilePicture = result; }); $scope.clearHelpCard = function() { $scope.helpCardHtml = null; $scope.helpCardHasContinueButton = false; }; $scope.getContentFocusLabel = function(index) { return CONTENT_FOCUS_LABEL_PREFIX + index; }; // If the exploration is iframed, send data to its parent about its // height so that the parent can be resized as necessary. $scope.lastRequestedHeight = 0; $scope.lastRequestedScroll = false; $scope.adjustPageHeight = function(scroll, callback) { $timeout(function() { var newHeight = document.body.scrollHeight; if (Math.abs($scope.lastRequestedHeight - newHeight) > 50.5 || (scroll && !$scope.lastRequestedScroll)) { // Sometimes setting iframe height to the exact content height // still produces scrollbar, so adding 50 extra px. newHeight += 50; messengerService.sendMessage(messengerService.HEIGHT_CHANGE, { height: newHeight, scroll: scroll }); $scope.lastRequestedHeight = newHeight; $scope.lastRequestedScroll = scroll; } if (callback) { callback(); } }, 100); }; $scope.isOnTerminalCard = function() { return $scope.activeCard && $scope.exploration.isStateTerminal($scope.activeCard.stateName); }; var isSupplementalCardNonempty = function(card) { return !$scope.exploration.isInteractionInline(card.stateName); }; $scope.isCurrentSupplementalCardNonempty = function() { return $scope.activeCard && isSupplementalCardNonempty( $scope.activeCard); }; // Navigates to the currently-active card, and resets the 'show previous // responses' setting. var _navigateToActiveCard = function() { var index = playerPositionService.getActiveCardIndex(); $scope.activeCard = playerTranscriptService.getCard(index); $scope.arePreviousResponsesShown = false; $scope.clearHelpCard(); tutorCardIsDisplayedIfNarrow = true; if (_nextFocusLabel && playerTranscriptService.isLastCard(index)) { focusService.setFocusIfOnDesktop(_nextFocusLabel); } else { focusService.setFocusIfOnDesktop( $scope.getContentFocusLabel(index)); } }; var animateToTwoCards = function(doneCallback) { $scope.isAnimatingToTwoCards = true; $timeout(function() { $scope.isAnimatingToTwoCards = false; if (doneCallback) { doneCallback(); } }, TIME_NUM_CARDS_CHANGE_MSEC + TIME_FADEIN_MSEC + TIME_PADDING_MSEC); }; var animateToOneCard = function(doneCallback) { $scope.isAnimatingToOneCard = true; $timeout(function() { $scope.isAnimatingToOneCard = false; if (doneCallback) { doneCallback(); } }, TIME_NUM_CARDS_CHANGE_MSEC); }; $scope.isCurrentCardAtEndOfTranscript = function() { return playerTranscriptService.isLastCard( playerPositionService.getActiveCardIndex()); }; var _addNewCard = function( stateName, newParams, contentHtml, interactionHtml) { playerTranscriptService.addNewCard( stateName, newParams, contentHtml, interactionHtml); if (newParams) { LearnerParamsService.init(newParams); } $scope.numProgressDots++; var totalNumCards = playerTranscriptService.getNumCards(); var previousSupplementalCardIsNonempty = ( totalNumCards > 1 && isSupplementalCardNonempty( playerTranscriptService.getCard(totalNumCards - 2))); var nextSupplementalCardIsNonempty = isSupplementalCardNonempty( playerTranscriptService.getLastCard()); if (totalNumCards > 1 && $scope.canWindowFitTwoCards() && !previousSupplementalCardIsNonempty && nextSupplementalCardIsNonempty) { playerPositionService.setActiveCardIndex( $scope.numProgressDots - 1); animateToTwoCards(function() {}); } else if ( totalNumCards > 1 && $scope.canWindowFitTwoCards() && previousSupplementalCardIsNonempty && !nextSupplementalCardIsNonempty) { animateToOneCard(function() { playerPositionService.setActiveCardIndex( $scope.numProgressDots - 1); }); } else { playerPositionService.setActiveCardIndex( $scope.numProgressDots - 1); } if ($scope.exploration.isStateTerminal(stateName)) { explorationRecommendationsService.getRecommendedSummaryDicts( $scope.exploration.getAuthorRecommendedExpIds(stateName), function(summaries) { $scope.recommendedExplorationSummaries = summaries; }); } }; $scope.toggleShowPreviousResponses = function() { $scope.arePreviousResponsesShown = !$scope.arePreviousResponsesShown; }; $scope.initializePage = function() { $scope.waitingForOppiaFeedback = false; hasInteractedAtLeastOnce = false; $scope.recommendedExplorationSummaries = []; playerPositionService.init(_navigateToActiveCard); oppiaPlayerService.init(function(exploration, initHtml, newParams) { $scope.exploration = exploration; $scope.isLoggedIn = oppiaPlayerService.isLoggedIn(); _nextFocusLabel = focusService.generateFocusLabel(); _addNewCard( exploration.initStateName, newParams, initHtml, oppiaPlayerService.getInteractionHtml( exploration.initStateName, _nextFocusLabel)); $rootScope.loadingMessage = ''; $scope.hasFullyLoaded = true; // If the exploration is embedded, use the exploration language // as site language. If the exploration language is not supported // as site language, English is used as default. var langCodes = $window.GLOBALS.SUPPORTED_SITE_LANGUAGES.map( function(language) { return language.id; }); if ($scope.isIframed) { var explorationLanguageCode = ( oppiaPlayerService.getExplorationLanguageCode()); if (langCodes.indexOf(explorationLanguageCode) !== -1) { $translate.use(explorationLanguageCode); } else { $translate.use('en'); } } $scope.adjustPageHeight(false, null); $window.scrollTo(0, 0); focusService.setFocusIfOnDesktop(_nextFocusLabel); }); }; $scope.submitAnswer = function(answer, interactionRulesService) { // For some reason, answers are getting submitted twice when the // submit button is clicked. This guards against that. if (_answerIsBeingProcessed || !$scope.isCurrentCardAtEndOfTranscript() || $scope.activeCard.destStateName) { return; } $scope.clearHelpCard(); _answerIsBeingProcessed = true; hasInteractedAtLeastOnce = true; $scope.waitingForOppiaFeedback = true; var _oldStateName = playerTranscriptService.getLastCard().stateName; playerTranscriptService.addNewAnswer(answer); var timeAtServerCall = new Date().getTime(); oppiaPlayerService.submitAnswer( answer, interactionRulesService, function( newStateName, refreshInteraction, feedbackHtml, contentHtml, newParams) { // Do not wait if the interaction is supplemental -- there's // already a delay bringing in the help card. var millisecsLeftToWait = ( !$scope.exploration.isInteractionInline(_oldStateName) ? 1.0 : Math.max(MIN_CARD_LOADING_DELAY_MSEC - ( new Date().getTime() - timeAtServerCall), 1.0)); $timeout(function() { $scope.waitingForOppiaFeedback = false; var pairs = ( playerTranscriptService.getLastCard().answerFeedbackPairs); var lastAnswerFeedbackPair = pairs[pairs.length - 1]; if (_oldStateName === newStateName) { // Stay on the same card. playerTranscriptService.addNewFeedback(feedbackHtml); if (feedbackHtml && !$scope.exploration.isInteractionInline( $scope.activeCard.stateName)) { $scope.helpCardHtml = feedbackHtml; } if (refreshInteraction) { // Replace the previous interaction with another of the // same type. _nextFocusLabel = focusService.generateFocusLabel(); playerTranscriptService.updateLatestInteractionHtml( oppiaPlayerService.getInteractionHtml( newStateName, _nextFocusLabel) + oppiaPlayerService.getRandomSuffix()); } focusService.setFocusIfOnDesktop(_nextFocusLabel); scrollToBottom(); } else { // There is a new card. If there is no feedback, move on // immediately. Otherwise, give the learner a chance to read // the feedback, and display a 'Continue' button. _nextFocusLabel = focusService.generateFocusLabel(); playerTranscriptService.setDestination(newStateName); // These are used to compute the dimensions for the next card. $scope.upcomingStateName = newStateName; $scope.upcomingParams = newParams; $scope.upcomingContentHtml = ( contentHtml + oppiaPlayerService.getRandomSuffix()); var _isNextInteractionInline = ( $scope.exploration.isInteractionInline(newStateName)); $scope.upcomingInlineInteractionHtml = ( _isNextInteractionInline ? oppiaPlayerService.getInteractionHtml( newStateName, _nextFocusLabel ) + oppiaPlayerService.getRandomSuffix() : ''); if (feedbackHtml) { playerTranscriptService.addNewFeedback(feedbackHtml); if (!$scope.exploration.isInteractionInline( $scope.activeCard.stateName)) { $scope.helpCardHtml = feedbackHtml; $scope.helpCardHasContinueButton = true; } _nextFocusLabel = $scope.CONTINUE_BUTTON_FOCUS_LABEL; focusService.setFocusIfOnDesktop(_nextFocusLabel); scrollToBottom(); } else { playerTranscriptService.addNewFeedback(feedbackHtml); $scope.showPendingCard( newStateName, newParams, contentHtml + oppiaPlayerService.getRandomSuffix()); } } _answerIsBeingProcessed = false; }, millisecsLeftToWait); } ); }; $scope.startCardChangeAnimation = false; $scope.showPendingCard = function( newStateName, newParams, newContentHtml) { $scope.startCardChangeAnimation = true; $timeout(function() { var newInteractionHtml = oppiaPlayerService.getInteractionHtml( newStateName, _nextFocusLabel); // Note that newInteractionHtml may be null. if (newInteractionHtml) { newInteractionHtml += oppiaPlayerService.getRandomSuffix(); } _addNewCard( newStateName, newParams, newContentHtml, newInteractionHtml); $scope.upcomingStateName = null; $scope.upcomingParams = null; $scope.upcomingContentHtml = null; $scope.upcomingInlineInteractionHtml = null; }, TIME_FADEOUT_MSEC + 0.1 * TIME_HEIGHT_CHANGE_MSEC); $timeout(function() { focusService.setFocusIfOnDesktop(_nextFocusLabel); scrollToTop(); }, TIME_FADEOUT_MSEC + TIME_HEIGHT_CHANGE_MSEC + 0.5 * TIME_FADEIN_MSEC); $timeout(function() { $scope.startCardChangeAnimation = false; }, TIME_FADEOUT_MSEC + TIME_HEIGHT_CHANGE_MSEC + TIME_FADEIN_MSEC + TIME_PADDING_MSEC); }; var scrollToBottom = function() { $timeout(function() { var tutorCard = $('.conversation-skin-main-tutor-card'); if (tutorCard.length === 0) { return; } var tutorCardBottom = ( tutorCard.offset().top + tutorCard.outerHeight()); if ($(window).scrollTop() + $(window).height() < tutorCardBottom) { $('html, body').animate({ scrollTop: tutorCardBottom - $(window).height() + 12 }, { duration: TIME_SCROLL_MSEC, easing: 'easeOutQuad' }); } }, 100); }; var scrollToTop = function() { $timeout(function() { $('html, body').animate({ scrollTop: 0 }, 800, 'easeOutQuart'); return false; }); }; $scope.submitUserRating = function(ratingValue) { LearnerViewRatingService.submitUserRating(ratingValue); }; $scope.$on('ratingUpdated', function() { $scope.userRating = LearnerViewRatingService.getUserRating(); }); $window.addEventListener('beforeunload', function(e) { if (hasInteractedAtLeastOnce && !$scope.isInPreviewMode && !$scope.exploration.isStateTerminal( playerTranscriptService.getLastCard().stateName)) { StatsReportingService.recordMaybeLeaveEvent( playerTranscriptService.getLastStateName(), LearnerParamsService.getAllParams()); var confirmationMessage = ( 'If you navigate away from this page, your progress on the ' + 'exploration will be lost.'); (e || $window.event).returnValue = confirmationMessage; return confirmationMessage; } }); $scope.windowWidth = windowDimensionsService.getWidth(); $window.onresize = function() { $scope.adjustPageHeight(false, null); $scope.windowWidth = windowDimensionsService.getWidth(); }; $window.addEventListener('scroll', function() { fadeDotsOnScroll(); fixSupplementOnScroll(); }); var fadeDotsOnScroll = function() { var progressDots = $('.conversation-skin-progress-dots'); var progressDotsTop = progressDots.height(); var newOpacity = Math.max( (progressDotsTop - $(window).scrollTop()) / progressDotsTop, 0); progressDots.css({ opacity: newOpacity }); }; var fixSupplementOnScroll = function() { var supplementCard = $('div.conversation-skin-supplemental-card'); var topMargin = $('.navbar-container').height() - 20; if ($(window).scrollTop() > topMargin) { supplementCard.addClass( 'conversation-skin-supplemental-card-fixed'); } else { supplementCard.removeClass( 'conversation-skin-supplemental-card-fixed'); } }; $scope.canWindowFitTwoCards = function() { return $scope.windowWidth >= TWO_CARD_THRESHOLD_PX; }; $scope.isViewportNarrow = function() { return $scope.windowWidth < TWO_CARD_THRESHOLD_PX; }; $scope.isWindowTall = function() { return document.body.scrollHeight > $window.innerHeight; }; $scope.isScreenNarrowAndShowingTutorCard = function() { if (!$scope.isCurrentSupplementalCardNonempty()) { return $scope.isViewportNarrow(); } return $scope.isViewportNarrow() && tutorCardIsDisplayedIfNarrow; }; $scope.isScreenNarrowAndShowingSupplementalCard = function() { return $scope.isViewportNarrow() && !tutorCardIsDisplayedIfNarrow; }; $scope.showTutorCardIfScreenIsNarrow = function() { if ($scope.isViewportNarrow()) { tutorCardIsDisplayedIfNarrow = true; } }; $scope.showSupplementalCardIfScreenIsNarrow = function() { if ($scope.isViewportNarrow()) { tutorCardIsDisplayedIfNarrow = false; } }; $scope.initializePage(); LearnerViewRatingService.init(function(userRating) { $scope.userRating = userRating; }); $scope.collectionId = GLOBALS.collectionId; $scope.collectionTitle = GLOBALS.collectionTitle; } ] }; }]);
raju249/oppia
core/templates/dev/head/player/ConversationSkinDirective.js
JavaScript
apache-2.0
27,713
/* * Copyright 2020 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.drools.workbench.screens.scenariosimulation.kogito.client.dmn; import org.drools.workbench.screens.scenariosimulation.model.typedescriptor.FactModelTuple; import org.jboss.errai.common.client.api.ErrorCallback; import org.jboss.errai.common.client.api.RemoteCallback; import org.kie.workbench.common.dmn.webapp.kogito.marshaller.js.model.dmn12.JSITDefinitions; import org.uberfire.backend.vfs.Path; /** * Interface required because <b>runtime</b> and <b>testing</b> environments would * need/provide different implementations */ public interface KogitoDMNService { void getDMNContent(final Path path, final RemoteCallback<String> remoteCallback, final ErrorCallback<Object> errorCallback); FactModelTuple getFactModelTuple(final JSITDefinitions jsitDefinitions); }
porcelli-forks/drools-wb
drools-wb-screens/drools-wb-scenario-simulation-editor/drools-wb-scenario-simulation-editor-kogito-client/src/main/java/org/drools/workbench/screens/scenariosimulation/kogito/client/dmn/KogitoDMNService.java
Java
apache-2.0
1,412
# Copyright 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. """Log entries within the Google Stackdriver Logging API.""" import collections import json import re from google.protobuf.any_pb2 import Any from google.protobuf.json_format import MessageToDict from google.protobuf.json_format import Parse from google.cloud.logging.resource import Resource from google.cloud._helpers import _name_from_project_path from google.cloud._helpers import _rfc3339_nanos_to_datetime from google.cloud._helpers import _datetime_to_rfc3339 _GLOBAL_RESOURCE = Resource(type='global', labels={}) _LOGGER_TEMPLATE = re.compile(r""" projects/ # static prefix (?P<project>[^/]+) # initial letter, wordchars + hyphen /logs/ # static midfix (?P<name>[^/]+) # initial letter, wordchars + allowed punc """, re.VERBOSE) def logger_name_from_path(path): """Validate a logger URI path and get the logger name. :type path: str :param path: URI path for a logger API request. :rtype: str :returns: Logger name parsed from ``path``. :raises: :class:`ValueError` if the ``path`` is ill-formed or if the project from the ``path`` does not agree with the ``project`` passed in. """ return _name_from_project_path(path, None, _LOGGER_TEMPLATE) def _int_or_none(value): """Helper: return an integer or ``None``.""" if value is not None: value = int(value) return value _LOG_ENTRY_FIELDS = ( # (name, default) ('log_name', None), ('labels', None), ('insert_id', None), ('severity', None), ('http_request', None), ('timestamp', None), ('resource', _GLOBAL_RESOURCE), ('trace', None), ('span_id', None), ('trace_sampled', None), ('source_location', None), ('operation', None), ('logger', None), ('payload', None), ) _LogEntryTuple = collections.namedtuple( 'LogEntry', (field for field, _ in _LOG_ENTRY_FIELDS)) _LogEntryTuple.__new__.__defaults__ = tuple( default for _, default in _LOG_ENTRY_FIELDS) _LOG_ENTRY_PARAM_DOCSTRING = """\ :type log_name: str :param log_name: the name of the logger used to post the entry. :type labels: dict :param labels: (optional) mapping of labels for the entry :type insert_id: text :param insert_id: (optional) the ID used to identify an entry uniquely. :type severity: str :param severity: (optional) severity of event being logged. :type http_request: dict :param http_request: (optional) info about HTTP request associated with the entry. :type timestamp: :class:`datetime.datetime` :param timestamp: (optional) timestamp for the entry :type resource: :class:`~google.cloud.logging.resource.Resource` :param resource: (Optional) Monitored resource of the entry :type trace: str :param trace: (optional) traceid to apply to the entry. :type span_id: str :param span_id: (optional) span_id within the trace for the log entry. Specify the trace parameter if span_id is set. :type trace_sampled: bool :param trace_sampled: (optional) the sampling decision of the trace associated with the log entry. :type source_location: dict :param source_location: (optional) location in source code from which the entry was emitted. :type operation: dict :param operation: (optional) additional information about a potentially long-running operation associated with the log entry. :type logger: :class:`google.cloud.logging.logger.Logger` :param logger: the logger used to write the entry. """ _LOG_ENTRY_SEE_ALSO_DOCSTRING = """\ See: https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry """ class LogEntry(_LogEntryTuple): __doc__ = """ Log entry. """ + _LOG_ENTRY_PARAM_DOCSTRING + _LOG_ENTRY_SEE_ALSO_DOCSTRING received_timestamp = None @classmethod def _extract_payload(cls, resource): """Helper for :meth:`from_api_repr`""" return None @classmethod def from_api_repr(cls, resource, client, loggers=None): """Factory: construct an entry given its API representation :type resource: dict :param resource: text entry resource representation returned from the API :type client: :class:`google.cloud.logging.client.Client` :param client: Client which holds credentials and project configuration. :type loggers: dict :param loggers: (Optional) A mapping of logger fullnames -> loggers. If not passed, the entry will have a newly-created logger. :rtype: :class:`google.cloud.logging.entries.LogEntry` :returns: Log entry parsed from ``resource``. """ if loggers is None: loggers = {} logger_fullname = resource['logName'] logger = loggers.get(logger_fullname) if logger is None: logger_name = logger_name_from_path(logger_fullname) logger = loggers[logger_fullname] = client.logger(logger_name) payload = cls._extract_payload(resource) insert_id = resource.get('insertId') timestamp = resource.get('timestamp') if timestamp is not None: timestamp = _rfc3339_nanos_to_datetime(timestamp) labels = resource.get('labels') severity = resource.get('severity') http_request = resource.get('httpRequest') trace = resource.get('trace') span_id = resource.get('spanId') trace_sampled = resource.get('traceSampled') source_location = resource.get('sourceLocation') if source_location is not None: line = source_location.pop('line', None) source_location['line'] = _int_or_none(line) operation = resource.get('operation') monitored_resource_dict = resource.get('resource') monitored_resource = None if monitored_resource_dict is not None: monitored_resource = Resource._from_dict(monitored_resource_dict) inst = cls( log_name=logger_fullname, insert_id=insert_id, timestamp=timestamp, labels=labels, severity=severity, http_request=http_request, resource=monitored_resource, trace=trace, span_id=span_id, trace_sampled=trace_sampled, source_location=source_location, operation=operation, logger=logger, payload=payload, ) received = resource.get('receiveTimestamp') if received is not None: inst.received_timestamp = _rfc3339_nanos_to_datetime(received) return inst def to_api_repr(self): """API repr (JSON format) for entry. """ info = {} if self.log_name is not None: info['logName'] = self.log_name if self.resource is not None: info['resource'] = self.resource._to_dict() if self.labels is not None: info['labels'] = self.labels if self.insert_id is not None: info['insertId'] = self.insert_id if self.severity is not None: info['severity'] = self.severity if self.http_request is not None: info['httpRequest'] = self.http_request if self.timestamp is not None: info['timestamp'] = _datetime_to_rfc3339(self.timestamp) if self.trace is not None: info['trace'] = self.trace if self.span_id is not None: info['spanId'] = self.span_id if self.trace_sampled is not None: info['traceSampled'] = self.trace_sampled if self.source_location is not None: source_location = self.source_location.copy() source_location['line'] = str(source_location.pop('line', 0)) info['sourceLocation'] = source_location if self.operation is not None: info['operation'] = self.operation return info class TextEntry(LogEntry): __doc__ = """ Log entry with text payload. """ + _LOG_ENTRY_PARAM_DOCSTRING + """ :type payload: str | unicode :param payload: payload for the log entry. """ + _LOG_ENTRY_SEE_ALSO_DOCSTRING @classmethod def _extract_payload(cls, resource): """Helper for :meth:`from_api_repr`""" return resource['textPayload'] def to_api_repr(self): """API repr (JSON format) for entry. """ info = super(TextEntry, self).to_api_repr() info['textPayload'] = self.payload return info class StructEntry(LogEntry): __doc__ = """ Log entry with JSON payload. """ + _LOG_ENTRY_PARAM_DOCSTRING + """ :type payload: dict :param payload: payload for the log entry. """ + _LOG_ENTRY_SEE_ALSO_DOCSTRING @classmethod def _extract_payload(cls, resource): """Helper for :meth:`from_api_repr`""" return resource['jsonPayload'] def to_api_repr(self): """API repr (JSON format) for entry. """ info = super(StructEntry, self).to_api_repr() info['jsonPayload'] = self.payload return info class ProtobufEntry(LogEntry): __doc__ = """ Log entry with protobuf message payload. """ + _LOG_ENTRY_PARAM_DOCSTRING + """ :type payload: protobuf message :param payload: payload for the log entry. """ + _LOG_ENTRY_SEE_ALSO_DOCSTRING @classmethod def _extract_payload(cls, resource): """Helper for :meth:`from_api_repr`""" return resource['protoPayload'] @property def payload_pb(self): if isinstance(self.payload, Any): return self.payload @property def payload_json(self): if not isinstance(self.payload, Any): return self.payload def to_api_repr(self): """API repr (JSON format) for entry. """ info = super(ProtobufEntry, self).to_api_repr() info['protoPayload'] = MessageToDict(self.payload) return info def parse_message(self, message): """Parse payload into a protobuf message. Mutates the passed-in ``message`` in place. :type message: Protobuf message :param message: the message to be logged """ # NOTE: This assumes that ``payload`` is already a deserialized # ``Any`` field and ``message`` has come from an imported # ``pb2`` module with the relevant protobuf message type. Parse(json.dumps(self.payload), message)
jonparrott/google-cloud-python
logging/google/cloud/logging/entries.py
Python
apache-2.0
11,279
/* * //****************************************************************** * // * // Copyright 2016 Samsung Electronics All Rights Reserved. * // * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= * // * // Licensed under the Apache License, Version 2.0 (the "License"); * // you may not use this file except in compliance with the License. * // You may obtain a copy of the License at * // * // http://www.apache.org/licenses/LICENSE-2.0 * // * // Unless required by applicable law or agreed to in writing, software * // distributed under the License is distributed on an "AS IS" BASIS, * // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * // See the License for the specific language governing permissions and * // limitations under the License. * // * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= */ package org.iotivity.cloud.base.protocols.coap; import java.util.List; import org.iotivity.cloud.base.exception.ServerException; import org.iotivity.cloud.base.protocols.MessageBuilder; import org.iotivity.cloud.base.protocols.enums.ResponseStatus; import org.iotivity.cloud.util.Log; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.ByteToMessageDecoder; public class CoapDecoder extends ByteToMessageDecoder { private enum ParsingState { SHIM_HEADER, OPTION_PAYLOAD_LENGTH, CODE_TOKEN_OPTION, PAYLOAD, FINISH } private ParsingState nextState = ParsingState.SHIM_HEADER; private int bufferToRead = 1; private int tokenLength = 0; private int optionPayloadLength = 0; private CoapMessage partialMsg = null; private int websocketLength = -1; @Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) { try { // TODO: need exceptional case handling while (in.isReadable(bufferToRead)) { switch (nextState) { case SHIM_HEADER: int shimHeader = in.readByte(); bufferToRead = (shimHeader >>> 4) & 0x0F; tokenLength = (shimHeader) & 0x0F; switch (bufferToRead) { case 13: bufferToRead = 1; nextState = ParsingState.OPTION_PAYLOAD_LENGTH; break; case 14: bufferToRead = 2; nextState = ParsingState.OPTION_PAYLOAD_LENGTH; break; case 15: bufferToRead = 4; nextState = ParsingState.OPTION_PAYLOAD_LENGTH; break; default: optionPayloadLength = bufferToRead; bufferToRead += 1 + tokenLength; // code + tkl nextState = ParsingState.CODE_TOKEN_OPTION; break; } break; case OPTION_PAYLOAD_LENGTH: switch (bufferToRead) { case 1: optionPayloadLength = 13 + (in.readByte() & 0xFF); break; case 2: optionPayloadLength = 269 + (((in.readByte() & 0xFF) << 8) + (in.readByte() & 0xFF)); break; case 4: optionPayloadLength = 65805 + (((in.readByte() & 0xFF) << 24) + ((in.readByte() & 0xFF) << 16) + ((in.readByte() & 0xFF) << 8) + (in.readByte() & 0xFF)); break; } nextState = ParsingState.CODE_TOKEN_OPTION; bufferToRead = 1 + tokenLength + optionPayloadLength; // code // + // tkl break; case CODE_TOKEN_OPTION: int code = in.readByte() & 0xFF; if (code <= 31) { partialMsg = new CoapRequest(code); } else if (code > 224) { partialMsg = new CoapSignaling(code); } else { partialMsg = new CoapResponse(code); } if (tokenLength > 0) { byte[] token = new byte[tokenLength]; in.readBytes(token); partialMsg.setToken(token); } if (websocketLength != -1) { optionPayloadLength = websocketLength - (bufferToRead + 1); // shimheader + code + // tokenLength } if (optionPayloadLength > 0) { int optionLen = parseOptions(partialMsg, in, optionPayloadLength); if (optionPayloadLength > optionLen) { nextState = ParsingState.PAYLOAD; bufferToRead = optionPayloadLength - optionLen; continue; } } nextState = ParsingState.FINISH; bufferToRead = 0; break; case PAYLOAD: byte[] payload = new byte[bufferToRead]; in.readBytes(payload); partialMsg.setPayload(payload); nextState = ParsingState.FINISH; bufferToRead = 0; break; case FINISH: nextState = ParsingState.SHIM_HEADER; bufferToRead = 1; out.add(partialMsg); break; default: break; } } in.discardReadBytes(); } catch (Throwable t) { ResponseStatus responseStatus = t instanceof ServerException ? ((ServerException) t).getErrorResponse() : ResponseStatus.INTERNAL_SERVER_ERROR; Log.f(ctx.channel(), t); ctx.writeAndFlush( MessageBuilder.createResponse(partialMsg, responseStatus)); ctx.close(); } } public void decode(ByteBuf in, List<Object> out, int length) throws Exception { websocketLength = length; decode(null, in, out); } private int parseOptions(CoapMessage coapMessage, ByteBuf byteBuf, int maxLength) { int preOptionNum = 0; int startPos = byteBuf.readerIndex(); int firstByte = byteBuf.readByte() & 0xFF; while (firstByte != 0xFF && maxLength > 0) { int optionDelta = (firstByte & 0xF0) >>> 4; int optionLength = firstByte & 0x0F; if (optionDelta == 13) { optionDelta = 13 + byteBuf.readByte() & 0xFF; } else if (optionDelta == 14) { optionDelta = 269 + ((byteBuf.readByte() & 0xFF) << 8) + (byteBuf.readByte() & 0xFF); } if (optionLength == 13) { optionLength = 13 + byteBuf.readByte() & 0xFF; } else if (optionLength == 14) { optionLength = 269 + ((byteBuf.readByte() & 0xFF) << 8) + (byteBuf.readByte() & 0xFF); } int curOptionNum = preOptionNum + optionDelta; byte[] optionValue = new byte[optionLength]; byteBuf.readBytes(optionValue); coapMessage.addOption(curOptionNum, optionValue); preOptionNum = curOptionNum; if (maxLength > byteBuf.readerIndex() - startPos) { firstByte = byteBuf.readByte() & 0xFF; } else { break; } } // return option length return byteBuf.readerIndex() - startPos; } }
JunhwanPark/TizenRT
external/iotivity/iotivity_1.3-rel/cloud/stack/src/main/java/org/iotivity/cloud/base/protocols/coap/CoapDecoder.java
Java
apache-2.0
9,113
/* * Copyright (c) 2009-2012 jMonkeyEngine * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of 'jMonkeyEngine' nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.jme3.shader.plugins; import com.jme3.asset.AssetInfo; import com.jme3.asset.AssetKey; import com.jme3.asset.AssetLoadException; import com.jme3.asset.AssetLoader; import com.jme3.asset.AssetManager; import com.jme3.asset.cache.AssetCache; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; import java.util.*; /** * GLSL File parser that supports #import pre-processor statement */ public class GLSLLoader implements AssetLoader { private AssetManager assetManager; private Map<String, ShaderDependencyNode> dependCache = new HashMap<String, ShaderDependencyNode>(); /** * Used to load {@link ShaderDependencyNode}s. * Asset caching is disabled. */ private class ShaderDependencyKey extends AssetKey<Reader> { public ShaderDependencyKey(String name) { super(name); } @Override public Class<? extends AssetCache> getCacheType() { // Disallow caching here return null; } } /** * Creates a {@link ShaderDependencyNode} from a stream representing shader code. * * @param in The input stream containing shader code * @param nodeName * @return * @throws IOException */ private ShaderDependencyNode loadNode(Reader reader, String nodeName) { ShaderDependencyNode node = new ShaderDependencyNode(nodeName); StringBuilder sb = new StringBuilder(); StringBuilder sbExt = new StringBuilder(); BufferedReader bufReader = null; try { bufReader = new BufferedReader(reader); String ln; if (!nodeName.equals("[main]")) { sb.append("// -- begin import ").append(nodeName).append(" --\n"); } while ((ln = bufReader.readLine()) != null) { if (ln.trim().startsWith("#import ")) { ln = ln.trim().substring(8).trim(); if (ln.startsWith("\"") && ln.endsWith("\"") && ln.length() > 3) { // import user code // remove quotes to get filename ln = ln.substring(1, ln.length() - 1); if (ln.equals(nodeName)) { throw new IOException("Node depends on itself."); } // check cache first ShaderDependencyNode dependNode = dependCache.get(ln); if (dependNode == null) { Reader dependNodeReader = assetManager.loadAsset(new ShaderDependencyKey(ln)); dependNode = loadNode(dependNodeReader, ln); } node.addDependency(sb.length(), dependNode); } } else if (ln.trim().startsWith("#extension ")) { sbExt.append(ln).append('\n'); } else { sb.append(ln).append('\n'); } } if (!nodeName.equals("[main]")) { sb.append("// -- end import ").append(nodeName).append(" --\n"); } } catch (IOException ex) { if (bufReader != null) { try { bufReader.close(); } catch (IOException ex1) { } } throw new AssetLoadException("Failed to load shader node: " + nodeName, ex); } node.setSource(sb.toString()); node.setExtensions(sbExt.toString()); dependCache.put(nodeName, node); return node; } private ShaderDependencyNode nextIndependentNode() throws IOException { Collection<ShaderDependencyNode> allNodes = dependCache.values(); if (allNodes == null || allNodes.isEmpty()) { return null; } for (ShaderDependencyNode node : allNodes) { if (node.getDependOnMe().isEmpty()) { return node; } } // Circular dependency found.. for (ShaderDependencyNode node : allNodes){ System.out.println(node.getName()); } throw new IOException("Circular dependency."); } private String resolveDependencies(ShaderDependencyNode node, Set<ShaderDependencyNode> alreadyInjectedSet, StringBuilder extensions) { if (alreadyInjectedSet.contains(node)) { return "// " + node.getName() + " was already injected at the top.\n"; } else { alreadyInjectedSet.add(node); } if (!node.getExtensions().isEmpty()) { extensions.append(node.getExtensions()); } if (node.getDependencies().isEmpty()) { return node.getSource(); } else { StringBuilder sb = new StringBuilder(node.getSource()); List<String> resolvedShaderNodes = new ArrayList<String>(); for (ShaderDependencyNode dependencyNode : node.getDependencies()) { resolvedShaderNodes.add(resolveDependencies(dependencyNode, alreadyInjectedSet, extensions)); } List<Integer> injectIndices = node.getDependencyInjectIndices(); for (int i = resolvedShaderNodes.size() - 1; i >= 0; i--) { // Must insert them backwards .. sb.insert(injectIndices.get(i), resolvedShaderNodes.get(i)); } return sb.toString(); } } public Object load(AssetInfo info) throws IOException { // The input stream provided is for the vertex shader, // to retrieve the fragment shader, use the content manager this.assetManager = info.getManager(); Reader reader = new InputStreamReader(info.openStream()); if (info.getKey().getExtension().equals("glsllib")) { // NOTE: Loopback, GLSLLIB is loaded by this loader // and needs data as InputStream return reader; } else { ShaderDependencyNode rootNode = loadNode(reader, "[main]"); StringBuilder extensions = new StringBuilder(); String code = resolveDependencies(rootNode, new HashSet<ShaderDependencyNode>(), extensions); extensions.append(code); dependCache.clear(); return extensions.toString(); } } }
PlanetWaves/clockworkengine
trunk/jme3-core/src/plugins/java/com/jme3/shader/plugins/GLSLLoader.java
Java
apache-2.0
8,037
# Copyright 2014 NeuroData (http://neurodata.io) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import argparse import glob import subprocess import pdb """ This is a script to convert jp2 to png for Mitra's Data. \ We use Kakadu software for this script. Kakadu only runs on Ubuntu \ and has to have the library added to shared path. """ def main(): parser = argparse.ArgumentParser(description='Convert JP2 to PNG') parser.add_argument('path', action="store", help='Directory with JP2 Files') parser.add_argument('location', action="store", help='Directory to write to') result = parser.parse_args() # Reading all the jp2 files in that directory filelist = glob.glob(result.path+'*.jp2') for name in filelist: print "Opening: {}".format( name ) # Identifying the subdirectory to place the data under if name.find('F') != -1: subfile = 'F/' elif name.find('IHC') != -1: subfile = 'IHC/' elif name.find('N') != -1: subfile = 'N/' # Determine the write location of the file. This was /mnt on datascopes writelocation = result.location+subfile+name.split(result.path)[1].split('_')[3].split('.')[0] # Call kakadu expand from the command line, specify the input and the output filenames subprocess.call( [ './kdu_expand' ,'-i', '{}'.format(name), '-o', '{}.tiff'.format(writelocation) ] ) if __name__ == "__main__": main()
neurodata/ndstore
scripts/ingest/mitra/jp2kakadu.py
Python
apache-2.0
1,931
/* * Copyright 2015 Edward Capriolo * * 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.teknek.nibiru.partitioner; import io.teknek.nibiru.Token; public interface Partitioner { public Token partition(String in); }
tonellotto/nibiru
src/main/java/io/teknek/nibiru/partitioner/Partitioner.java
Java
apache-2.0
737
/* * 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.util; import org.junit.Test; import java.util.concurrent.CountDownLatch; import org.junit.Assert; import org.apache.activemq.artemis.api.core.SimpleString; import org.apache.activemq.artemis.utils.DataConstants; public class SimpleStringTest extends Assert { /** * Converting back and forth between char and byte requires care as char is unsigned. * @see SimpleString#getChars(int, int, char[], int) * @see SimpleString#charAt(int) * @see SimpleString#split(char) * @see SimpleString#concat(char) */ @Test public void testGetChar() { SimpleString p1 = new SimpleString("foo"); SimpleString p2 = new SimpleString("bar"); for (int i = 0; i < 1 << 16; i++) { String msg = "expecting " + i; char c = (char)i; SimpleString s = new SimpleString(String.valueOf(c)); // test getChars(...) char[] c1 = new char[1]; s.getChars(0, 1, c1, 0); assertEquals(msg, c, c1[0]); // test charAt(int) assertEquals(msg, c, s.charAt(0)); // test concat(char) SimpleString s2 = s.concat(c); assertEquals(msg, c, s2.charAt(1)); // test splitting with chars SimpleString sSplit = new SimpleString("foo" + String.valueOf(c) + "bar"); SimpleString[] chunks = sSplit.split(c); SimpleString[] split1 = p1.split(c); SimpleString[] split2 = p2.split(c); assertEquals(split1.length + split2.length, chunks.length); int j = 0; for (SimpleString iS : split1) { assertEquals(iS.toString(), iS, chunks[j++]); } for (SimpleString iS : split2) { assertEquals(iS.toString(), iS, chunks[j++]); } } } @Test public void testString() throws Exception { final String str = "hello123ABC__524`16254`6125!%^$!%$!%$!%$!%!$%!$$!\uA324"; SimpleString s = new SimpleString(str); Assert.assertEquals(str, s.toString()); Assert.assertEquals(2 * str.length(), s.getData().length); byte[] data = s.getData(); SimpleString s2 = new SimpleString(data); Assert.assertEquals(str, s2.toString()); } @Test public void testStartsWith() throws Exception { SimpleString s1 = new SimpleString("abcdefghi"); Assert.assertTrue(s1.startsWith(new SimpleString("abc"))); Assert.assertTrue(s1.startsWith(new SimpleString("abcdef"))); Assert.assertTrue(s1.startsWith(new SimpleString("abcdefghi"))); Assert.assertFalse(s1.startsWith(new SimpleString("abcdefghijklmn"))); Assert.assertFalse(s1.startsWith(new SimpleString("aardvark"))); Assert.assertFalse(s1.startsWith(new SimpleString("z"))); } @Test public void testCharSequence() throws Exception { String s = "abcdefghijkl"; SimpleString s1 = new SimpleString(s); Assert.assertEquals('a', s1.charAt(0)); Assert.assertEquals('b', s1.charAt(1)); Assert.assertEquals('c', s1.charAt(2)); Assert.assertEquals('k', s1.charAt(10)); Assert.assertEquals('l', s1.charAt(11)); try { s1.charAt(-1); Assert.fail("Should throw exception"); } catch (IndexOutOfBoundsException e) { // OK } try { s1.charAt(-2); Assert.fail("Should throw exception"); } catch (IndexOutOfBoundsException e) { // OK } try { s1.charAt(s.length()); Assert.fail("Should throw exception"); } catch (IndexOutOfBoundsException e) { // OK } try { s1.charAt(s.length() + 1); Assert.fail("Should throw exception"); } catch (IndexOutOfBoundsException e) { // OK } Assert.assertEquals(s.length(), s1.length()); CharSequence ss = s1.subSequence(0, s1.length()); Assert.assertEquals(ss, s1); ss = s1.subSequence(1, 4); Assert.assertEquals(ss, new SimpleString("bcd")); ss = s1.subSequence(5, 10); Assert.assertEquals(ss, new SimpleString("fghij")); ss = s1.subSequence(5, 12); Assert.assertEquals(ss, new SimpleString("fghijkl")); try { s1.subSequence(-1, 2); Assert.fail("Should throw exception"); } catch (IndexOutOfBoundsException e) { // OK } try { s1.subSequence(-4, -2); Assert.fail("Should throw exception"); } catch (IndexOutOfBoundsException e) { // OK } try { s1.subSequence(0, s1.length() + 1); Assert.fail("Should throw exception"); } catch (IndexOutOfBoundsException e) { // OK } try { s1.subSequence(0, s1.length() + 2); Assert.fail("Should throw exception"); } catch (IndexOutOfBoundsException e) { // OK } try { s1.subSequence(5, 1); Assert.fail("Should throw exception"); } catch (IndexOutOfBoundsException e) { // OK } } @Test public void testEquals() throws Exception { Assert.assertFalse(new SimpleString("abcdef").equals(new Object())); Assert.assertFalse(new SimpleString("abcef").equals(null)); Assert.assertEquals(new SimpleString("abcdef"), new SimpleString("abcdef")); Assert.assertFalse(new SimpleString("abcdef").equals(new SimpleString("abggcdef"))); Assert.assertFalse(new SimpleString("abcdef").equals(new SimpleString("ghijkl"))); } @Test public void testHashcode() throws Exception { SimpleString str = new SimpleString("abcdef"); SimpleString sameStr = new SimpleString("abcdef"); SimpleString differentStr = new SimpleString("ghijk"); Assert.assertTrue(str.hashCode() == sameStr.hashCode()); Assert.assertFalse(str.hashCode() == differentStr.hashCode()); } @Test public void testUnicode() throws Exception { String myString = "abcdef&^*&!^ghijkl\uB5E2\uCAC7\uB2BB\uB7DD\uB7C7\uB3A3\uBCE4\uB5A5"; SimpleString s = new SimpleString(myString); byte[] data = s.getData(); s = new SimpleString(data); Assert.assertEquals(myString, s.toString()); } @Test public void testUnicodeWithSurrogates() throws Exception { String myString = "abcdef&^*&!^ghijkl\uD900\uDD00"; SimpleString s = new SimpleString(myString); byte[] data = s.getData(); s = new SimpleString(data); Assert.assertEquals(myString, s.toString()); } @Test public void testSizeofString() throws Exception { Assert.assertEquals(DataConstants.SIZE_INT, SimpleString.sizeofString(new SimpleString(""))); SimpleString str = new SimpleString(RandomUtil.randomString()); Assert.assertEquals(DataConstants.SIZE_INT + str.getData().length, SimpleString.sizeofString(str)); } @Test public void testSizeofNullableString() throws Exception { Assert.assertEquals(1, SimpleString.sizeofNullableString(null)); Assert.assertEquals(1 + DataConstants.SIZE_INT, SimpleString.sizeofNullableString(new SimpleString(""))); SimpleString str = new SimpleString(RandomUtil.randomString()); Assert.assertEquals(1 + DataConstants.SIZE_INT + str.getData().length, SimpleString.sizeofNullableString(str)); } @Test public void testSplitNoDelimeter() throws Exception { SimpleString s = new SimpleString("abcdefghi"); SimpleString[] strings = s.split('.'); Assert.assertNotNull(strings); Assert.assertEquals(strings.length, 1); Assert.assertEquals(strings[0], s); } @Test public void testSplit1Delimeter() throws Exception { SimpleString s = new SimpleString("abcd.efghi"); SimpleString[] strings = s.split('.'); Assert.assertNotNull(strings); Assert.assertEquals(strings.length, 2); Assert.assertEquals(strings[0], new SimpleString("abcd")); Assert.assertEquals(strings[1], new SimpleString("efghi")); } @Test public void testSplitmanyDelimeters() throws Exception { SimpleString s = new SimpleString("abcd.efghi.jklmn.opqrs.tuvw.xyz"); SimpleString[] strings = s.split('.'); Assert.assertNotNull(strings); Assert.assertEquals(strings.length, 6); Assert.assertEquals(strings[0], new SimpleString("abcd")); Assert.assertEquals(strings[1], new SimpleString("efghi")); Assert.assertEquals(strings[2], new SimpleString("jklmn")); Assert.assertEquals(strings[3], new SimpleString("opqrs")); Assert.assertEquals(strings[4], new SimpleString("tuvw")); Assert.assertEquals(strings[5], new SimpleString("xyz")); } @Test public void testContains() { SimpleString simpleString = new SimpleString("abcdefghijklmnopqrst"); Assert.assertFalse(simpleString.contains('.')); Assert.assertFalse(simpleString.contains('%')); Assert.assertFalse(simpleString.contains('8')); Assert.assertFalse(simpleString.contains('.')); Assert.assertTrue(simpleString.contains('a')); Assert.assertTrue(simpleString.contains('b')); Assert.assertTrue(simpleString.contains('c')); Assert.assertTrue(simpleString.contains('d')); Assert.assertTrue(simpleString.contains('e')); Assert.assertTrue(simpleString.contains('f')); Assert.assertTrue(simpleString.contains('g')); Assert.assertTrue(simpleString.contains('h')); Assert.assertTrue(simpleString.contains('i')); Assert.assertTrue(simpleString.contains('j')); Assert.assertTrue(simpleString.contains('k')); Assert.assertTrue(simpleString.contains('l')); Assert.assertTrue(simpleString.contains('m')); Assert.assertTrue(simpleString.contains('n')); Assert.assertTrue(simpleString.contains('o')); Assert.assertTrue(simpleString.contains('p')); Assert.assertTrue(simpleString.contains('q')); Assert.assertTrue(simpleString.contains('r')); Assert.assertTrue(simpleString.contains('s')); Assert.assertTrue(simpleString.contains('t')); } @Test public void testConcat() { SimpleString start = new SimpleString("abcdefg"); SimpleString middle = new SimpleString("hijklmnop"); SimpleString end = new SimpleString("qrstuvwxyz"); Assert.assertEquals(start.concat(middle).concat(end), new SimpleString("abcdefghijklmnopqrstuvwxyz")); Assert.assertEquals(start.concat('.').concat(end), new SimpleString("abcdefg.qrstuvwxyz")); // Testing concat of SimpleString with String for (int i = 0; i < 10; i++) { Assert.assertEquals(new SimpleString("abcdefg-" + i), start.concat("-" + Integer.toString(i))); } } @Test public void testMultithreadHashCode() throws Exception { for (int repeat = 0; repeat < 10; repeat++) { StringBuffer buffer = new StringBuffer(); for (int i = 0; i < 100; i++) { buffer.append("Some Big String " + i); } String strvalue = buffer.toString(); final int initialhash = new SimpleString(strvalue).hashCode(); final SimpleString value = new SimpleString(strvalue); int nThreads = 100; final CountDownLatch latch = new CountDownLatch(nThreads); final CountDownLatch start = new CountDownLatch(1); class T extends Thread { boolean failed = false; @Override public void run() { try { latch.countDown(); start.await(); int newhash = value.hashCode(); if (newhash != initialhash) { failed = true; } } catch (Exception e) { e.printStackTrace(); failed = true; } } } T[] x = new T[nThreads]; for (int i = 0; i < nThreads; i++) { x[i] = new T(); x[i].start(); } ActiveMQTestBase.waitForLatch(latch); start.countDown(); for (T t : x) { t.join(); } for (T t : x) { Assert.assertFalse(t.failed); } } } }
rogerchina/activemq-artemis
artemis-server/src/test/java/org/apache/activemq/artemis/tests/util/SimpleStringTest.java
Java
apache-2.0
13,390
package org.mybatis.generator.internal.util; import java.lang.reflect.Array; /** * This class is from javapractices.com: * * http://www.javapractices.com/Topic28.cjp * * Collected methods which allow easy implementation of <code>hashCode</code>. * * Example use case: * * <pre> * public int hashCode() { * int result = HashCodeUtil.SEED; * // collect the contributions of various fields * result = HashCodeUtil.hash(result, fPrimitive); * result = HashCodeUtil.hash(result, fObject); * result = HashCodeUtil.hash(result, fArray); * return result; * } * </pre> */ public final class HashCodeUtil { /** * An initial value for a <code>hashCode</code>, to which is added * contributions from fields. Using a non-zero value decreases collisons of * <code>hashCode</code> values. */ public static final int SEED = 23; /** * booleans. */ public static int hash(int aSeed, boolean aBoolean) { return firstTerm(aSeed) + (aBoolean ? 1 : 0); } /** * chars. */ public static int hash(int aSeed, char aChar) { return firstTerm(aSeed) + aChar; } /** * ints. */ public static int hash(int aSeed, int aInt) { /* * Implementation Note Note that byte and short are handled by this * method, through implicit conversion. */ return firstTerm(aSeed) + aInt; } /** * longs. */ public static int hash(int aSeed, long aLong) { return firstTerm(aSeed) + (int) (aLong ^ (aLong >>> 32)); } /** * floats. */ public static int hash(int aSeed, float aFloat) { return hash(aSeed, Float.floatToIntBits(aFloat)); } /** * doubles. */ public static int hash(int aSeed, double aDouble) { return hash(aSeed, Double.doubleToLongBits(aDouble)); } /** * <code>aObject</code> is a possibly-null object field, and possibly an * array. * * If <code>aObject</code> is an array, then each element may be a primitive * or a possibly-null object. */ public static int hash(int aSeed, Object aObject) { int result = aSeed; if (aObject == null) { result = hash(result, 0); } else if (!isArray(aObject)) { result = hash(result, aObject.hashCode()); } else { int length = Array.getLength(aObject); for (int idx = 0; idx < length; ++idx) { Object item = Array.get(aObject, idx); // recursive call! result = hash(result, item); } } return result; } // / PRIVATE /// private static final int fODD_PRIME_NUMBER = 37; private static int firstTerm(int aSeed) { return fODD_PRIME_NUMBER * aSeed; } private static boolean isArray(Object aObject) { return aObject.getClass().isArray(); } }
fnyexx/mybator
src/main/java/org/mybatis/generator/internal/util/HashCodeUtil.java
Java
apache-2.0
2,726
/* * Copyright 2015 JBoss Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * 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.designer.repository; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; public class RepositoryManager { private static RepositoryManager instance; private Map<String, Repository> availableRepositories = new ConcurrentHashMap<String, Repository>(); private RepositoryManager() { } public Repository getRepository(String repositoryId) { return this.availableRepositories.get(repositoryId); } public void registerRepository(String repositoryId, Repository repository) { if (this.availableRepositories.containsKey(repositoryId)) { return; } this.availableRepositories.put(repositoryId, repository); } public Repository unregisterRepository(String repositoryId) { Repository repository = this.availableRepositories.get(repositoryId); this.availableRepositories.remove(repository); return repository; } public static RepositoryManager getInstance() { if (instance == null) { instance = new RepositoryManager(); } return instance; } }
xingguang2013/jbpm-designer
jbpm-designer-backend/src/main/java/org/jbpm/designer/repository/RepositoryManager.java
Java
apache-2.0
1,682
/* Copyright (c) 2014-2015 F-Secure See LICENSE for details */ package cc.softwarefactory.lokki.android; import android.app.Application; import android.graphics.Bitmap; import android.os.StrictMode; import android.preference.PreferenceManager; import android.support.v4.util.LruCache; import android.util.Log; import com.google.android.gms.maps.GoogleMap; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import cc.softwarefactory.lokki.android.utilities.AnalyticsUtils; import cc.softwarefactory.lokki.android.utilities.PreferenceUtils; public class MainApplication extends Application { /** * Indicates whether this is a development or production build */ private static final boolean DEVELOPER_MODE = true; /** * Debug tag identifying that a log message was caused by the main application */ private static final String TAG = "MainApplication"; /** * Int array enumerating the codes used for different Google Maps map view types */ public static final int[] mapTypes = {GoogleMap.MAP_TYPE_NORMAL, GoogleMap.MAP_TYPE_SATELLITE, GoogleMap.MAP_TYPE_HYBRID}; /** * Currently selected Google Maps map view type. * TODO: make private with proper accessor methods to disallow values not in mapTypes */ public static int mapType = 0; public static String emailBeingTracked; /** * User dashboard JSON object. Format: * { * "battery":"", * "canseeme":["c429003ba3a3c508cba1460607ab7f8cd4a0d450"], * "icansee":{ * "c429003ba3a3c508cba1460607ab7f8cd4a0d450":{ * "battery":"", * "location":{}, * "visibility":true * } * }, * "idmapping":{ * "a1b2c3d4e5f6g7h8i9j10k11l12m13n14o15p16q":"test@test.com", * "c429003ba3a3c508cba1460607ab7f8cd4a0d450":"family.member@example.com" * }, * "location":{}, * "visibility":true * } */ public static JSONObject dashboard = null; public static String userAccount; // Email /** * User's contacts. Format: * { * "test.friend@example.com": { * "id":1, * "name":"Test Friend" * }, * "family.member@example.com":{ * "id":2, * "name":"Family Member" * }, * "work.buddy@example.com":{ * "id":3, * "name":"Work Buddy" * }, * "mapping":{ * "Test Friend":"test.friend@example.com", * "Family Member":"family.member@example.com", * "Work Buddy":"work.buddy@example.com" * } * } */ public static JSONObject contacts; /** * Format: * { * "Test Friend":"test.friend@example.com", * "Family Member":"family.member@example.com", * "Work Buddy":"work.buddy@example.com" * } */ public static JSONObject mapping; /** * Contacts that aren't shown on the map. Format: * { * "test.friend@example.com":1, * "family.member@example.com":1 * } */ public static JSONObject iDontWantToSee; public static Boolean visible = true; public static LruCache<String, Bitmap> avatarCache; /** * The user's places. Format: * { * "f414af16-e532-49d2-999f-c3bdd160dca4":{ * "lat":11.17839332191203, * "lon":1.4752149581909178E-5, * "rad":6207030, * "name":"1", * "img":"" * }, * "b0d77236-cdad-4a25-8cca-47b4426d5f1f":{ * "lat":11.17839332191203, * "lon":1.4752149581909178E-5, * "rad":6207030, * "name":"1", * "img":"" * }, * "1f1a3303-5964-40d5-bd07-3744a0c0d0f7":{ * "lat":11.17839332191203, * "lon":1.4752149581909178E-5, * "rad":6207030, * "name":"3", * "img":"" * } * } */ public static JSONObject places; public static boolean locationDisabledPromptShown; public static JSONArray buzzPlaces; public static boolean firstTimeZoom = true; @Override public void onCreate() { Log.d(TAG, "Lokki started component"); //Load user settings loadSetting(); AnalyticsUtils.initAnalytics(getApplicationContext()); locationDisabledPromptShown = false; final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024); // Use 1/8th of the available memory for this memory cache. final int cacheSize = maxMemory / 8; avatarCache = new LruCache<String, Bitmap>(cacheSize) { @Override protected int sizeOf(String key, Bitmap bitmap) { // The cache size will be measured in kilobytes rather than number of items. return (bitmap.getRowBytes() * bitmap.getHeight()) / 1024; } }; String iDontWantToSeeString = PreferenceUtils.getString(this, PreferenceUtils.KEY_I_DONT_WANT_TO_SEE); if (!iDontWantToSeeString.isEmpty()) { try { MainApplication.iDontWantToSee = new JSONObject(iDontWantToSeeString); } catch (JSONException e) { MainApplication.iDontWantToSee = null; Log.e(TAG, e.getMessage()); } } else { MainApplication.iDontWantToSee = new JSONObject(); } Log.d(TAG, "MainApplication.iDontWantToSee: " + MainApplication.iDontWantToSee); if (DEVELOPER_MODE) { StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder() .detectAll() .penaltyLog() .build()); StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder() .detectLeakedSqlLiteObjects() .penaltyLog() .penaltyDeath() .build()); } buzzPlaces = new JSONArray(); super.onCreate(); } private void loadSetting() { PreferenceManager.setDefaultValues(this, R.xml.preferences, false); visible = PreferenceUtils.getBoolean(getApplicationContext(), PreferenceUtils.KEY_SETTING_VISIBILITY); Log.d(TAG, "Visible: " + visible); // get mapValue from preferences try { mapType = Integer.parseInt(PreferenceUtils.getString(getApplicationContext(), PreferenceUtils.KEY_SETTING_MAP_MODE)); } catch (NumberFormatException e){ mapType = mapTypes[0]; Log.w(TAG, "Could not parse map type; using default value: " + e); } } }
Grandi/lokki-android
App/src/main/java/cc/softwarefactory/lokki/android/MainApplication.java
Java
apache-2.0
6,855
/* * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights * Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.redshift.model.transform; import org.w3c.dom.Node; import com.amazonaws.AmazonServiceException; import com.amazonaws.util.XpathUtils; import com.amazonaws.transform.StandardErrorUnmarshaller; import com.amazonaws.services.redshift.model.ClusterQuotaExceededException; public class ClusterQuotaExceededExceptionUnmarshaller extends StandardErrorUnmarshaller { public ClusterQuotaExceededExceptionUnmarshaller() { super(ClusterQuotaExceededException.class); } @Override public AmazonServiceException unmarshall(Node node) throws Exception { // Bail out if this isn't the right error code that this // marshaller understands String errorCode = parseErrorCode(node); if (errorCode == null || !errorCode.equals("ClusterQuotaExceeded")) return null; ClusterQuotaExceededException e = (ClusterQuotaExceededException) super .unmarshall(node); return e; } }
nterry/aws-sdk-java
aws-java-sdk-redshift/src/main/java/com/amazonaws/services/redshift/model/transform/ClusterQuotaExceededExceptionUnmarshaller.java
Java
apache-2.0
1,589
/* * Copyright 2016 Development Entropy (deventropy.org) Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.deventropy.junithelper.derby; import static org.junit.Assert.assertTrue; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import org.junit.AfterClass; import org.junit.Rule; import org.junit.Test; import org.junit.rules.RuleChain; import org.junit.rules.TemporaryFolder; /** * @author Bindul Bhowmik */ public class SimpleDerbyTest { private TemporaryFolder tempFolder = new TemporaryFolder(); private EmbeddedDerbyResource embeddedDerbyResource = new EmbeddedDerbyResource(DerbyResourceConfig.buildDefault() .useDevNullErrorLogging(), tempFolder); @Rule public RuleChain derbyRuleChain = RuleChain.outerRule(tempFolder).around(embeddedDerbyResource); /** * Cleanup stuff. */ @AfterClass public static void cleanupDerbySystem () { // Cleanup for next test DerbyUtils.shutdownDerbySystemQuitely(true); } @Test public void test () throws SQLException { final String jdbcUrl = embeddedDerbyResource.getJdbcUrl(); Connection connection = null; Statement stmt = null; ResultSet rs = null; try { connection = DriverManager.getConnection(jdbcUrl); // Check a value stmt = connection.createStatement(); rs = stmt.executeQuery("SELECT 1 FROM SYSIBM.SYSDUMMY1"); assertTrue(rs.next()); } finally { DerbyUtils.closeQuietly(rs); DerbyUtils.closeQuietly(stmt); DerbyUtils.closeQuietly(connection); } } }
bindul/junit-helper
junit-helper-derby/src/test/java/org/deventropy/junithelper/derby/SimpleDerbyTest.java
Java
apache-2.0
2,114
<?php /** * @author Bilal Cinarli * @link http://bcinarli.com **/ class router { private static $_routes; private static $_routeMatch = false; private static $_page; private static $_matches; private static $_role = '404'; public static $is_404 = true; public function __construct() { require_once(ABS_PATH . APP_PATH . 'settings/routes.php'); self::$_page = $routes['404']['page']; $this->setRoutes($routes); } public function setRoutes(array $routes) { if (is_array($routes)) { self::$_routes = $routes; $this->analyseRoutes(); } } public function analyseRoutes() { foreach (self::$_routes as $route) { $match = 'plain'; if (isset($route['match'])) { $match = $route['match']; } switch ($match) { case 'plain': default: $this->checkPlainRoute($route['url']); break; case 'regex': $this->checkRegexRoute($route['url']); break; } if (self::$_routeMatch === true) { self::$is_404 = false; $this->setRole($route); $this->setPage($route); break; } } } private function setPage($route) { $page = $route['page']; if (isset($route['match']) && $route['match'] == 'regex') { $matches = self::getMatches(); // loop matches and replace $1, $2 like placeholders with matched vars foreach ($matches as $key => $value) { $page = str_replace('$' . $key, $value, $page); } // if url matched, and page if is not exists, set page to 404 if (!file_exists(APP_PATH . $page)) { $page = $this->_routes[404]['page']; self::$is_404 = true; } } return self::$_page = $page; } private function setRole($route) { if (!isset($route['role'])) { self::$_role = 'role'; } else { self::$_role = $route['role']; } } private function checkPlainRoute($url) { self::$_routeMatch = false; if ($url == url::getUrl()) { self::$_routeMatch = true; } } private function checkRegexRoute($url) { self::$_routeMatch = false; if (preg_match('#' . $url . '#', url::getUrl(), $matches)) { self::$_matches = $matches; self::$_routeMatch = true; } } public static function setRoute($route) { if (array_key_exists('page', self::$_routes[$route])) { return self::$_page = self::$_routes[$route]['page']; } } public static function getRoute() { return self::$_page; } public static function getRole() { return self::$_role; } public static function getMatches($matched = null) { if ($matched == null) { return self::$_matches; } return self::$_matches[$matched]; } }
bcinarli/bcinarli.com
misto/router.php
PHP
apache-2.0
2,578
describe VmMigrateWorkflow do include Spec::Support::WorkflowHelper let(:admin) { FactoryGirl.create(:user_with_group) } let(:ems) { FactoryGirl.create(:ems_vmware) } let(:vm) { FactoryGirl.create(:vm_vmware, :name => 'My VM', :ext_management_system => ems) } context "With a Valid Template," do context "#allowed_hosts" do let(:workflow) { VmMigrateWorkflow.new({:src_ids => [vm.id]}, admin) } context "#allowed_hosts" do it "with no hosts" do stub_dialog expect(workflow.allowed_hosts).to eq([]) end it "with a host" do stub_dialog host = FactoryGirl.create(:host_vmware, :ext_management_system => ems) host.set_parent(ems) allow(workflow).to receive(:process_filter).and_return([host]) expect(workflow.allowed_hosts).to eq([workflow.ci_to_hash_struct(host)]) end end end end describe "#make_request" do let(:alt_user) { FactoryGirl.create(:user_with_group) } it "creates and update a request" do EvmSpecHelper.local_miq_server stub_dialog # if running_pre_dialog is set, it will run 'continue_request' workflow = described_class.new(values = {:running_pre_dialog => false}, admin) expect(AuditEvent).to receive(:success).with( :event => "vm_migrate_request_created", :target_class => "Vm", :userid => admin.userid, :message => "VM Migrate requested by <#{admin.userid}> for Vm:#{[vm.id].inspect}" ) # creates a request # the dialogs populate this values.merge!(:src_ids => [vm.id], :vm_tags => []) request = workflow.make_request(nil, values) expect(request).to be_valid expect(request).to be_a_kind_of(VmMigrateRequest) expect(request.request_type).to eq("vm_migrate") expect(request.description).to eq("VM Migrate for: #{vm.name} - ") expect(request.requester).to eq(admin) expect(request.userid).to eq(admin.userid) expect(request.requester_name).to eq(admin.name) expect(request.workflow).to be_a described_class # updates a request workflow = described_class.new(values, alt_user) expect(AuditEvent).to receive(:success).with( :event => "vm_migrate_request_updated", :target_class => "Vm", :userid => alt_user.userid, :message => "VM Migrate request updated by <#{alt_user.userid}> for Vm:#{[vm.id].inspect}" ) workflow.make_request(request, values) end end end
romaintb/manageiq
spec/models/vm_migrate_workflow_spec.rb
Ruby
apache-2.0
2,579
/* * Copyright 2016 e-UCM (http://www.e-ucm.es/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * This project has received funding from the European Union’s Horizon * 2020 research and innovation programme under grant agreement No 644187. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 (link is external) * * 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. */ 'use strict'; // Declare app level module which depends on filters, and services angular.module('myApp', [ 'ngRoute', 'toolbarApp', 'signupApp', 'loginApp', 'loginPluginApp', 'classApp', 'participantsApp', 'classesApp', 'activitiesApp', 'activityApp', 'gameApp', 'analysisApp', 'kibanaApp', 'gamesApp', 'activityApp', 'analyticsApp', 'devVisualizatorApp', 'services', 'xeditable', 'env-vars', 'ui.router', 'blockUI' ]).run(function (editableOptions, $localStorage, $cookies) { editableOptions.theme = 'bs3'; if ($localStorage.user) { $cookies.put('rageUserCookie', $localStorage.user.token, { path: '/' }); } }).filter('prettyDateId', function () { return function (_id) { if (_id) { return $.format.prettyDate(new Date(parseInt(_id.slice(0, 8), 16) * 1000)); } }; }).filter('prettyDate', function () { return function (date) { if (date) { return $.format.prettyDate(new Date(date)); } }; }).filter('list', function () { return function (list) { if (!list || list.length === 0) { return 'Empty list'; } var result = ''; list.forEach(function (v) { result += v + ', '; }); return result; }; }).filter('object2array', function () { return function (input) { var out = []; for (var i in input) { out.push(input[i]); } return out; }; }).factory('httpRequestInterceptor', ['$localStorage', function ($localStorage) { return { request: function (config) { config.headers.Accept = 'application/json'; if ($localStorage.user) { config.headers.Authorization = 'Bearer ' + $localStorage.user.token; } return config; } }; } ]).config(['$routeProvider', '$httpProvider', '$locationProvider', '$stateProvider', 'blockUIConfig', function ($routeProvider, $httpProvider, $locationProvider, $stateProvider, blockUIConfig) { $httpProvider.interceptors.push('httpRequestInterceptor'); $locationProvider.html5Mode({enabled: true, requireBase: false}); $stateProvider.state({ name: 'default', url: '/', templateUrl: 'view/home' }); $stateProvider.state({ name: 'home', url: '/home', templateUrl: 'view/home' }); $stateProvider.state({ name: 'login', url: '/login', templateUrl: 'view/login' }); $stateProvider.state({ name: 'signup', url: '/signup', templateUrl: 'view/signup' }); $stateProvider.state({ name: 'class', url: '/class', templateUrl: 'view/classactivity' }); $stateProvider.state({ name: 'data', url: '/data', templateUrl: 'view/data' }); $stateProvider.state({ name: 'game', url: '/game', templateUrl: 'view/gameactivity' }); blockUIConfig.autoBlock = false; blockUIConfig.message = 'Please wait...'; } ]).controller('AppCtrl', ['$rootScope', '$scope', '$location', '$http', '$timeout', '$localStorage', '$window', 'Games', 'Classes', 'Activities', 'Versions', 'Analysis', 'Role', 'CONSTANTS', 'QueryParams', function ($rootScope, $scope, $location, $http, $timeout, $localStorage, $window, Games, Classes, Activities, Versions, Analysis, Role, CONSTANTS, QueryParams) { $scope.$storage = $localStorage; $scope.DOCS = CONSTANTS.DOCS; // Role determination $scope.isUser = function () { return Role.isUser(); }; $scope.isAdmin = function () { return Role.isAdmin(); }; $scope.isStudent = function () { return Role.isStudent(); }; $scope.isTeacher = function () { return Role.isTeacher(); }; $scope.isOfflineActivity = function () { return $scope.isOfflineActivityParam($scope.selectedActivity); }; $scope.isOnlineActivity = function () { return $scope.isOnlineActivityParam($scope.selectedActivity); }; $scope.isOfflineActivityParam = function (activity) { return activity && activity.offline; }; $scope.isOnlineActivityParam = function (activity) { return activity && !activity.offline; }; $scope.isDeveloper = function () { return Role.isDeveloper(); }; $scope.goToClass = function(c) { $scope.$emit('selectClass', { class: c}); }; $scope.goToGame = function(game) { $scope.$emit('selectGame', { game: game}); }; $scope.goToActivity = function(activity) { $scope.$emit('selectActivity', { activity: activity}); }; var checkLogin = function() { $scope.username = $scope.isUser() ? $scope.$storage.user.username : ''; }; checkLogin(); $scope.$on('login', checkLogin); $scope.href = function (href) { $window.location.href = href; }; $scope.logout = function () { $http.delete(CONSTANTS.APIPATH + '/logout').success(function () { delete $scope.$storage.user; $timeout(function () { $location.url('login'); }, 50); }).error(function (data, status) { delete $scope.$storage.user; console.error('Error on get /logout ' + JSON.stringify(data) + ', status: ' + status); }); }; $scope.testIndex = 'default'; $scope.statementSubmitted = false; $scope.submitStatementsFile = function () { $scope.loadingDashboard = true; $scope.statementsFile.contents = JSON.parse($scope.statementsFile.contents); if ($scope.statementsFile.contents) { $http.post(CONSTANTS.PROXY + '/activities/test/' + $scope.selectedGame._id, $scope.statementsFile.contents) .success(function (data) { $scope.testIndex = data.id; $scope.statementSubmitted = true; $scope.generateTestVisualization(); $scope.loadingDashboard = false; }).error(function (data, status) { $scope.statementSubmitted = true; $scope.generateTestVisualization(); console.error('Error on post /activities/test/' + $scope.selectedGame._id + ' ' + JSON.stringify(data) + ', status: ' + status); $scope.loadingDashboard = false; }); } }; if (!$scope.selectedConfigView) { $scope.selectedConfigView = 'stormAnalysis'; } $scope.getActiveClass = function (id) { if (id === $scope.selectedConfigView) { return 'active'; } return null; }; $scope.templateButtonMsg = function (opened) { if (opened) { return 'Hide default JSON'; } return 'Show JSON'; }; $scope.$on('selectGame', function (event, params) { if (params.game) { $scope.selectedGame = params.game; Versions.forGame({gameId: params.game._id}).$promise.then(function(versions) { $scope.selectedVersion = versions[0]; if (Role.isDeveloper()) { $location.url('data'); } else { $location.url('game'); } $location.search('game', params.game._id); $location.search('version', $scope.selectedVersion._id); }); } }); $scope.$on('selectClass', function (event, params) { if (params.class) { $scope.selectedClass = params.class; $location.url('class'); $location.search('class', params.class._id); } }); $scope.$on('selectActivity', function (event, params) { if (params.activity) { $scope.selectedActivity = params.activity; $scope.selectedClass = Classes.get({classId: params.activity.classId}); $scope.selectedVersion = Versions.get({gameId: gameId, versionId: params.activity.versionId}); $scope.selectedGame = Games.get({gameId: params.activity.gameId}); $location.url('data'); $location.search('activity', params.activity._id); } }); $scope.developer = { name: '' }; // Load if ($scope.isUser()) { var gameId = QueryParams.getQueryParam('game'); if (gameId) { $scope.selectedGame = Games.get({gameId: gameId}); } var versionId = QueryParams.getQueryParam('version'); if (gameId && versionId) { $scope.selectedVersion = Versions.get({gameId: gameId, versionId: versionId}); } var classId = QueryParams.getQueryParam('class'); if (classId) { $scope.selectedClass = Classes.get({classId: classId}); } var activityId = QueryParams.getQueryParam('activity'); if (activityId) { Activities.get({activityId: activityId}).$promise.then(function(activity) { $scope.selectedActivity = activity; $scope.selectedClass = Classes.get({classId: activity.classId}); $scope.selectedVersion = Versions.get({gameId: gameId, versionId: activity.versionId}); $scope.selectedGame = Games.get({gameId: activity.gameId}); }); } } else if (!$window.location.pathname.endsWith('loginbyplugin')) { $location.url('login'); } } ]);
gorco/gf
app/public/js/controllers/app.js
JavaScript
apache-2.0
11,160
//----------------------------------------------------------------------- // <copyright file="Eventsourced.cs" company="Akka.NET Project"> // Copyright (C) 2009-2016 Typesafe Inc. <http://www.typesafe.com> // Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Linq; using Akka.Actor; using Akka.Event; using Akka.Util.Internal; namespace Akka.Persistence { public interface IPendingHandlerInvocation { object Event { get; } Action<object> Handler { get; } } /// <summary> /// Forces actor to stash incoming commands until all invocations are handled. /// </summary> public sealed class StashingHandlerInvocation : IPendingHandlerInvocation { public StashingHandlerInvocation(object evt, Action<object> handler) { Event = evt; Handler = handler; } public object Event { get; private set; } public Action<object> Handler { get; private set; } } /// <summary> /// Unlike <see cref="StashingHandlerInvocation"/> this one does not force actor to stash commands. /// Originates from <see cref="Eventsourced.PersistAsync{TEvent}(TEvent,System.Action{TEvent})"/> /// or <see cref="Eventsourced.Defer{TEvent}(TEvent,System.Action{TEvent})"/> method calls. /// </summary> public sealed class AsyncHandlerInvocation : IPendingHandlerInvocation { public AsyncHandlerInvocation(object evt, Action<object> handler) { Event = evt; Handler = handler; } public object Event { get; private set; } public Action<object> Handler { get; private set; } } public abstract partial class Eventsourced : ActorBase, IPersistentIdentity, IWithUnboundedStash { private static readonly AtomicCounter InstanceCounter = new AtomicCounter(1); private readonly int _instanceId; private readonly IStash _internalStash; private IActorRef _snapshotStore; private IActorRef _journal; private ICollection<IPersistentEnvelope> _journalBatch = new List<IPersistentEnvelope>(); private readonly int _maxMessageBatchSize; private bool _isWriteInProgress = false; private long _sequenceNr = 0L; private EventsourcedState _currentState; private LinkedList<IPersistentEnvelope> _eventBatch = new LinkedList<IPersistentEnvelope>(); /// Used instead of iterating `pendingInvocations` in order to check if safe to revert to processing commands private long _pendingStashingPersistInvocations = 0L; /// Holds user-supplied callbacks for persist/persistAsync calls private LinkedList<IPendingHandlerInvocation> _pendingInvocations = new LinkedList<IPendingHandlerInvocation>(); protected readonly PersistenceExtension Extension; private readonly ILoggingAdapter _log; protected Eventsourced() { LastSequenceNr = 0L; Extension = Persistence.Instance.Apply(Context.System); _instanceId = InstanceCounter.GetAndIncrement(); _maxMessageBatchSize = Extension.Settings.Journal.MaxMessageBatchSize; _currentState = RecoveryPending(); _internalStash = CreateStash(); _log = Context.GetLogger(); } protected virtual ILoggingAdapter Log { get { return _log; } } /// <summary> /// Id of the persistent entity for which messages should be replayed. /// </summary> public abstract string PersistenceId { get; } public IStash Stash { get; set; } public string JournalPluginId { get; protected set; } public string SnapshotPluginId { get; protected set; } public IActorRef Journal { get { return _journal ?? (_journal = Extension.JournalFor(JournalPluginId)); } } public IActorRef SnapshotStore { get { return _snapshotStore ?? (_snapshotStore = Extension.SnapshotStoreFor(SnapshotPluginId)); } } /// <summary> /// Returns <see cref="PersistenceId"/>. /// </summary> public string SnapshotterId { get { return PersistenceId; } } /// <summary> /// Returns true if this persistent entity is currently recovering. /// </summary> public bool IsRecovering { get { return _currentState.IsRecoveryRunning; } } /// <summary> /// Returns true if this persistent entity has successfully finished recovery. /// </summary> public bool IsRecoveryFinished { get { return !IsRecovering; } } /// <summary> /// Highest received sequence number so far or `0L` if this actor /// hasn't replayed or stored any persistent events yet. /// </summary> public long LastSequenceNr { get; private set; } /// <summary> /// Returns <see cref="LastSequenceNr"/> /// </summary> public long SnapshotSequenceNr { get { return LastSequenceNr; } } public void LoadSnapshot(string persistenceId, SnapshotSelectionCriteria criteria, long toSequenceNr) { SnapshotStore.Tell(new LoadSnapshot(persistenceId, criteria, toSequenceNr)); } public void SaveSnapshot(object snapshot) { SnapshotStore.Tell(new SaveSnapshot(new SnapshotMetadata(SnapshotterId, SnapshotSequenceNr), snapshot)); } public void DeleteSnapshot(long sequenceNr, DateTime timestamp) { SnapshotStore.Tell(new DeleteSnapshot(new SnapshotMetadata(SnapshotterId, sequenceNr, timestamp))); } public void DeleteSnapshots(SnapshotSelectionCriteria criteria) { SnapshotStore.Tell(new DeleteSnapshots(SnapshotterId, criteria)); } /// <summary> /// Recovery handler that receives persistent events during recovery. If a state snapshot has been captured and saved, /// this handler will receive a <see cref="SnapshotOffer"/> message followed by events that are younger than offer itself. /// /// This handler must be a pure function (no side effects allowed), it should not perform any actions that may fail. /// If recovery fails this actor will be stopped. This can be customized in <see cref="RecoveryFailure"/>. /// </summary> protected abstract bool ReceiveRecover(object message); /// <summary> /// Command handler. Typically validates commands against current state - possibly by communicating with other actors. /// On successful validation, one or more events are derived from command and persisted. /// </summary> /// <param name="message"></param> /// <returns></returns> protected abstract bool ReceiveCommand(object message); /// <summary> /// Asynchronously persists an <paramref name="event"/>. On successful persistence, the <paramref name="handler"/> /// is called with the persisted event. This method guarantees that no new commands will be received by a persistent actor /// between a call to <see cref="Persist{TEvent}(TEvent,System.Action{TEvent})"/> and execution of it's handler. It also /// holds multiple persist calls per received command. Internally this is done by stashing. /// /// /// An event <paramref name="handler"/> may close over eventsourced actor state and modify it. Sender of the persistent event /// is considered a sender of the corresponding command. That means, one can respond to sender from within an event handler. /// /// /// Within an event handler, applications usually update persistent actor state using /// persisted event data, notify listeners and reply to command senders. /// /// /// If persistence of an event fails, the persistent actor will be stopped. /// This can be customized by handling <see cref="PersistenceFailure"/> in <see cref="ReceiveCommand"/> method. /// </summary> public void Persist<TEvent>(TEvent @event, Action<TEvent> handler) { _pendingStashingPersistInvocations++; _pendingInvocations.AddLast(new StashingHandlerInvocation(@event, o => handler((TEvent)o))); _eventBatch.AddFirst(new Persistent(@event)); } /// <summary> /// Asynchronously persists series of <paramref name="events"/> in specified order. /// This is equivalent of multiple calls of <see cref="Persist{TEvent}(TEvent,System.Action{TEvent})"/> calls. /// </summary> public void Persist<TEvent>(IEnumerable<TEvent> events, Action<TEvent> handler) { Action<object> inv = o => handler((TEvent)o); foreach (var @event in events) { _pendingStashingPersistInvocations++; _pendingInvocations.AddLast(new StashingHandlerInvocation(@event, inv)); _eventBatch.AddFirst(new Persistent(@event)); } } /// <summary> /// Asynchronously persists an <paramref name="event"/>. On successful persistence, the <paramref name="handler"/> /// is called with the persisted event. Unlike <see cref="Persist{TEvent}(TEvent,System.Action{TEvent})"/> method, /// this one will continue to receive incoming commands between calls and executing it's event <paramref name="handler"/>. /// /// /// This version should be used in favor of <see cref="Persist{TEvent}(TEvent,System.Action{TEvent})"/> /// method when throughput is more important that commands execution precedence. /// /// /// An event <paramref name="handler"/> may close over eventsourced actor state and modify it. Sender of the persistent event /// is considered a sender of the corresponding command. That means, one can respond to sender from within an event handler. /// /// /// Within an event handler, applications usually update persistent actor state using /// persisted event data, notify listeners and reply to command senders. /// /// /// If persistence of an event fails, the persistent actor will be stopped. /// This can be customized by handling <see cref="PersistenceFailure"/> in <see cref="ReceiveCommand"/> method. /// </summary> public void PersistAsync<TEvent>(TEvent @event, Action<TEvent> handler) { _pendingInvocations.AddLast(new AsyncHandlerInvocation(@event, o => handler((TEvent)o))); _eventBatch.AddFirst(new Persistent(@event)); } /// <summary> /// Asynchronously persists series of <paramref name="events"/> in specified order. /// This is equivalent of multiple calls of <see cref="PersistAsync{TEvent}(TEvent,System.Action{TEvent})"/> calls. /// </summary> public void PersistAsync<TEvent>(IEnumerable<TEvent> events, Action<TEvent> handler) { Action<object> inv = o => handler((TEvent)o); foreach (var @event in events) { _pendingInvocations.AddLast(new AsyncHandlerInvocation(@event, inv)); _eventBatch.AddFirst(new Persistent(@event)); } } /// <summary> /// /// Defer the <paramref name="handler"/> execution until all pending handlers have been executed. /// If <see cref="PersistAsync{TEvent}(TEvent,System.Action{TEvent})"/> was invoked before defer, /// the corresponding handlers will be invoked in the same order as they were registered in. /// /// /// This call will NOT result in persisted event. If it should be possible to replay use persist method instead. /// If there are not awaiting persist handler calls, the <paramref name="handler"/> will be invoiced immediately. /// /// </summary> public void Defer<TEvent>(TEvent evt, Action<TEvent> handler) { if (_pendingInvocations.Count == 0) { handler(evt); } else { _pendingInvocations.AddLast(new AsyncHandlerInvocation(evt, o => handler((TEvent)o))); _eventBatch.AddFirst(new NonPersistentMessage(evt, Sender)); } } public void Defer<TEvent>(IEnumerable<TEvent> events, Action<TEvent> handler) { foreach (var @event in events) { Defer(@event, handler); } } public void DeleteMessages(long toSequenceNr, bool permanent) { Journal.Tell(new DeleteMessagesTo(PersistenceId, toSequenceNr, permanent)); } public void UnstashAll() { // Internally, all messages are processed by unstashing them from // the internal stash one-by-one. Hence, an unstashAll() from the // user stash must be prepended to the internal stash. _internalStash.Prepend(Stash.ClearStash()); } /// <summary> /// Called whenever a message replay succeeds. /// </summary> protected virtual void OnReplaySuccess() { } /// <summary> /// Called whenever a message replay fails. By default it log the errors. /// </summary> /// <param name="reason">Reason of failure</param> /// <param name="message">Message that caused a failure</param> protected virtual void OnReplayFailure(Exception reason, object message = null) { if (message != null) { _log.Error(reason, "Exception in ReceiveRecover when replaying event type [{0}] with sequence number [{1}] for persistenceId [{2}]", message.GetType(), LastSequenceNr, PersistenceId); } else { _log.Error(reason, "Persistence failure when replaying events for persistenceId [{0}]. Last known sequence number [{1}]", PersistenceId, LastSequenceNr); } } private void ChangeState(EventsourcedState state) { _currentState = state; } private void UpdateLastSequenceNr(IPersistentRepresentation persistent) { if (persistent.SequenceNr > LastSequenceNr) LastSequenceNr = persistent.SequenceNr; } private long NextSequenceNr() { return (++_sequenceNr); } private void FlushJournalBatch() { Journal.Tell(new WriteMessages(_journalBatch.ToArray(), Self, _instanceId)); _journalBatch = new List<IPersistentEnvelope>(0); _isWriteInProgress = true; } private IStash CreateStash() { return Context.CreateStash(GetType()); } } }
skotzko/akka.net
src/core/Akka.Persistence/Eventsourced.cs
C#
apache-2.0
15,217
/** * Copyright 2015 Knowm Inc. (http://knowm.org) and contributors. * Copyright 2013-2015 Xeiam LLC (http://xeiam.com) and contributors. * Copyright 2001-2011 Terracotta Inc. (http://terracotta.org). * * 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.quartz.plugins.management; import org.quartz.core.Scheduler; import org.quartz.exceptions.SchedulerConfigException; import org.quartz.exceptions.SchedulerException; import org.quartz.plugins.SchedulerPlugin; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This plugin catches the event of the JVM terminating (such as upon a CRTL-C) and tells the scheduler to shutdown. * * @see org.quartz.core.Scheduler#shutdown(boolean) * @author James House */ public class ShutdownHookPlugin implements SchedulerPlugin { /* * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Data members. * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ private boolean cleanShutdown = true; private final Logger logger = LoggerFactory.getLogger(getClass()); /* * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Constructors. * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ public ShutdownHookPlugin() { } /* * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Interface. * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ /** * Determine whether or not the plug-in is configured to cause a clean shutdown of the scheduler. * <p> * The default value is <code>true</code>. * </p> * * @see org.quartz.core.Scheduler#shutdown(boolean) */ public boolean isCleanShutdown() { return cleanShutdown; } /** * Set whether or not the plug-in is configured to cause a clean shutdown of the scheduler. * <p> * The default value is <code>true</code>. * </p> * * @see org.quartz.core.Scheduler#shutdown(boolean) */ public void setCleanShutdown(boolean b) { cleanShutdown = b; } /* * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ SchedulerPlugin Interface. * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ /** * <p> * Called during creation of the <code>Scheduler</code> in order to give the <code>SchedulerPlugin</code> a chance to initialize. * </p> * * @throws SchedulerConfigException if there is an error initializing. */ @Override public void initialize(String name, final Scheduler scheduler) throws SchedulerException { logger.info("Registering Quartz shutdown hook."); Thread t = new Thread("Quartz Shutdown-Hook") { @Override public void run() { logger.info("Shutting down Quartz..."); try { scheduler.shutdown(isCleanShutdown()); } catch (SchedulerException e) { logger.info("Error shutting down Quartz: " + e.getMessage(), e); } } }; Runtime.getRuntime().addShutdownHook(t); } @Override public void start() { // do nothing. } /** * <p> * Called in order to inform the <code>SchedulerPlugin</code> that it should free up all of it's resources because the scheduler is shutting down. * </p> */ @Override public void shutdown() { // nothing to do in this case (since the scheduler is already shutting // down) } }
jkandasa/Sundial
src/main/java/org/quartz/plugins/management/ShutdownHookPlugin.java
Java
apache-2.0
3,992
/** * 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.oozie.service; import org.apache.oozie.util.XLog; import org.apache.oozie.util.ELEvaluator; import org.apache.oozie.ErrorCode; import org.apache.hadoop.conf.Configuration; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.HashMap; import java.util.List; /** * The ELService creates {@link ELEvaluator} instances preconfigured with constants and functions defined in the * configuration. <p> The following configuration parameters control the EL service: <p> {@link #CONF_CONSTANTS} list * of constant definitions to be available for EL evaluations. <p> {@link #CONF_FUNCTIONS} list of function definitions * to be available for EL evalations. <p> Definitions must be separated by a comma, definitions are trimmed. <p> The * syntax for a constant definition is <code>PREFIX:NAME=CLASS_NAME#CONSTANT_NAME</code>. <p> The syntax for a constant * definition is <code>PREFIX:NAME=CLASS_NAME#METHOD_NAME</code>. */ public class ELService implements Service { public static final String CONF_PREFIX = Service.CONF_PREFIX + "ELService."; public static final String CONF_CONSTANTS = CONF_PREFIX + "constants."; public static final String CONF_EXT_CONSTANTS = CONF_PREFIX + "ext.constants."; public static final String CONF_FUNCTIONS = CONF_PREFIX + "functions."; public static final String CONF_EXT_FUNCTIONS = CONF_PREFIX + "ext.functions."; public static final String CONF_GROUPS = CONF_PREFIX + "groups"; private final XLog log = XLog.getLog(getClass()); //<Group Name>, <List of constants> private HashMap<String, List<ELConstant>> constants; //<Group Name>, <List of functions> private HashMap<String, List<ELFunction>> functions; private static class ELConstant { private String name; private Object value; private ELConstant(String prefix, String name, Object value) { if (prefix.length() > 0) { name = prefix + ":" + name; } this.name = name; this.value = value; } } private static class ELFunction { private String prefix; private String name; private Method method; private ELFunction(String prefix, String name, Method method) { this.prefix = prefix; this.name = name; this.method = method; } } private List<ELService.ELConstant> extractConstants(Configuration conf, String key) throws ServiceException { List<ELService.ELConstant> list = new ArrayList<ELService.ELConstant>(); if (conf.get(key, "").trim().length() > 0) { for (String function : ConfigurationService.getStrings(conf, key)) { String[] parts = parseDefinition(function); list.add(new ELConstant(parts[0], parts[1], findConstant(parts[2], parts[3]))); log.trace("Registered prefix:constant[{0}:{1}] for class#field[{2}#{3}]", (Object[]) parts); } } return list; } private List<ELService.ELFunction> extractFunctions(Configuration conf, String key) throws ServiceException { List<ELService.ELFunction> list = new ArrayList<ELService.ELFunction>(); if (conf.get(key, "").trim().length() > 0) { for (String function : ConfigurationService.getStrings(conf, key)) { String[] parts = parseDefinition(function); list.add(new ELFunction(parts[0], parts[1], findMethod(parts[2], parts[3]))); log.trace("Registered prefix:constant[{0}:{1}] for class#field[{2}#{3}]", (Object[]) parts); } } return list; } /** * Initialize the EL service. * * @param services services instance. * @throws ServiceException thrown if the EL service could not be initialized. */ @Override public synchronized void init(Services services) throws ServiceException { log.trace("Constants and functions registration"); constants = new HashMap<String, List<ELConstant>>(); functions = new HashMap<String, List<ELFunction>>(); //Get the list of group names from configuration file // defined in the property tag: oozie.service.ELSerice.groups //String []groupList = services.getConf().get(CONF_GROUPS, "").trim().split(","); String[] groupList = ConfigurationService.getStrings(services.getConf(), CONF_GROUPS); //For each group, collect the required functions and constants // and store it into HashMap for (String group : groupList) { List<ELConstant> tmpConstants = new ArrayList<ELConstant>(); tmpConstants.addAll(extractConstants(services.getConf(), CONF_CONSTANTS + group)); tmpConstants.addAll(extractConstants(services.getConf(), CONF_EXT_CONSTANTS + group)); constants.put(group, tmpConstants); List<ELFunction> tmpFunctions = new ArrayList<ELFunction>(); tmpFunctions.addAll(extractFunctions(services.getConf(), CONF_FUNCTIONS + group)); tmpFunctions.addAll(extractFunctions(services.getConf(), CONF_EXT_FUNCTIONS + group)); functions.put(group, tmpFunctions); } } /** * Destroy the EL service. */ @Override public void destroy() { constants = null; functions = null; } /** * Return the public interface for EL service. * * @return {@link ELService}. */ @Override public Class<? extends Service> getInterface() { return ELService.class; } /** * Return an {@link ELEvaluator} pre-configured with the constants and functions for the specific group of * EL-functions and variables defined in the configuration. If the group name doesn't exist, * IllegalArgumentException is thrown * @param group: Name of the group of required EL Evaluator. * @return ELEvaluator a preconfigured {@link ELEvaluator}. */ public ELEvaluator createEvaluator(String group) { ELEvaluator.Context context = new ELEvaluator.Context(); boolean groupDefined = false; if (constants.containsKey(group)) { for (ELConstant constant : constants.get(group)) { context.setVariable(constant.name, constant.value); } groupDefined = true; } if (functions.containsKey(group)) { for (ELFunction function : functions.get(group)) { context.addFunction(function.prefix, function.name, function.method); } groupDefined = true; } if (groupDefined == false) { throw new IllegalArgumentException("Group " + group + " is not defined"); } return new ELEvaluator(context); } private static String[] parseDefinition(String str) throws ServiceException { try { str = str.trim(); if (!str.contains(":")) { str = ":" + str; } String[] parts = str.split(":"); String prefix = parts[0]; parts = parts[1].split("="); String name = parts[0]; parts = parts[1].split("#"); String klass = parts[0]; String method = parts[1]; return new String[]{prefix, name, klass, method}; } catch (Exception ex) { throw new ServiceException(ErrorCode.E0110, str, ex.getMessage(), ex); } } public static Method findMethod(String className, String methodName) throws ServiceException { Method method = null; try { Class klass = Thread.currentThread().getContextClassLoader().loadClass(className); for (Method m : klass.getMethods()) { if (m.getName().equals(methodName)) { method = m; break; } } if (method == null) { throw new ServiceException(ErrorCode.E0111, className, methodName); } if ((method.getModifiers() & (Modifier.PUBLIC | Modifier.STATIC)) != (Modifier.PUBLIC | Modifier.STATIC)) { throw new ServiceException(ErrorCode.E0112, className, methodName); } } catch (ClassNotFoundException ex) { throw new ServiceException(ErrorCode.E0113, className); } return method; } public static Object findConstant(String className, String constantName) throws ServiceException { try { Class klass = Thread.currentThread().getContextClassLoader().loadClass(className); Field field = klass.getField(constantName); if ((field.getModifiers() & (Modifier.PUBLIC | Modifier.STATIC)) != (Modifier.PUBLIC | Modifier.STATIC)) { throw new ServiceException(ErrorCode.E0114, className, constantName); } return field.get(null); } catch (IllegalAccessException ex) { throw new IllegalArgumentException(ex); } catch (NoSuchFieldException ex) { throw new ServiceException(ErrorCode.E0115, className, constantName); } catch (ClassNotFoundException ex) { throw new ServiceException(ErrorCode.E0113, className); } } }
cbaenziger/oozie
core/src/main/java/org/apache/oozie/service/ELService.java
Java
apache-2.0
10,251
/** * Copyright 2017 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ApiAiSDK { public class PrivacyStatementDeclinedException : Exception { public PrivacyStatementDeclinedException(string message, Exception innerException) : base(message, innerException) { } public PrivacyStatementDeclinedException() { } } }
dialogflow/dialogflow-dotnet-client
ApiAiSDK.WP8/PrivacyStatementDeclinedException.cs
C#
apache-2.0
1,053
/* Copyright (c) 2002 JSON.org 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 shall be used for Good, not Evil. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. json.js 2006-10-05 This file adds these methods to JavaScript: object.toJSONString() This method produces a JSON text from an object. The object must not contain any cyclical references. array.toJSONString() This method produces a JSON text from an array. The array must not contain any cyclical references. string.parseJSON() This method parses a JSON text to produce an object or array. It will return false if there is an error. It is expected that these methods will formally become part of the JavaScript Programming Language in the Fourth Edition of the ECMAScript standard. */ (function () { var m = { '\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"' : '\\"', '\\': '\\\\' }, s = { array: function (x) { var a = ['['], b, f, i, l = x.length, v; for (i = 0; i < l; i += 1) { v = x[i]; f = s[typeof v]; if (f) { v = f(v); if (typeof v == 'string') { if (b) { a[a.length] = ','; } a[a.length] = v; b = true; } } } a[a.length] = ']'; return a.join(''); }, 'boolean': function (x) { return String(x); }, 'null': function (x) { return "null"; }, number: function (x) { return isFinite(x) ? String(x) : 'null'; }, object: function (x) { if (x) { if (x instanceof Array) { return s.array(x); } var a = ['{'], b, f, i, v; for (i in x) { v = x[i]; f = s[typeof v]; if (f) { v = f(v); if (typeof v == 'string') { if (b) { a[a.length] = ','; } a.push(s.string(i), ':', v); b = true; } } } a[a.length] = '}'; return a.join(''); } return 'null'; }, string: function (x) { if (/["\\\x00-\x1f]/.test(x)) { x = x.replace(/([\x00-\x1f\\"])/g, function(a, b) { var c = m[b]; if (c) { return c; } c = b.charCodeAt(); return '\\u00' + Math.floor(c / 16).toString(16) + (c % 16).toString(16); }); } return '"' + x + '"'; } }; Object.prototype.toJSONString = function () { return s.object(this); }; Array.prototype.toJSONString = function () { return s.array(this); }; })(); String.prototype.parseJSON = function () { try { return (/^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/.test(this)) && eval('(' + this + ')'); } catch (e) { return false; } };
apache/chukwa
core/src/main/web/hicc/js/json.js
JavaScript
apache-2.0
4,907
/******************************************************************************* * 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.olingo.odata2.client.core.ep.deserializer; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.apache.olingo.odata2.api.edm.EdmException; import org.apache.olingo.odata2.api.ep.EntityProviderException; import org.apache.olingo.odata2.api.ep.entry.DeletedEntryMetadata; import org.apache.olingo.odata2.api.ep.entry.ODataEntry; import org.apache.olingo.odata2.api.ep.feed.ODataDeltaFeed; import org.apache.olingo.odata2.api.ep.feed.ODataFeed; import org.apache.olingo.odata2.client.api.ep.DeserializerProperties; import org.apache.olingo.odata2.core.ep.aggregator.EntityInfoAggregator; import org.apache.olingo.odata2.core.ep.feed.FeedMetadataImpl; import org.apache.olingo.odata2.core.ep.feed.JsonFeedEntry; import org.apache.olingo.odata2.core.ep.feed.ODataDeltaFeedImpl; import org.apache.olingo.odata2.core.ep.util.FormatJson; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonToken; /** * This class Deserializes JsonFeed payloads */ public class JsonFeedDeserializer { private JsonReader reader; private EntityInfoAggregator eia; private DeserializerProperties readProperties; private List<DeletedEntryMetadata> deletedEntries = new ArrayList<DeletedEntryMetadata>(); private List<ODataEntry> entries = new ArrayList<ODataEntry>(); private FeedMetadataImpl feedMetadata = new FeedMetadataImpl(); private boolean resultsArrayPresent = false; private static final String JSONFEED = "JsonFeed"; /** * * @param reader * @param eia * @param readProperties */ public JsonFeedDeserializer(final JsonReader reader, final EntityInfoAggregator eia, final DeserializerProperties readProperties) { this.reader = reader; this.eia = eia; this.readProperties = readProperties; } /** * * @return ODataDeltaFeed * @throws EntityProviderException */ public ODataDeltaFeed readFeedStandalone() throws EntityProviderException { try { readFeed(); if (reader.peek() != JsonToken.END_DOCUMENT) { throw new EntityProviderException(EntityProviderException.END_DOCUMENT_EXPECTED.addContent(reader.peek() .toString())); } } catch (IOException e) { throw new EntityProviderException(EntityProviderException.EXCEPTION_OCCURRED.addContent(e.getClass() .getSimpleName()), e); } catch (EdmException e) { throw new EntityProviderException(EntityProviderException.EXCEPTION_OCCURRED.addContent(e.getClass() .getSimpleName()), e); } catch (IllegalStateException e) { throw new EntityProviderException(EntityProviderException.EXCEPTION_OCCURRED.addContent(e.getClass() .getSimpleName()), e); } return new ODataDeltaFeedImpl(entries, feedMetadata, deletedEntries); } /** * * @throws IOException * @throws EdmException * @throws EntityProviderException */ private void readFeed() throws IOException, EdmException, EntityProviderException { JsonToken peek = reader.peek(); if (peek == JsonToken.BEGIN_ARRAY) { readArrayContent(); } else { reader.beginObject(); final String nextName = reader.nextName(); if (FormatJson.D.equals(nextName)) { if (reader.peek() == JsonToken.BEGIN_ARRAY) { readArrayContent(); } else { reader.beginObject(); readFeedContent(); reader.endObject(); } } else { handleName(nextName); readFeedContent(); } reader.endObject(); } } /** * * @throws IOException * @throws EdmException * @throws EntityProviderException */ private void readFeedContent() throws IOException, EdmException, EntityProviderException { while (reader.hasNext()) { final String nextName = reader.nextName(); handleName(nextName); } if (!resultsArrayPresent) { throw new EntityProviderException(EntityProviderException.MISSING_RESULTS_ARRAY); } } /** * * @param nextName * @throws IOException * @throws EdmException * @throws EntityProviderException */ private void handleName(final String nextName) throws IOException, EdmException, EntityProviderException { if (FormatJson.RESULTS.equals(nextName)) { resultsArrayPresent = true; readArrayContent(); } else if (FormatJson.COUNT.equals(nextName)) { readInlineCount(reader, feedMetadata); } else if (FormatJson.NEXT.equals(nextName)) { if (reader.peek() == JsonToken.STRING && feedMetadata.getNextLink() == null) { String nextLink = reader.nextString(); feedMetadata.setNextLink(nextLink); } else { throw new EntityProviderException(EntityProviderException.INVALID_CONTENT.addContent(nextName).addContent( JSONFEED)); } } else if (FormatJson.DELTA.equals(nextName)) { if (reader.peek() == JsonToken.STRING && feedMetadata.getDeltaLink() == null) { String deltaLink = reader.nextString(); feedMetadata.setDeltaLink(deltaLink); } else { throw new EntityProviderException(EntityProviderException.INVALID_CONTENT.addContent(nextName).addContent( JSONFEED)); } } else { throw new EntityProviderException(EntityProviderException.INVALID_CONTENT.addContent(nextName).addContent( JSONFEED)); } } /** * * @throws IOException * @throws EdmException * @throws EntityProviderException */ private void readArrayContent() throws IOException, EdmException, EntityProviderException { reader.beginArray(); while (reader.hasNext()) { final JsonFeedEntry entry = new JsonEntryDeserializer(reader, eia, readProperties).readFeedEntry(); if (entry.isODataEntry()) { entries.add(entry.getODataEntry()); } else { deletedEntries.add(entry.getDeletedEntryMetadata()); } } reader.endArray(); } /** * * @param reader * @param feedMetadata * @throws IOException * @throws EntityProviderException */ protected static void readInlineCount(final JsonReader reader, final FeedMetadataImpl feedMetadata) throws IOException, EntityProviderException { if (reader.peek() == JsonToken.STRING && feedMetadata.getInlineCount() == null) { int inlineCount; try { inlineCount = reader.nextInt(); } catch (final NumberFormatException e) { throw new EntityProviderException(EntityProviderException.INLINECOUNT_INVALID.addContent(""), e); } if (inlineCount >= 0) { feedMetadata.setInlineCount(inlineCount); } else { throw new EntityProviderException(EntityProviderException.INLINECOUNT_INVALID.addContent(inlineCount)); } } else { throw new EntityProviderException(EntityProviderException.INLINECOUNT_INVALID.addContent(reader.peek())); } } /** * * @param name * @return ODataFeed * @throws EdmException * @throws EntityProviderException * @throws IOException */ protected ODataFeed readStartedInlineFeed(final String name) throws EdmException, EntityProviderException, IOException { // consume the already started content handleName(name); // consume the rest of the entry content readFeedContent(); return new ODataDeltaFeedImpl(entries, feedMetadata); } /** * * @return ODataFeed * @throws EdmException * @throws EntityProviderException * @throws IOException */ protected ODataFeed readInlineFeedStandalone() throws EdmException, EntityProviderException, IOException { readFeed(); return new ODataDeltaFeedImpl(entries, feedMetadata); } }
apache/olingo-odata2
odata2-lib/odata-client-core/src/main/java/org/apache/olingo/odata2/client/core/ep/deserializer/JsonFeedDeserializer.java
Java
apache-2.0
8,653
/** * Created by hooxin on 14-10-10. */ /** * 字典维护标志 */ Ext.define('Techsupport.store.DictMaintFlag', { extend: 'Ext.data.Store', fields: ['text', 'value'], data: [ {text: '维护', value: 0}, {text: '停止维护', value: 1} ] })
firefoxmmx2/techsupport_ext4_scala
public/javascripts/app/store/DictMaintFlag.js
JavaScript
apache-2.0
279
package water.api; import water.*; import water.H2O.H2OCountedCompleter; import water.persist.PersistS3Task; import water.persist.PersistS3; import water.util.Log; import com.google.gson.JsonObject; public class ExportS3 extends Request { protected class BucketArg extends TypeaheadInputText<String> { public BucketArg(String name) { super(TypeaheadS3BucketRequest.class, name, true); } @Override protected String parse(String input) throws IllegalArgumentException { PersistS3.getClient(); return input; } @Override protected String queryDescription() { return "S3 Bucket"; } @Override protected String defaultValue() { return null; } } protected final H2OExistingKey _source = new H2OExistingKey(SOURCE_KEY); protected final BucketArg _bucket = new BucketArg(BUCKET); protected final Str _object = new Str(OBJECT, ""); public ExportS3() { _requestHelp = "Exports a key to Amazon S3. All nodes in the " + "cloud must have permission to access the Amazon object."; _bucket._requestHelp = "Target Amazon S3 Bucket."; } @Override protected Response serve() { final Value value = _source.value(); final String bucket = _bucket.value(); final String object = _object.value(); try { final Key dest = PersistS3Task.init(value); H2O.submitTask(new H2OCountedCompleter() { @Override public void compute2() { PersistS3Task.run(dest, value, bucket, object); } }); JsonObject response = new JsonObject(); response.addProperty(RequestStatics.DEST_KEY, dest.toString()); Response r = ExportS3Progress.redirect(response, dest); r.setBuilder(RequestStatics.DEST_KEY, new KeyElementBuilder()); return r; } catch( Throwable e ) { return Response.error(e); } } }
janezhango/BigDataMachineLearning
src/main/java/water/api/ExportS3.java
Java
apache-2.0
1,889
/* * JBoss, Home of Professional Open Source * Copyright 2009, Red Hat, Inc. and/or its affiliates, and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.hibernate.validator.test.internal.constraintvalidators; import java.util.Date; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import org.hibernate.validator.internal.constraintvalidators.FutureValidatorForDate; public class FutureValidatorForDateTest { private static FutureValidatorForDate constraint; @BeforeClass public static void init() { constraint = new FutureValidatorForDate(); } @Test public void testIsValid() { Date futureDate = getFutureDate(); Date pastDate = getPastDate(); assertTrue( constraint.isValid( null, null ) ); assertTrue( constraint.isValid( futureDate, null ) ); assertFalse( constraint.isValid( pastDate, null ) ); } private Date getFutureDate() { Date date = new Date(); long timeStamp = date.getTime(); date.setTime( timeStamp + 31557600000L ); return date; } private Date getPastDate() { Date date = new Date(); long timeStamp = date.getTime(); date.setTime( timeStamp - 31557600000L ); return date; } }
jmartisk/hibernate-validator
engine/src/test/java/org/hibernate/validator/test/internal/constraintvalidators/FutureValidatorForDateTest.java
Java
apache-2.0
1,901
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import functools from keystone.common import json_home from keystone.common import wsgi from keystone.contrib.federation import controllers build_resource_relation = functools.partial( json_home.build_v3_extension_resource_relation, extension_name='OS-FEDERATION', extension_version='1.0') build_parameter_relation = functools.partial( json_home.build_v3_extension_parameter_relation, extension_name='OS-FEDERATION', extension_version='1.0') IDP_ID_PARAMETER_RELATION = build_parameter_relation(parameter_name='idp_id') PROTOCOL_ID_PARAMETER_RELATION = build_parameter_relation( parameter_name='protocol_id') SP_ID_PARAMETER_RELATION = build_parameter_relation(parameter_name='sp_id') class FederationExtension(wsgi.V3ExtensionRouter): """API Endpoints for the Federation extension. The API looks like:: PUT /OS-FEDERATION/identity_providers/$identity_provider GET /OS-FEDERATION/identity_providers GET /OS-FEDERATION/identity_providers/$identity_provider DELETE /OS-FEDERATION/identity_providers/$identity_provider PATCH /OS-FEDERATION/identity_providers/$identity_provider PUT /OS-FEDERATION/identity_providers/ $identity_provider/protocols/$protocol GET /OS-FEDERATION/identity_providers/ $identity_provider/protocols GET /OS-FEDERATION/identity_providers/ $identity_provider/protocols/$protocol PATCH /OS-FEDERATION/identity_providers/ $identity_provider/protocols/$protocol DELETE /OS-FEDERATION/identity_providers/ $identity_provider/protocols/$protocol PUT /OS-FEDERATION/mappings GET /OS-FEDERATION/mappings PATCH /OS-FEDERATION/mappings/$mapping_id GET /OS-FEDERATION/mappings/$mapping_id DELETE /OS-FEDERATION/mappings/$mapping_id GET /OS-FEDERATION/projects GET /OS-FEDERATION/domains PUT /OS-FEDERATION/service_providers/$service_provider GET /OS-FEDERATION/service_providers GET /OS-FEDERATION/service_providers/$service_provider DELETE /OS-FEDERATION/service_providers/$service_provider PATCH /OS-FEDERATION/service_providers/$service_provider GET /OS-FEDERATION/identity_providers/$identity_provider/ protocols/$protocol/auth POST /OS-FEDERATION/identity_providers/$identity_provider/ protocols/$protocol/auth POST /auth/OS-FEDERATION/saml2 GET /OS-FEDERATION/saml2/metadata GET /auth/OS-FEDERATION/websso/{protocol_id} ?origin=https%3A//horizon.example.com POST /auth/OS-FEDERATION/websso/{protocol_id} ?origin=https%3A//horizon.example.com """ def _construct_url(self, suffix): return "/OS-FEDERATION/%s" % suffix def add_routes(self, mapper): auth_controller = controllers.Auth() idp_controller = controllers.IdentityProvider() protocol_controller = controllers.FederationProtocol() mapping_controller = controllers.MappingController() project_controller = controllers.ProjectAssignmentV3() domain_controller = controllers.DomainV3() saml_metadata_controller = controllers.SAMLMetadataV3() sp_controller = controllers.ServiceProvider() # Identity Provider CRUD operations self._add_resource( mapper, idp_controller, path=self._construct_url('identity_providers/{idp_id}'), get_action='get_identity_provider', put_action='create_identity_provider', patch_action='update_identity_provider', delete_action='delete_identity_provider', rel=build_resource_relation(resource_name='identity_provider'), path_vars={ 'idp_id': IDP_ID_PARAMETER_RELATION, }) self._add_resource( mapper, idp_controller, path=self._construct_url('identity_providers'), get_action='list_identity_providers', rel=build_resource_relation(resource_name='identity_providers')) # Protocol CRUD operations self._add_resource( mapper, protocol_controller, path=self._construct_url('identity_providers/{idp_id}/protocols/' '{protocol_id}'), get_action='get_protocol', put_action='create_protocol', patch_action='update_protocol', delete_action='delete_protocol', rel=build_resource_relation( resource_name='identity_provider_protocol'), path_vars={ 'idp_id': IDP_ID_PARAMETER_RELATION, 'protocol_id': PROTOCOL_ID_PARAMETER_RELATION, }) self._add_resource( mapper, protocol_controller, path=self._construct_url('identity_providers/{idp_id}/protocols'), get_action='list_protocols', rel=build_resource_relation( resource_name='identity_provider_protocols'), path_vars={ 'idp_id': IDP_ID_PARAMETER_RELATION, }) # Mapping CRUD operations self._add_resource( mapper, mapping_controller, path=self._construct_url('mappings/{mapping_id}'), get_action='get_mapping', put_action='create_mapping', patch_action='update_mapping', delete_action='delete_mapping', rel=build_resource_relation(resource_name='mapping'), path_vars={ 'mapping_id': build_parameter_relation( parameter_name='mapping_id'), }) self._add_resource( mapper, mapping_controller, path=self._construct_url('mappings'), get_action='list_mappings', rel=build_resource_relation(resource_name='mappings')) # Service Providers CRUD operations self._add_resource( mapper, sp_controller, path=self._construct_url('service_providers/{sp_id}'), get_action='get_service_provider', put_action='create_service_provider', patch_action='update_service_provider', delete_action='delete_service_provider', rel=build_resource_relation(resource_name='service_provider'), path_vars={ 'sp_id': SP_ID_PARAMETER_RELATION, }) self._add_resource( mapper, sp_controller, path=self._construct_url('service_providers'), get_action='list_service_providers', rel=build_resource_relation(resource_name='service_providers')) self._add_resource( mapper, domain_controller, path=self._construct_url('domains'), get_action='list_domains_for_groups', rel=build_resource_relation(resource_name='domains')) self._add_resource( mapper, project_controller, path=self._construct_url('projects'), get_action='list_projects_for_groups', rel=build_resource_relation(resource_name='projects')) self._add_resource( mapper, auth_controller, path=self._construct_url('identity_providers/{identity_provider}/' 'protocols/{protocol}/auth'), get_post_action='federated_authentication', rel=build_resource_relation( resource_name='identity_provider_protocol_auth'), path_vars={ 'identity_provider': IDP_ID_PARAMETER_RELATION, 'protocol': PROTOCOL_ID_PARAMETER_RELATION, }) # Auth operations self._add_resource( mapper, auth_controller, path='/auth' + self._construct_url('saml2'), post_action='create_saml_assertion', rel=build_resource_relation(resource_name='saml2')) self._add_resource( mapper, auth_controller, path='/auth' + self._construct_url('websso/{protocol_id}'), get_post_action='federated_sso_auth', rel=build_resource_relation(resource_name='websso'), path_vars={ 'protocol_id': PROTOCOL_ID_PARAMETER_RELATION, }) # Keystone-Identity-Provider metadata endpoint self._add_resource( mapper, saml_metadata_controller, path=self._construct_url('saml2/metadata'), get_action='get_metadata', rel=build_resource_relation(resource_name='metadata'))
rushiagr/keystone
keystone/contrib/federation/routers.py
Python
apache-2.0
9,192
# Copyright 2012-2013 OpenStack Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # """Command-line interface to the OpenStack APIs""" import getpass import logging import sys import traceback from cliff import app from cliff import command from cliff import complete from cliff import help import openstackclient from openstackclient.common import clientmanager from openstackclient.common import commandmanager from openstackclient.common import exceptions as exc from openstackclient.common import timing from openstackclient.common import utils DEFAULT_DOMAIN = 'default' def prompt_for_password(prompt=None): """Prompt user for a password Propmpt for a password if stdin is a tty. """ if not prompt: prompt = 'Password: ' pw = None # If stdin is a tty, try prompting for the password if hasattr(sys.stdin, 'isatty') and sys.stdin.isatty(): # Check for Ctl-D try: pw = getpass.getpass(prompt) except EOFError: pass # No password because we did't have a tty or nothing was entered if not pw: raise exc.CommandError( "No password entered, or found via --os-password or OS_PASSWORD", ) return pw class OpenStackShell(app.App): CONSOLE_MESSAGE_FORMAT = '%(levelname)s: %(name)s %(message)s' log = logging.getLogger(__name__) timing_data = [] def __init__(self): # Patch command.Command to add a default auth_required = True command.Command.auth_required = True command.Command.best_effort = False # But not help help.HelpCommand.auth_required = False complete.CompleteCommand.best_effort = True super(OpenStackShell, self).__init__( description=__doc__.strip(), version=openstackclient.__version__, command_manager=commandmanager.CommandManager('openstack.cli')) self.api_version = {} # Until we have command line arguments parsed, dump any stack traces self.dump_stack_trace = True # This is instantiated in initialize_app() only when using # password flow auth self.auth_client = None # Assume TLS host certificate verification is enabled self.verify = True self.client_manager = None # NOTE(dtroyer): This hack changes the help action that Cliff # automatically adds to the parser so we can defer # its execution until after the api-versioned commands # have been loaded. There doesn't seem to be a # way to edit/remove anything from an existing parser. # Replace the cliff-added help.HelpAction to defer its execution self.DeferredHelpAction = None for a in self.parser._actions: if type(a) == help.HelpAction: # Found it, save and replace it self.DeferredHelpAction = a # These steps are argparse-implementation-dependent self.parser._actions.remove(a) if self.parser._option_string_actions['-h']: del self.parser._option_string_actions['-h'] if self.parser._option_string_actions['--help']: del self.parser._option_string_actions['--help'] # Make a new help option to just set a flag self.parser.add_argument( '-h', '--help', action='store_true', dest='deferred_help', default=False, help="Show this help message and exit", ) def configure_logging(self): """Configure logging for the app Cliff sets some defaults we don't want so re-work it a bit """ if self.options.debug: # --debug forces verbose_level 3 # Set this here so cliff.app.configure_logging() can work self.options.verbose_level = 3 super(OpenStackShell, self).configure_logging() root_logger = logging.getLogger('') # Set logging to the requested level if self.options.verbose_level == 0: # --quiet root_logger.setLevel(logging.ERROR) elif self.options.verbose_level == 1: # This is the default case, no --debug, --verbose or --quiet root_logger.setLevel(logging.WARNING) elif self.options.verbose_level == 2: # One --verbose root_logger.setLevel(logging.INFO) elif self.options.verbose_level >= 3: # Two or more --verbose root_logger.setLevel(logging.DEBUG) # Requests logs some stuff at INFO that we don't want # unless we have DEBUG requests_log = logging.getLogger("requests") # Other modules we don't want DEBUG output for cliff_log = logging.getLogger('cliff') stevedore_log = logging.getLogger('stevedore') iso8601_log = logging.getLogger("iso8601") if self.options.debug: # --debug forces traceback self.dump_stack_trace = True requests_log.setLevel(logging.DEBUG) cliff_log.setLevel(logging.DEBUG) else: self.dump_stack_trace = False requests_log.setLevel(logging.ERROR) cliff_log.setLevel(logging.ERROR) stevedore_log.setLevel(logging.ERROR) iso8601_log.setLevel(logging.ERROR) def run(self, argv): try: return super(OpenStackShell, self).run(argv) except Exception as e: if not logging.getLogger('').handlers: logging.basicConfig() if self.dump_stack_trace: self.log.error(traceback.format_exc(e)) else: self.log.error('Exception raised: ' + str(e)) return 1 def build_option_parser(self, description, version): parser = super(OpenStackShell, self).build_option_parser( description, version) # service token auth argument parser.add_argument( '--os-url', metavar='<url>', default=utils.env('OS_URL'), help='Defaults to env[OS_URL]') # Global arguments parser.add_argument( '--os-region-name', metavar='<auth-region-name>', default=utils.env('OS_REGION_NAME'), help='Authentication region name (Env: OS_REGION_NAME)') parser.add_argument( '--os-cacert', metavar='<ca-bundle-file>', default=utils.env('OS_CACERT'), help='CA certificate bundle file (Env: OS_CACERT)') verify_group = parser.add_mutually_exclusive_group() verify_group.add_argument( '--verify', action='store_true', help='Verify server certificate (default)', ) verify_group.add_argument( '--insecure', action='store_true', help='Disable server certificate verification', ) parser.add_argument( '--os-default-domain', metavar='<auth-domain>', default=utils.env( 'OS_DEFAULT_DOMAIN', default=DEFAULT_DOMAIN), help='Default domain ID, default=' + DEFAULT_DOMAIN + ' (Env: OS_DEFAULT_DOMAIN)') parser.add_argument( '--timing', default=False, action='store_true', help="Print API call timing info", ) return clientmanager.build_plugin_option_parser(parser) def initialize_app(self, argv): """Global app init bits: * set up API versions * validate authentication info * authenticate against Identity if requested """ super(OpenStackShell, self).initialize_app(argv) # Save default domain self.default_domain = self.options.os_default_domain # Loop through extensions to get API versions for mod in clientmanager.PLUGIN_MODULES: version_opt = getattr(self.options, mod.API_VERSION_OPTION, None) if version_opt: api = mod.API_NAME self.api_version[api] = version_opt version = '.v' + version_opt.replace('.', '_') cmd_group = 'openstack.' + api.replace('-', '_') + version self.command_manager.add_command_group(cmd_group) self.log.debug( '%(name)s API version %(version)s, cmd group %(group)s', {'name': api, 'version': version_opt, 'group': cmd_group} ) # Commands that span multiple APIs self.command_manager.add_command_group( 'openstack.common') # This is the naive extension implementation referred to in # blueprint 'client-extensions' # Extension modules can register their commands in an # 'openstack.extension' entry point group: # entry_points={ # 'openstack.extension': [ # 'list_repo=qaz.github.repo:ListRepo', # 'show_repo=qaz.github.repo:ShowRepo', # ], # } self.command_manager.add_command_group( 'openstack.extension') # call InitializeXxx() here # set up additional clients to stuff in to client_manager?? # Handle deferred help and exit if self.options.deferred_help: self.DeferredHelpAction(self.parser, self.parser, None, None) # Set up common client session if self.options.os_cacert: self.verify = self.options.os_cacert else: self.verify = not self.options.insecure self.client_manager = clientmanager.ClientManager( auth_options=self.options, verify=self.verify, api_version=self.api_version, pw_func=prompt_for_password, ) def prepare_to_run_command(self, cmd): """Set up auth and API versions""" self.log.info( 'command: %s.%s', cmd.__class__.__module__, cmd.__class__.__name__, ) if cmd.auth_required and cmd.best_effort: try: # Trigger the Identity client to initialize self.client_manager.auth_ref except Exception: pass return def clean_up(self, cmd, result, err): self.log.debug('clean_up %s', cmd.__class__.__name__) if err: self.log.debug('got an error: %s', err) # Process collected timing data if self.options.timing: # Loop through extensions for mod in self.ext_modules: client = getattr(self.client_manager, mod.API_NAME) if hasattr(client, 'get_timings'): self.timing_data.extend(client.get_timings()) # Use the Timing pseudo-command to generate the output tcmd = timing.Timing(self, self.options) tparser = tcmd.get_parser('Timing') # If anything other than prettytable is specified, force csv format = 'table' # Check the formatter used in the actual command if hasattr(cmd, 'formatter') \ and cmd.formatter != cmd._formatter_plugins['table'].obj: format = 'csv' sys.stdout.write('\n') targs = tparser.parse_args(['-f', format]) tcmd.run(targs) def main(argv=sys.argv[1:]): return OpenStackShell().run(argv) if __name__ == "__main__": sys.exit(main(sys.argv[1:]))
varunarya10/python-openstackclient
openstackclient/shell.py
Python
apache-2.0
12,311
/* * Copyright 2011 Nate Koenig & Andrew Howard * * 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. * */ /* Desc: Graphics 3d Interface for Player * Author: Nate Koenig * Date: 30 Jan 2007 */ #ifndef GRAPHICS3DINTERFACE_HH #define GRAPHICS3DINTERFACE_HH #include "GazeboInterface.hh" namespace boost { class recursive_mutex; } namespace libgazebo { // Forward declarations class Graphics3dIface; /// \brief Graphics3d interface class Graphics3dInterface : public GazeboInterface { /// \brief Constructor public: Graphics3dInterface(player_devaddr_t addr, GazeboDriver *driver, ConfigFile *cf, int section); /// \brief Destructor public: virtual ~Graphics3dInterface(); /// \brief Handle all messages. This is called from GazeboDriver public: virtual int ProcessMessage(QueuePointer &respQueue, player_msghdr_t *hdr, void *data); /// \brief Update this interface, publish new info. public: virtual void Update(); /// \brief Open a SHM interface when a subscription is received. /// This is called fromGazeboDriver::Subscribe public: virtual void Subscribe(); /// \brief Close a SHM interface. This is called from /// GazeboDriver::Unsubscribe public: virtual void Unsubscribe(); private: Graphics3dIface *iface; /// \brief Gazebo id. This needs to match and ID in a Gazebo WorldFile private: char *gz_id; private: static boost::recursive_mutex *mutex; }; } #endif
nherment/gazebo
interfaces/player/Graphics3dInterface.hh
C++
apache-2.0
2,058
<?php /* * Copyright 2013 Johannes M. Schmitt <johannes@scrutinizer-ci.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. */ namespace Scrutinizer\PhpAnalyzer\DataFlow\TypeInference; use Psr\Log\LoggerInterface; use Psr\Log\NullLogger; use Scrutinizer\PhpAnalyzer\ControlFlow\ControlFlowGraph; use Scrutinizer\PhpAnalyzer\ControlFlow\GraphEdge; use Scrutinizer\PhpAnalyzer\DataFlow\BinaryJoinOp; use Scrutinizer\PhpAnalyzer\DataFlow\BranchedForwardDataFlowAnalysis; use Scrutinizer\PhpAnalyzer\DataFlow\LatticeElementInterface; use Scrutinizer\PhpAnalyzer\PhpParser\NodeUtil; use Scrutinizer\PhpAnalyzer\PhpParser\Scope\Scope; use Scrutinizer\PhpAnalyzer\PhpParser\Scope\Variable; use Scrutinizer\PhpAnalyzer\PhpParser\Type\ArrayType; use Scrutinizer\PhpAnalyzer\PhpParser\Type\NamedType; use Scrutinizer\PhpAnalyzer\PhpParser\Type\PhpType; use Scrutinizer\PhpAnalyzer\PhpParser\Type\ThisType; use Scrutinizer\PhpAnalyzer\PhpParser\Type\TypeRegistry; use Scrutinizer\PhpAnalyzer\PhpParser\Type\UnionType; use Scrutinizer\PhpAnalyzer\DataFlow\TypeInference\FunctionInterpreter\FunctionInterpreterInterface; use Scrutinizer\PhpAnalyzer\DataFlow\TypeInference\ReverseInterpreter\ReverseInterpreterInterface; use Scrutinizer\PhpAnalyzer\Model\ClassProperty; use Scrutinizer\PhpAnalyzer\Model\Clazz; use Scrutinizer\PhpAnalyzer\Model\ContainerMethodInterface; use Scrutinizer\PhpAnalyzer\Model\GlobalFunction; use JMS\PhpManipulator\PhpParser\BlockNode; class TypeInference extends BranchedForwardDataFlowAnalysis { /** @var LoggerInterface */ private $logger; /** @var TypeRegistry */ private $typeRegistry; /** @var ReverseInterpreterInterface */ private $reverseInterpreter; /** @var FunctionInterpreterInterface */ private $functionInterpreter; /** @var MethodInterpreter\MethodInterpreterInterface */ private $methodInterpreter; /** @var \Scrutinizer\PhpAnalyzer\PhpParser\DocCommentParser */ private $commentParser; /** @var Scope */ private $syntacticScope; /** @var LinkedFlowScope */ private $functionScope; /** @var LinkedFlowScope */ private $bottomScope; /** * Returns whether the given node has a uniquely identifying name. * * @param \PHPParser_Node $node * * @return boolean */ public static function hasQualifiedName(\PHPParser_Node $node) { return null !== self::getQualifiedName($node); } /** * Returns a name that uniquely identifies a slot in the flow scope. * * @param \PHPParser_Node $node * * @return string|null */ public static function getQualifiedName(\PHPParser_Node $node) { if ($node instanceof \PHPParser_Node_Expr_Variable) { return is_string($node->name) ? $node->name : null; } if ($node instanceof \PHPParser_Node_Expr_StaticPropertyFetch) { if ( ! $node->class instanceof \PHPParser_Node_Name) { return null; } if ( ! is_string($node->name)) { return null; } $objType = $node->class->getAttribute('type'); if (null === $objType || null === $resolvedObjType = $objType->toMaybeObjectType()) { if ($objType instanceof NamedType) { return $objType->getReferenceName().'::$'.$node->name; } return null; } // If this property has been declared correctly, then we fetch the declaring class // to make type inference a bit more precise. Otherwise, we will simply fallback // to using the current class name, and assume that it will be implicitly declared. if ($resolvedObjType->isClass() && $resolvedObjType->hasProperty($node->name)) { return $resolvedObjType->getProperty($node->name)->getDeclaringClass().'::$'.$node->name; } return $resolvedObjType->getName().'::$'.$node->name; } if ($node instanceof \PHPParser_Node_Expr_PropertyFetch) { if ( ! $node->var instanceof \PHPParser_Node_Expr_Variable) { return null; } if ( ! is_string($node->name)) { return null; } if ( ! is_string($node->var->name)) { return null; } return $node->var->name.'->'.$node->name; } return null; } public static function createJoinOperation() { return new BinaryJoinOp(function(LinkedFlowScope $a, LinkedFlowScope $b) { $a->frozen = true; $b->frozen = true; if ($a->optimize() === $b->optimize()) { return $a->createChildFlowScope(); } return new LinkedFlowScope(FlatFlowScopeCache::createFromLinkedScopes($a, $b)); }); } public function __construct(ControlFlowGraph $cfg, ReverseInterpreterInterface $reverseInterpreter, FunctionInterpreterInterface $functionInterpreter, MethodInterpreter\MethodInterpreterInterface $methodInterpreter, \Scrutinizer\PhpAnalyzer\PhpParser\DocCommentParser $commentParser, Scope $functionScope, TypeRegistry $registry, LoggerInterface $logger = null) { parent::__construct($cfg, self::createJoinOperation()); $this->reverseInterpreter = $reverseInterpreter; $this->functionInterpreter = $functionInterpreter; $this->methodInterpreter = $methodInterpreter; $this->syntacticScope = $functionScope; $this->commentParser = $commentParser; $this->functionScope = LinkedFlowScope::createLatticeElement($functionScope); $this->bottomScope = LinkedFlowScope::createLatticeElement( Scope::createBottomScope($functionScope->getRootNode(), $functionScope->getTypeOfThis())); $this->typeRegistry = $registry; $this->logger = $logger ?: new NullLogger(); } protected function createInitialEstimateLattice() { return $this->bottomScope; } protected function createEntryLattice() { return $this->functionScope; } /** * Calculates the out lattices for the different branches. * * Right now, we just treat ON_EX edges like UNCOND edges. If we want to be perfect, we would have to actually join * all the out lattices of this flow with the in lattice, and then make that the out lattice for the ON_EX edge. * However, that would add some extra computation for an edge case. So, the current behavior looks like a "good enough" * approximation. * * @param \PHPParser_Node $source * @param LatticeElementInterface $input * * @return array<LatticeElementInterface> */ protected function branchedFlowThrough($source, LatticeElementInterface $input) { assert($source instanceof \PHPParser_Node); assert($input instanceof LinkedFlowScope); // If we have not walked a path from the entry node to this node, we cannot infer anything // about this scope. So, just skip it for now, we will come back later. if ($input === $this->bottomScope) { $output = $input; } else { $output = $input->createChildFlowScope(); $output = $this->traverse($source, $output); } $condition = $conditionFlowScope = $conditionOutcomes = null; $result = array(); foreach ($this->cfg->getOutEdges($source) as $branchEdge) { $branch = $branchEdge->getType(); $newScope = $output; switch ($branch) { case GraphEdge::TYPE_ON_TRUE: if ($source instanceof \PHPParser_Node_Stmt_Foreach) { $informed = $this->traverse($source->expr, $output->createChildFlowScope()); $exprType = $this->getType($source->expr); if (null !== $source->keyVar && $source->keyVar instanceof \PHPParser_Node_Expr_Variable) { $keyType = null; if ($exprType->isArrayType()) { $keyType = $exprType->toMaybeArrayType()->getKeyType(); } // If we do not have the precise key type available, we can always // assume it to be either a string, or an integer. $this->redeclareSimpleVar($informed, $source->keyVar, $keyType ?: $this->typeRegistry->getNativeType('generic_array_key')); } $valueType = $this->typeRegistry->getNativeType('unknown'); if ($exprType->isArrayType()) { $valueType = $exprType->toMaybeArrayType()->getElementType(); } else if ($exprType->toMaybeObjectType()) { $valueType = $exprType->toMaybeObjectType()->getTraversableElementType(); } $source->valueVar->setAttribute('type', $valueType); $this->redeclareSimpleVar($informed, $source->valueVar, $valueType); $newScope = $informed; break; } // FALL THROUGH case GraphEdge::TYPE_ON_FALSE: if (null === $condition) { $condition = NodeUtil::getConditionExpression($source); if (null === $condition && $source instanceof \PHPParser_Node_Stmt_Case // Do ignore DEFAULT statements. && null !== $source->cond) { $condition = $source; // conditionFlowScope is cached from previous iterations of the loop if (null === $conditionFlowScope) { $conditionFlowScope = $this->traverse($source->cond, $output->createChildFlowScope()); } } } if (null !== $condition) { if ($condition instanceof \PHPParser_Node_Expr_BooleanAnd || $condition instanceof \PHPParser_Node_Expr_LogicalAnd || $condition instanceof \PHPParser_Node_Expr_BooleanOr || $condition instanceof \PHPParser_Node_Expr_LogicalOr) { // When handling the short-circuiting binary operators, the outcome scope on true can be // different than the outcome scope on false. // // TODO: // The "right" way to do this is to carry the known outcome all the way through the // recursive traversal, so that we can construct a different flow scope based on the outcome. // However, this would require a bunch of code and a bunch of extra computation for an edge // case. This seems to be a "good enough" approximation. // conditionOutcomes is cached from previous iterations of the loop. if (null === $conditionOutcomes) { $conditionOutcomes = ($condition instanceof \PHPParser_Node_Expr_BooleanAnd || $condition instanceof \PHPParser_Node_Expr_LogicalAnd) ? $this->traverseAnd($condition, $output->createChildFlowScope()) : $this->traverseOr($condition, $output->createChildFlowScope()); } $newScope = $this->reverseInterpreter->getPreciserScopeKnowingConditionOutcome( $condition, $conditionOutcomes->getOutcomeFlowScope( $condition, $branch === GraphEdge::TYPE_ON_TRUE), $branch === GraphEdge::TYPE_ON_TRUE); } else { // conditionFlowScope is cached from previous iterations of the loop. if (null === $conditionFlowScope) { // In case of a FOR loop, $condition might be an array of expressions. PHP will execute // all expressions, but only the last one is used to determine the expression outcome. if (is_array($condition)) { $conditionFlowScope = $output->createChildFlowScope(); foreach ($condition as $cond) { $conditionFlowScope = $this->traverse($cond, $conditionFlowScope); } } else { $conditionFlowScope = $this->traverse($condition, $output->createChildFlowScope()); } } // See above comment regarding the handling of FOR loops. $relevantCondition = $condition; if (is_array($condition)) { $relevantCondition = end($condition); } $newScope = $this->reverseInterpreter->getPreciserScopeKnowingConditionOutcome( $relevantCondition, $conditionFlowScope, $branch === GraphEdge::TYPE_ON_TRUE); } } break; } if (null === $newScope) { throw new \LogicException('$newScope must not be null for source '.get_class($source).' and branch '.GraphEdge::getLiteral($branch).'.'); } $result[] = $newScope->optimize(); } return $result; } private function traverse(\PHPParser_Node $node, LinkedFlowScope $scope) { if (null !== $docComment = $node->getDocComment()) { foreach ($this->commentParser->getTypesFromInlineComment($docComment) as $name => $type) { $scope->inferSlotType($name, $type); } } switch (true) { case $node instanceof \PHPParser_Node_Expr_Clone: $scope = $this->traverseClone($node, $scope); break; case $node instanceof \PHPParser_Node_Expr_Assign: case $node instanceof \PHPParser_Node_Expr_AssignRef: $scope = $this->traverseAssign($node, $scope); break; case $node instanceof \PHPParser_Node_Expr_AssignList: $scope = $this->traverseAssignList($node, $scope); break; case $node instanceof \PHPParser_Node_Expr_StaticPropertyFetch: case $node instanceof \PHPParser_Node_Expr_PropertyFetch: $scope = $this->traverseGetProp($node, $scope); break; case $node instanceof \PHPParser_Node_Expr_LogicalAnd: case $node instanceof \PHPParser_Node_Expr_BooleanAnd: $scope = $this->traverseAnd($node, $scope)->getJoinedFlowScope() ->createChildFlowScope(); break; case $node instanceof \PHPParser_Node_Expr_Array: $scope = $this->traverseArray($node, $scope); break; case $node instanceof \PHPParser_Node_Expr_LogicalOr: case $node instanceof \PHPParser_Node_Expr_BooleanOr: $scope = $this->traverseOr($node, $scope)->getJoinedFlowScope() ->createChildFlowScope(); break; case $node instanceof \PHPParser_Node_Expr_Ternary: $scope = $this->traverseTernary($node, $scope); break; case $node instanceof \PHPParser_Node_Expr_FuncCall: case $node instanceof \PHPParser_Node_Expr_MethodCall: case $node instanceof \PHPParser_Node_Expr_StaticCall: $scope = $this->traverseCall($node, $scope); break; case $node instanceof \PHPParser_Node_Expr_New: $scope = $this->traverseNew($node, $scope); break; case $node instanceof \PHPParser_Node_Expr_UnaryPlus: case $node instanceof \PHPParser_Node_Expr_UnaryMinus: $scope = $this->traverseUnaryPlusMinus($node, $scope); break; case $node instanceof \PHPParser_Node_Expr_BooleanNot: $scope = $this->traverse($node->expr, $scope); $node->setAttribute('type', $this->typeRegistry->getNativeType('boolean')); break; case $node instanceof \PHPParser_Node_Expr_Identical: case $node instanceof \PHPParser_Node_Expr_Equal: case $node instanceof \PHPParser_Node_Expr_Greater: case $node instanceof \PHPParser_Node_Expr_GreaterOrEqual: case $node instanceof \PHPParser_Node_Expr_NotEqual: case $node instanceof \PHPParser_Node_Expr_NotIdentical: case $node instanceof \PHPParser_Node_Expr_Smaller: case $node instanceof \PHPParser_Node_Expr_SmallerOrEqual: case $node instanceof \PHPParser_Node_Expr_LogicalXor: case $node instanceof \PHPParser_Node_Expr_Empty: case $node instanceof \PHPParser_Node_Expr_Cast_Bool: case $node instanceof \PHPParser_Node_Expr_Isset: case $node instanceof \PHPParser_Node_Expr_Instanceof: $scope = $this->traverseChildren($node, $scope); $node->setAttribute('type', $this->typeRegistry->getNativeType('boolean')); break; case $node instanceof \PHPParser_Node_Expr_Cast_Int: case $node instanceof \PHPParser_Node_Expr_Mod: case $node instanceof \PHPParser_Node_Expr_BitwiseXor: case $node instanceof \PHPParser_Node_Expr_BitwiseOr: case $node instanceof \PHPParser_Node_Expr_BitwiseNot: case $node instanceof \PHPParser_Node_Expr_BitwiseAnd: case $node instanceof \PHPParser_Node_Expr_ShiftLeft: case $node instanceof \PHPParser_Node_Expr_ShiftRight: $scope = $this->traverseChildren($node, $scope); $node->setAttribute('type', $this->typeRegistry->getNativeType('integer')); break; case $node instanceof \PHPParser_Node_Expr_Cast_Double: $scope = $this->traverseChildren($node, $scope); $node->setAttribute('type', $this->typeRegistry->getNativeType('double')); break; case $node instanceof \PHPParser_Node_Expr_AssignPlus: $scope = $this->traversePlus($node, $node->var, $node->expr, $scope); break; case $node instanceof \PHPParser_Node_Expr_Plus: $scope = $this->traversePlus($node, $node->left, $node->right, $scope); break; case $node instanceof \PHPParser_Node_Expr_AssignDiv: case $node instanceof \PHPParser_Node_Expr_AssignMinus: case $node instanceof \PHPParser_Node_Expr_AssignMul: case $node instanceof \PHPParser_Node_Expr_Div: case $node instanceof \PHPParser_Node_Expr_Minus: case $node instanceof \PHPParser_Node_Expr_Mul: $scope = $this->traverseChildren($node, $scope); if (isset($node->left, $node->right)) { $left = $node->left; $right = $node->right; } else if (isset($node->var, $node->expr)) { $left = $node->var; $right = $node->expr; } else { throw new \LogicException('Previous statements were exhaustive.'); } if ($this->getType($left)->isIntegerType() && $this->getType($right)->isIntegerType()) { $type = $this->typeRegistry->getNativeType('integer'); } else if ($this->getType($left)->isDoubleType() || $this->getType($right)->isDoubleType()) { $type = $this->typeRegistry->getNativeType('double'); } else { $type = $this->typeRegistry->getNativeType('number'); } $node->setAttribute('type', $type); $this->updateScopeForTypeChange($scope, $left, $this->getType($left), $type); break; case $node instanceof \PHPParser_Node_Expr_PostDec: case $node instanceof \PHPParser_Node_Expr_PostInc: case $node instanceof \PHPParser_Node_Expr_PreDec: case $node instanceof \PHPParser_Node_Expr_PreInc: $scope = $this->traverseChildren($node, $scope); if ($this->getType($node->var)->isIntegerType()) { $node->setAttribute('type', $this->typeRegistry->getNativeType('integer')); } else if ($this->getType($node->var)->isDoubleType()) { $node->setAttribute('type', $this->typeRegistry->getNativeType('double')); } else { $node->setAttribute('type', $this->typeRegistry->getNativeType('number')); } break; case $node instanceof \PHPParser_Node_Expr_Cast_String: case $node instanceof \PHPParser_Node_Expr_Concat: $scope = $this->traverseChildren($node, $scope); $node->setAttribute('type', $this->typeRegistry->getNativeType('string')); break; case $node instanceof \PHPParser_Node_Stmt_Return: $scope = $this->traverseReturn($node, $scope); break; case $node instanceof \PHPParser_Node_Expr_Variable: $scope = $this->traverseVariable($node, $scope); break; case $node instanceof \PHPParser_Node_Stmt_Echo: case $node instanceof \PHPParser_Node_Expr_ArrayItem: case $node instanceof \PHPParser_Node_Stmt_Throw: $scope = $this->traverseChildren($node, $scope); break; case $node instanceof \PHPParser_Node_Arg: $scope = $this->traverseChildren($node, $scope); $node->setAttribute('type', $node->value->getAttribute('type')); break; case $node instanceof \PHPParser_Node_Stmt_Switch: $scope = $this->traverse($node->cond, $scope); break; case $node instanceof \PHPParser_Node_Stmt_Catch: $scope = $this->traverseCatch($node, $scope); break; case $node instanceof \PHPParser_Node_Expr_ArrayDimFetch: $scope = $this->traverseArrayDimFetch($node, $scope); break; } return $scope; } private function traversePlus(\PHPParser_Node_Expr $plusExpr, \PHPParser_Node_Expr $left, \PHPParser_Node_Expr $right, LinkedFlowScope $scope) { $scope = $this->traverseChildren($plusExpr, $scope); $leftType = $this->getType($left); $rightType = $this->getType($right); // If both sides are unknown, we leave the outcome at unknown type. The alternative would be to assume the union, // integer, double, and array types, which would most likely never be the case in the real world, and just result // in weird error messages without any real benefit. if ($leftType->isUnknownType() && $rightType->isUnknownType()) { $resultType = $this->typeRegistry->getNativeType('unknown'); } else { $joinTypes = array(); if ( ! $leftType->isUnknownType()) { $joinTypes[] = $leftType; } if ( ! $rightType->isUnknownType()) { $joinTypes[] = $rightType; } $joinedType = $this->typeRegistry->createUnionType($joinTypes); switch (true) { // If only integer is available, then that is the resulting type. // In rare circumstances, we might get a double even if both input types // are integers, namely if there is an overflow. However, this seems // like an appropriate approximation. case $joinedType->isIntegerType(): $resultType = $joinedType; break; // If one, or both types are doubles, then the resulting type is a double // as whatever is not a double will be cast to one. case $joinedType->isSubtypeOf($this->typeRegistry->createUnionType(array('integer', 'double'))): $resultType = $this->typeRegistry->getNativeType('double'); break; // If all types are scalars, we assume the result to be either an integer, or a double. // This is in line with Zend engine's behavior which tries to cast the scalar to a number. case $joinedType->isSubtypeOf($this->typeRegistry->createUnionType(array('scalar', 'null'))): $resultType = $this->typeRegistry->getNativeType('number'); break; // If we reach this, it get's tricky as array types might be involved :/ default: // If we do have something else than an array, then we go // assume the result type to be unknown. Everything else, would // be a weird combination of types which should never happen // in the real world and if we indeed run into this in real // code making anything more sophisticated here would also not // help us in any way. if ( ! $joinedType->isSubtypeOf($this->typeRegistry->getNativeType('array'))) { $resultType = $this->typeRegistry->getNativeType('unknown'); } else if ($joinedType->isArrayType()) { $resultType = $joinedType; } else if ($joinedType->isUnionType()) { $keyTypes = array(); $elementTypes = array(); foreach ($joinedType->getAlternates() as $alt) { if ($alt->isNoType()) { continue; } if ( ! $alt->isArrayType()) { throw new \LogicException(sprintf('All alternates must be arrays, but got "%s".', $alt)); } $keyTypes[] = $alt->getKeyType(); $elementType = $alt->getElementType(); if ( ! $elementType->isUnknownType()) { $elementTypes[] = $elementType; } } $keyType = empty($keyTypes) ? $this->typeRegistry->getNativeType('generic_array_key') : $this->typeRegistry->createUnionType($keyTypes); $elementType = empty($elementTypes) ? $this->typeRegistry->getNativeType('generic_array_value') : $this->typeRegistry->createUnionType($elementTypes); $resultType = $this->typeRegistry->getArrayType($elementType, $keyType); } else { throw new \LogicException(sprintf('The previous conditions were exhaustive, but got joined type of "%s".', $joinedType)); } } } $plusExpr->setAttribute('type', $resultType); $this->updateScopeForTypeChange($scope, $left, $leftType, $resultType); return $scope; } private function traverseClone(\PHPParser_Node_Expr_Clone $node, LinkedFlowScope $scope) { $scope = $this->traverse($node->expr, $scope); if ($type = $this->getType($node->expr)) { $type = $type->restrictByNotNull(); if ($type instanceof NamedType || $type->isObjectType()) { $node->setAttribute('type', $type); } else if ($type->isUnionType()) { $node->setAttribute('type', $type); } else { $node->setAttribute('type', $this->typeRegistry->getNativeType('object')); } } else { $node->setAttribute('type', $this->typeRegistry->getNativeType('object')); } return $scope; } private function traverseCall(\PHPParser_Node $node, LinkedFlowScope $scope) { assert($node instanceof \PHPParser_Node_Expr_MethodCall || $node instanceof \PHPParser_Node_Expr_FuncCall || $node instanceof \PHPParser_Node_Expr_StaticCall); $scope = $this->traverseChildren($node, $scope); // Propagate type for constants if (NodeUtil::isConstantDefinition($node)) { $constantName = $node->args[0]->value->value; if ($constant = $this->typeRegistry->getConstant($constantName)) { $constant->setPhpType($this->getType($node->args[1]->value)); } } // If the assert function is called inside a block node, we are just going to assume // that some sort of exception is thrown if the assert fails (and it will not silently // be ignored). // TODO: This needs to be extracted as a general concept where we can have different // effects for functions/methods. For example, array_pop affects the known item // types of arrays on which it is called. if ($node->getAttribute('parent') instanceof BlockNode && NodeUtil::isMaybeFunctionCall($node, 'assert') && isset($node->args[0])) { $scope = $this->reverseInterpreter->getPreciserScopeKnowingConditionOutcome($node->args[0]->value, $scope, true); } $returnType = null; if (null !== $function = $this->typeRegistry->getCalledFunctionByNode($node)) { $node->setAttribute('returns_by_ref', $function->isReturnByRef()); $argValues = $argTypes = array(); foreach ($node->args as $arg) { $argValues[] = $arg->value; $argTypes[] = $this->getType($arg); } if ($function instanceof ContainerMethodInterface) { $objType = $function->getContainer(); $maybeReturnType = $function->getReturnType(); if (null !== $restrictedType = $this->methodInterpreter->getPreciserMethodReturnTypeKnowingArguments($function, $argValues, $argTypes)) { $maybeReturnType = $restrictedType; } $returnType = $this->updateThisReference( $node instanceof \PHPParser_Node_Expr_MethodCall ? $node->var : $node->class, $scope->getTypeOfThis(), $objType, $maybeReturnType); } else if ($function instanceof GlobalFunction) { if (null !== $restrictedType = $this->functionInterpreter->getPreciserFunctionReturnTypeKnowingArguments($function, $argValues, $argTypes)) { $returnType = $restrictedType; } else if (null === $returnType) { $returnType = $function->getReturnType(); } } else { throw new \LogicException(sprintf('Unknown function "%s".', get_class($function))); } } $node->setAttribute('type', $returnType ?: $this->typeRegistry->getNativeType('unknown')); return $scope; } /** * Updates the context of returned ThisType types. * * ```php * class A { * public function returnsThis() { * return $this; // this<A> * } * } * * class B extends A { * public function returnsSomething() { * $rs = $this->returnsThis(); * * return $rs; // this<B> * } * * public function returnsSomethingElse() * { * $rs = parent::returnsThis(); * * return $rs; // this<B> * } * } * * class C extends B { } * * $c = new C(); * $c->returnsThis(); // object<C> * $c->returnsSomething(); // object<C> * ``` * * We have two basic cases: * * 1. The called node refers to the current scope ($this->, self::, * parent::, static::, or SuperTypeName::). * 2. The node was called from the "outside" $foo->...(). * * In the first case, we need to preserve the wrapping with ThisType with * an updated creation context. In the second case, we have to unwrap the * ThisType. * * @param \PHPParser_Node $calledNode * @param PhpType $thisType Type of the current context * @param PhpType $calledType Type of the $calledNode * @param PhpType $returnType * * @return PhpType */ private function updateThisReference(\PHPParser_Node $calledNode, PhpType $thisType = null, PhpType $calledType, PhpType $returnType = null) { // Delays execution until necessary. $needsWrapping = function() use ($calledNode, $thisType, $calledType) { if (null === $thisType) { return false; } switch (true) { case $calledNode instanceof \PHPParser_Node_Expr_Variable: return 'this' === $calledNode->name; case $calledNode instanceof \PHPParser_Node_Name: if (in_array(strtolower(implode("\\", $calledNode->parts)), array('self', 'static', 'parent'), true)) { return true; } // This handles the following case: // // class A { public function foo() { return $this; } } // class B extends A { public function bar() { return A::foo(); } } // $x = (new B())->bar(); // // $x is resolved to object<B>. if (null !== $thisType && $thisType->isSubtypeOf($calledType)) { return true; } return false; default: return false; } }; switch (true) { case $returnType instanceof ThisType: return $needsWrapping() ? $this->typeRegistry->getThisType($thisType) : $calledType; case $returnType instanceof UnionType: $types = array(); foreach ($returnType->getAlternates() as $alt) { if ($alt instanceof ThisType) { $types[] = $needsWrapping() ? $this->typeRegistry->getThisType($thisType) : $calledType; continue; } $types[] = $alt; } return $this->typeRegistry->createUnionType($types); default: return $returnType; } } /** * On the first run of the type inference engine, arrays always have * the generic array type at this point. This is assigned by the * {@see AbstractScopeBuilder::attachLiteralTypes}. * * We try to make this more specific by introspecting the values of * the items which are assigned. * * @param \PHPParser_Node_Expr_Array $node * @param LinkedFlowScope $scope * * @return LinkedFlowScope */ private function traverseArray(\PHPParser_Node_Expr_Array $node, LinkedFlowScope $scope) { $keyTypes = $elementTypes = $itemTypes = array(); $lastNumericKey = -1; $containsDynamicKey = false; foreach ($node->items as $item) { assert($item instanceof \PHPParser_Node_Expr_ArrayItem); $scope = $this->traverse($item, $scope); if (null === $item->key) { $keyTypes[] = 'integer'; } else if (null !== $type = $item->key->getAttribute('type')) { $keyTypes[] = $type; } else { // If the key type is not available, then we will just assume both // possible types. It's not that bad after all. $keyTypes[] = 'string'; $keyTypes[] = 'integer'; } $itemName = null; $keyValue = NodeUtil::getValue($item->key); if (null === $item->key && ! $containsDynamicKey) { $itemName = ++$lastNumericKey; } else if ($keyValue->isDefined()) { // We cast everything to a string (even integers), and then process // both cases: 1) numeric key, and 2) anything else $keyValue = (string) $keyValue->get(); if (ctype_digit($keyValue)) { // Case 1) $itemName = (integer) $keyValue; // PHP will always use the next highest number starting from the // greatest numeric value that the array contains when no explicit // key has been defined; so, we need to keep track of this. if ($itemName > $lastNumericKey) { $lastNumericKey = $itemName; } } else { // Case 2) $itemName = $keyValue; } } else { $containsDynamicKey = true; } if (null !== $type = $item->value->getAttribute('type')) { if (null !== $itemName) { $itemTypes[$itemName] = $type; } $elementTypes[] = $type; } } $node->setAttribute('type', $this->typeRegistry->getArrayType( $elementTypes ? $this->typeRegistry->createUnionType($elementTypes) : null, $keyTypes ? $this->typeRegistry->createUnionType($keyTypes) : null, $itemTypes)); return $scope; } private function traverseArrayDimFetch(\PHPParser_Node_Expr_ArrayDimFetch $node, LinkedFlowScope $scope) { $scope = $this->traverseChildren($node, $scope); $varType = $this->getType($node->var); if ($varType->isStringType()) { $node->setAttribute('type', $this->typeRegistry->getNativeType('string')); } else if ($varType->isArrayType()) { $itemType = NodeUtil::getValue($node->dim) ->flatMap([$varType, 'getItemType']) ->getOrCall([$varType, 'getElementType']); $node->setAttribute('type', $itemType); } else { $node->setAttribute('type', $this->typeRegistry->getNativeType('unknown')); } return $this->dereferencePointer($node->var, $scope); } private function traverseCatch(\PHPParser_Node_Stmt_Catch $node, LinkedFlowScope $scope) { $className = implode("\\", $node->type->parts); $type = $this->typeRegistry->getClassOrCreate($className); $scope->inferSlotType($node->var, $type); return $scope; } /** * Traverse a return value. */ private function traverseReturn(\PHPParser_Node_Stmt_Return $node, LinkedFlowScope $scope) { $scope = $this->traverseChildren($node, $scope); if (null === $node->expr) { $node->setAttribute('type', $this->typeRegistry->getNativeType('null')); } else { $node->setAttribute('type', $this->getType($node->expr)); } return $scope; } private function traverseVariable(\PHPParser_Node_Expr_Variable $node, LinkedFlowScope $scope) { if ('this' === $node->name) { if (null === $scope->getTypeOfThis()) { $node->setAttribute('type', $this->typeRegistry->getNativeType('none')); return $scope; } $node->setAttribute('type', $this->typeRegistry->getThisType($scope->getTypeOfThis())); return $scope; } if (is_string($node->name)) { $slot = $scope->getSlot($node->name); if ($slot && $type = $slot->getType()) { $node->setAttribute('type', $type); } } else { $scope = $this->traverseChildren($node, $scope); } return $scope; } private function traverseUnaryPlusMinus(\PHPParser_Node $node, LinkedFlowScope $scope) { $scope = $this->traverse($node->expr, $scope); $exprType = $node->expr->getAttribute('type'); $type = null; if ($exprType) { if ($exprType->isIntegerType()) { $type = $this->typeRegistry->getNativeType('integer'); } else if ($exprType->isDoubleType()) { $type = $this->typeRegistry->getNativeType('double'); } } $node->setAttribute('type', $type ?: $this->typeRegistry->getNativeType('number')); return $scope; } private function traverseNew(\PHPParser_Node_Expr_New $node, LinkedFlowScope $scope) { $scope = $this->traverse($node->class, $scope); $type = null; if ($node->class instanceof \PHPParser_Node_Name) { $type = $node->class->getAttribute('type'); } if (null === $type) { $type = $this->typeRegistry->getNativeType('object'); } $node->setAttribute('type', $type); foreach ($node->args as $arg) { $scope = $this->traverse($arg, $scope); } return $scope; } private function traverseAnd(\PHPParser_Node $node, LinkedFlowScope $scope) { return $this->traverseShortCircuitingBinOp($node, $scope, true); } private function traverseTernary(\PHPParser_Node_Expr_Ternary $n, LinkedFlowScope $scope) { if (null === $n->if) { // $a ?: $b $condition = new \PHPParser_Node_Expr_NotIdentical(new \PHPParser_Node_Expr_ConstFetch(new \PHPParser_Node_Name(array('null'))), $n->cond); $trueNode = $n->cond; $falseNode = $n->else; } else { // $a ? $b : $c $condition = $n->cond; $trueNode = $n->if; $falseNode = $n->else; } // verify the condition $scope = $this->traverse($condition, $scope); // reverse abstract interpret the condition to produce two new scopes $trueScope = $this->reverseInterpreter->getPreciserScopeKnowingConditionOutcome($condition, $scope, true); $falseScope = $this->reverseInterpreter->getPreciserScopeKnowingConditionOutcome($condition, $scope, false); // traverse the true node with the trueScope $this->traverse($trueNode, $trueScope->createChildFlowScope()); // traverse the false node with the falseScope $this->traverse($falseNode, $falseScope->createChildFlowScope()); // meet true and false node's types and assign $trueType = $trueNode->getAttribute('type'); $falseType = $falseNode->getAttribute('type'); // For statements such as $a ?: $b, the true type ($a) can never be null. if (null === $n->if && $trueType) { $trueType = $trueType->restrictByNotNull(); } if (null !== $trueType && null !== $falseType) { $n->setAttribute('type', $trueType->getLeastSupertype($falseType)); } else { $n->setAttribute('type', null); } return $scope->createChildFlowScope(); } private function traverseOr(\PHPParser_Node $n, LinkedFlowScope $scope) { return $this->traverseShortCircuitingBinOp($n, $scope, false); } private function traverseShortCircuitingBinOp(\PHPParser_Node $node, LinkedFlowScope $scope, $condition) { $left = $node->left; $right = $node->right; // Type the left node. $leftLiterals = $this->traverseWithinShortCircuitingBinOp($left, $scope->createChildFlowScope()); $leftType = $left->getAttribute('type'); // As these operations are short circuiting, we can reverse interpreter the left node as we know the // outcome to its evaluation if we are ever going to reach the right node. $rightScope = $this->reverseInterpreter->getPreciserScopeKnowingConditionOutcome($left, $leftLiterals->getOutcomeFlowScope($left, $condition), $condition); // Now, type the right node in the updated scope. $rightLiterals = $this->traverseWithinShortCircuitingBinOp($right, $rightScope->createChildFlowScope()); $rightType = $right->getAttribute('type'); if (null === $leftType || null === $rightType) { return new BooleanOutcomePair( $this, array(true, false), array(true, false), $leftLiterals->getJoinedFlowScope(), $rightLiterals->getJoinedFlowScope()); } // In PHP, binary operations are always of boolean type. $node->setAttribute('type', $this->typeRegistry->getNativeType('boolean')); if ($leftLiterals->toBooleanOutcomes === array(!$condition)) { // Use the restricted left type, since the right side never gets evaluated. return $leftLiterals; } // Use the join of the restricted left type knowing the outcome of the // ToBoolean predicate of the right type. return BooleanOutcomePair::fromPairs($this, $leftLiterals, $rightLiterals, $condition); } private function traverseWithinShortCircuitingBinOp(\PHPParser_Node $node, LinkedFlowScope $scope) { if ($node instanceof \PHPParser_Node_Expr_BooleanAnd) { return $this->traverseAnd($node, $scope); } if ($node instanceof \PHPParser_Node_Expr_BooleanOr) { return $this->traverseOr($node, $scope); } $scope = $this->traverse($node, $scope); if (null === $type = $node->getAttribute('type')) { return new BooleanOutcomePair($this, array(true, false), array(true, false), $scope, $scope); } return new BooleanOutcomePair($this, $type->getPossibleOutcomesComparedToBoolean(), $this->typeRegistry->getNativeType('boolean')->isSubTypeOf($type) ? array(true, false) : array(), $scope, $scope); } private function traverseGetProp(\PHPParser_Node $node, LinkedFlowScope $scope) { assert($node instanceof \PHPParser_Node_Expr_PropertyFetch || $node instanceof \PHPParser_Node_Expr_StaticPropertyFetch); $objNode = $node instanceof \PHPParser_Node_Expr_PropertyFetch ? $node->var : $node->class; $property = $node->name; $scope = $this->traverseChildren($node, $scope); if (is_string($property)) { $node->setAttribute('type', $this->getPropertyType($objNode->getAttribute('type'), $property, $node, $scope)); } else { $node->setAttribute('type', $this->typeRegistry->getNativeType(TypeRegistry::NATIVE_UNKNOWN)); } return $this->dereferencePointer($objNode, $scope); } private function traverseAssign(\PHPParser_Node_Expr $node, LinkedFlowScope $scope) { assert($node instanceof \PHPParser_Node_Expr_Assign || $node instanceof \PHPParser_Node_Expr_AssignRef); $scope = $this->traverseChildren($node, $scope); $leftType = $node->var->getAttribute('type'); $rightType = $this->getType($node->expr); $node->setAttribute('type', $rightType); $castTypes = $this->commentParser->getTypesFromInlineComment($node->getDocComment()); $this->updateScopeForTypeChange($scope, $node->var, $leftType, $rightType, $castTypes); return $scope; } private function traverseAssignList(\PHPParser_Node_Expr_AssignList $node, LinkedFlowScope $scope) { $scope = $this->traverse($node->expr, $scope); $exprType = $this->getType($node->expr); $isArray = $exprType->isArrayType(); $checkedUnknown = $this->typeRegistry->getNativeType('unknown_checked'); $castTypes = $this->commentParser->getTypesFromInlineComment($node->getDocComment()); foreach ($node->vars as $i => $var) { if (null === $var) { continue; } $newType = $isArray ? $exprType->getItemType($i)->getOrElse($checkedUnknown) : $checkedUnknown; $this->updateScopeForTypeChange($scope, $var, null, $newType, $castTypes); } return $scope; } private function traverseChildren(\PHPParser_Node $node, LinkedFlowScope $scope) { foreach ($node as $subNode) { if (is_array($subNode)) { foreach ($subNode as $aSubNode) { $scope = $this->traverse($aSubNode, $scope); } } else if ($subNode instanceof \PHPParser_Node) { $scope = $this->traverse($subNode, $scope); } } return $scope; } private function dereferencePointer(\PHPParser_Node $node, LinkedFlowScope $scope) { if ($this->hasQualifiedName($node)) { if ($type = $node->getAttribute('type')) { $narrowed = $type->restrictByNotNull(); if ($type !== $narrowed) { $scope = $this->narrowScope($scope, $node, $narrowed); } } } return $scope; } private function narrowScope(LinkedFlowScope $scope, \PHPParser_Node $node, PhpType $narrowed) { $scope = $scope->createChildFlowScope(); if ($node instanceof \PHPParser_Node_Expr_PropertyFetch || $node instanceof \PHPParser_Node_Expr_StaticPropertyFetch) { $scope->inferQualifiedSlot($node, $this->getQualifiedName($node), $this->getType($node), $narrowed); } else { $this->redeclareSimpleVar($scope, $node, $narrowed); } return $scope; } private function redeclareSimpleVar(LinkedFlowScope $scope, \PHPParser_Node $nameNode, PhpType $varType = null) { if (!self::hasQualifiedName($nameNode)) { return; } if (null === $varType) { $varType = $this->typeRegistry->getNativeType('unknown'); } $varName = self::getQualifiedName($nameNode); $scope->inferSlotType($varName, $varType); } private function updateScopeForTypeChange(LinkedFlowScope $scope, \PHPParser_Node $left, PhpType $leftType = null, PhpType $resultType = null, array $castTypes = array()) { assert('null !== $resultType'); switch (true) { case $left instanceof \PHPParser_Node_Expr_Variable && is_string($left->name): $var = $this->syntacticScope->getVar($left->name); // If an explicit type has been annotated for the variable, we // use this instead of whatever the type inference engine has found. if (isset($castTypes[$left->name])) { $resultType = $castTypes[$left->name]; } $this->redeclareSimpleVar($scope, $left, $resultType); $left->setAttribute('type', $resultType); if (null !== $var && $var->isTypeInferred()) { $oldType = $var->getType(); $newType = null === $oldType ? $resultType : $oldType->getLeastSupertype($resultType); $var->setType($newType); } break; case $left instanceof \PHPParser_Node_Expr_ArrayDimFetch: if ($left->var instanceof \PHPParser_Node_Expr_Variable && is_string($left->var->name)) { $varType = $this->getType($left->var); // If the variable type is not known yet, then it has not yet // been initialized. In such a case, it must be an array. if (null === $varType || $varType->isUnknownType()) { $this->redeclareSimpleVar($scope, $left->var, $this->getRefinedArrayType($this->typeRegistry->getNativeType('array'), $resultType, $left)); } else if ($varType->isArrayType()) { $this->redeclareSimpleVar($scope, $left->var, $this->getRefinedArrayType($varType, $resultType, $left)); } } else if (($left->var instanceof \PHPParser_Node_Expr_PropertyFetch || $left->var instanceof \PHPParser_Node_Expr_StaticPropertyFetch ) && null !== $qualifiedName = self::getQualifiedName($left->var)) { $bottomType = $this->getType($left->var); if (null === $bottomType || $bottomType->isUnknownType()) { $refinedArrayType = $this->getRefinedArrayType( $this->typeRegistry->getNativeType('array'), $resultType, $left); $scope->inferQualifiedSlot($left->var, $qualifiedName, $bottomType, $refinedArrayType); $left->setAttribute('type', $refinedArrayType); $this->ensurePropertyDefined($left->var, $refinedArrayType); } else if ($bottomType->isArrayType()) { $refinedArrayType = $this->getRefinedArrayType($bottomType, $resultType, $left); $scope->inferQualifiedSlot($left->var, $qualifiedName, $bottomType, $refinedArrayType); $left->setAttribute('type', $refinedArrayType); $this->ensurePropertyDefined($left->var, $refinedArrayType); } } break; case $left instanceof \PHPParser_Node_Expr_PropertyFetch: case $left instanceof \PHPParser_Node_Expr_StaticPropertyFetch: if (null === $qualifiedName = self::getQualifiedName($left)) { break; } $bottomType = $leftType ?: $this->typeRegistry->getNativeType('unknown'); $scope->inferQualifiedSlot($left, $qualifiedName, $bottomType, $resultType); $left->setAttribute('type', $resultType); $this->ensurePropertyDefined($left, $resultType); break; } } /** * Refines an array type with the information about the used key, and assigned element type. * * This also defines the type for the item key if available and non-dynamic. * * @param PhpType $varType * @param PhpType $resultType * @param \PHPParser_Node_Expr_ArrayDimFetch $node * * @return ArrayType */ private function getRefinedArrayType(PhpType $varType, PhpType $resultType, \PHPParser_Node_Expr_ArrayDimFetch $node) { $usedKeyType = $this->getKeyTypeForDimFetch($node); $keyType = $varType->getKeyType(); if ($keyType === $this->typeRegistry->getNativeType('generic_array_key')) { $refinedKeyType = $usedKeyType; } else { $refinedKeyType = $keyType->getLeastSupertype($usedKeyType); } $elementType = $varType->getElementType(); if ($elementType === $this->typeRegistry->getNativeType('generic_array_value')) { $refinedElementType = $resultType; } else { $refinedElementType = $elementType->getLeastSupertype($resultType); } $refinedType = $this->typeRegistry->getArrayType($refinedElementType, $refinedKeyType); // Infer the type of the key if a concrete value is available. NodeUtil::getValue($node->dim)->map(function($keyName) use (&$refinedType, $resultType) { $refinedType = $refinedType->inferItemType($keyName, $resultType); }); return $refinedType; } private function getKeyTypeForDimFetch(\PHPParser_Node_Expr_ArrayDimFetch $node) { if (null === $node->dim) { return $this->typeRegistry->getNativeType('integer'); } if ($type = $node->dim->getAttribute('type')) { return $type; } return $this->typeRegistry->getNativeType('generic_array_key'); } private function ensurePropertyDefined($left, $resultType) { if ($resultType->isUnknownType()) { return; } $property = $this->typeRegistry->getFetchedPropertyByNode($left); if (null !== $property) { assert($property instanceof ClassProperty); // Specifically ignore anything that is being set in a tearDown() method. // TODO: We should think about introducing a general concept for this which takes // inter procedural control flow into account. $scopeRoot = $this->syntacticScope->getRootNode(); if ( ! $scopeRoot instanceof BlockNode && ! $scopeRoot instanceof \PHPParser_Node_Expr_Closure) { $testCase = $this->typeRegistry->getClassOrCreate('PHPUnit_Framework_TestCase'); $method = $this->typeRegistry->getFunctionByNode($scopeRoot); if ($property->getDeclaringClassType()->isSubtypeOf($testCase) && (null !== $thisType = $this->syntacticScope->getTypeOfThis()) && $thisType->isSubtypeOf($testCase) && null !== $method && strtolower($method->getName()) === 'teardown') { return; } } if (null !== $type = $property->getPhpType()) { $newType = $this->typeRegistry->createUnionType(array($type, $resultType)); } else { $newType = $resultType; } $property->setPhpType($newType); if ($astNode = $property->getAstNode()) { $astNode->setAttribute('type', $newType); } } } /** * This method gets the PhpType from the Node argument and verifies that it is * present. If not type is present, it will be logged, and unknown is returned. * * @return PhpType */ private function getType(\PHPParser_Node $node) { $type = $node->getAttribute('type'); if (null === $type) { // Theoretically, we should never enter this branch because all // interesting nodes should have received a type by the scope builder, // or the type inference engine. It is not worth throwing an exception, // but we should at least log it, and fix it over time. $this->logger->debug(sprintf('Encountered untyped node "%s"; assuming unknown type.', get_class($node))); return $this->typeRegistry->getNativeType('unknown'); } return $type; } private function getPropertyType(PhpType $objType = null, $propName, \PHPParser_Node $n, LinkedFlowScope $scope) { // Check whether the scope contains inferred type information about the property, // or fallback to the wider property type if not available. Scopes could // contain information about properties if we have reverse interpreted // the property previously. $qualifiedName = self::getQualifiedName($n); $var = $scope->getSlot($qualifiedName); if (null !== $var && null !== $varType = $var->getType()) { if ($varType->equals($this->typeRegistry->getNativeType('unknown')) && $var !== $this->syntacticScope->getSlot($qualifiedName)) { // If the type of this qualified name has been checked in this scope, // then use CHECKED_UNKNOWN_TYPE instead to indicate that. // TODO: The checked unknown type has not really proved useful in // practice. Consider removing it entirely. return $this->typeRegistry->getNativeType('unknown_checked'); } return $varType; } $propertyType = null; if (null !== $objType && (null !== $objType = $objType->toMaybeObjectType()) && $objType instanceof Clazz && $objType->hasProperty($propName)) { $propertyType = $objType->getProperty($propName)->getPhpType(); } return $propertyType ?: $this->typeRegistry->getNativeType('unknown'); } }
Ocramius/php-analyzer
src/Scrutinizer/PhpAnalyzer/DataFlow/TypeInference/TypeInference.php
PHP
apache-2.0
62,063
//***************************************************************************** // @@@ START COPYRIGHT @@@ // // 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. // // @@@ END COPYRIGHT @@@ //***************************************************************************** #include "PrivMgrComponentOperations.h" #include "PrivMgrMD.h" #include "PrivMgrMDTable.h" #include "PrivMgrComponents.h" #include "PrivMgrComponentPrivileges.h" #include <string> #include <cstdio> #include "ComSmallDefs.h" // sqlcli.h included because ExExeUtilCli.h needs it (and does not include it!) #include "sqlcli.h" #include "ExExeUtilCli.h" #include "ComQueue.h" #include "ComDiags.h" // CmpCommon.h contains STMTHEAP declaration #include "CmpCommon.h" #include "CmpContext.h" #include "CmpDDLCatErrorCodes.h" #include "ComUser.h" namespace ComponentOperations { // ***************************************************************************** // * Class: MyRow // * Description: This class represents a component operations row which contains: // * - UID of the component // * - 2 character code of the component operation // * - ANSI name of the component operation // * - Description of the component operation // * // * A component operation can be uniquely identified by its component UID // * and either its ANSI name or its 2 character code. // ***************************************************************************** class MyRow : public PrivMgrMDRow { public: // ------------------------------------------------------------------- // Constructors and destructors: // ------------------------------------------------------------------- MyRow(std::string tableName) : PrivMgrMDRow(tableName, COMPONENT_OPERATIONS_ENUM), componentUID_(0) { }; MyRow(const MyRow &other) : PrivMgrMDRow(other) { componentUID_ = other.componentUID_; operationCode_ = other.operationCode_; operationName_ = other.operationName_; operationType_ = other.operationType_; operationDescription_ = other.operationDescription_; }; virtual ~MyRow() {}; inline void clear() {componentUID_ = 0;}; bool lookupByCode( const int64_t componentUID, const std::string & operationCode, std::string & operationName, PrivMgrComponentOperations::OperationType & operationType, std::string & operationDescription); bool lookupByName( const int64_t componentUID, const std::string & operationName, std::string & operationCode, PrivMgrComponentOperations::OperationType & operationType, std::string & operationDescription); // ------------------------------------------------------------------- // Data Members: // ------------------------------------------------------------------- // From COMPONENT_OPERATIONS int64_t componentUID_; std::string operationCode_; std::string operationName_; PrivMgrComponentOperations::OperationType operationType_; std::string operationDescription_; private: MyRow(); }; // ***************************************************************************** // * Class: MyTable // * Description: This class represents the COMPONENT_OPERATIONS table containing: // * - the fully qualified name of the table // * // * A component operation can be uniquely identified by a component UID and // * either the name of the operation or the operation code. // ***************************************************************************** class MyTable : public PrivMgrMDTable { public: MyTable( const std::string & tableName, PrivMgrTableEnum myTableEnum, ComDiagsArea * pDiags) : PrivMgrMDTable(tableName,COMPONENT_OPERATIONS_ENUM, pDiags), lastRowRead_(tableName) {}; inline void clear() { lastRowRead_.clear(); }; PrivStatus fetchByCode( const int64_t componentUID, const std::string & operationCode, MyRow & row); PrivStatus fetchByName( const std::string & componentUIDString, const std::string & operationName, MyRow & row); PrivStatus fetchByName( const int64_t componentUID, const std::string & operationName, MyRow & row); virtual PrivStatus insert(const PrivMgrMDRow &row); virtual PrivStatus selectWhereUnique( const std::string & whereClause, PrivMgrMDRow & row); PrivStatus selectWhere( const std::string & whereClause, std::vector<MyRow *> &rowList); PrivStatus update( const std::string &setClause, const std::string &whereClause); private: MyTable(); void setRow(OutputInfo *pCliRow, MyRow &rowOut); MyRow lastRowRead_; }; }//End namespace ComponentOperations using namespace ComponentOperations; // ***************************************************************************** // PrivMgrComponentOperations methods // ***************************************************************************** // ----------------------------------------------------------------------- // Construct a PrivMgrComponentOperations object for a new component operation. // ----------------------------------------------------------------------- PrivMgrComponentOperations::PrivMgrComponentOperations( const std::string & metadataLocation, ComDiagsArea * pDiags) : PrivMgr(metadataLocation, pDiags), fullTableName_(metadataLocation_ + "." + PRIVMGR_COMPONENT_OPERATIONS), myTable_(*new MyTable(fullTableName_,COMPONENT_OPERATIONS_ENUM, pDiags)) { }; // ----------------------------------------------------------------------- // Copy constructor // ----------------------------------------------------------------------- PrivMgrComponentOperations::PrivMgrComponentOperations(const PrivMgrComponentOperations &other) : PrivMgr(other), myTable_(*new MyTable(fullTableName_,COMPONENT_OPERATIONS_ENUM, pDiags_)) { fullTableName_ = other.fullTableName_; } // ----------------------------------------------------------------------- // Destructor. // ----------------------------------------------------------------------- PrivMgrComponentOperations::~PrivMgrComponentOperations() { delete &myTable_; } // ***************************************************************************** // * * // * Function: PrivMgrComponentOperations::clear * // * * // * This function clears any cache associated with this object. * // * * // ***************************************************************************** void PrivMgrComponentOperations::clear() { MyTable &myTable = static_cast<MyTable &>(myTable_); myTable.clear(); } //******************* End of PrivMgrComponentOperations::clear ***************** // ***************************************************************************** // * * // * Function: PrivMgrComponentOperations::codeExists * // * * // * This function determines if a specific component operation code has * // * been defined in Privilege Manager metadata. * // * * // ***************************************************************************** // * * // * Parameters: * // * * // * <componentUID> const int64_t In * // * is the unique ID associated with the component. * // * * // * <operationCode> const std::string & In * // * is the two character code associated with the component operation. * // * * // ***************************************************************************** // * * // * Returns: bool * // * * // * true: Operation has been created. * // * false: Operation does not exist or error encountered. * // * * // ***************************************************************************** bool PrivMgrComponentOperations::codeExists( const int64_t componentUID, const std::string & operationCode) { MyRow row(fullTableName_); MyTable &myTable = static_cast<MyTable &>(myTable_); PrivStatus privStatus = myTable.fetchByCode(componentUID,operationCode,row); if (privStatus == STATUS_GOOD || privStatus == STATUS_WARNING) return true; return false; } //********************* End of PrivMgrComponents::codeExists ******************* // ***************************************************************************** // * * // * Function: PrivMgrComponentOperations::createOperation * // * * // * Add an operation for the specified component to the * // * COMPONENT_OPERATIONS table. * // * * // ***************************************************************************** // * * // * Parameters: * // * * // * <componentName> const std::string & In * // * is the component name. * // * * // * <operationName> const std::string & In * // * is the name of the operation to be added. * // * * // * <operationCode> const std::string & In * // * is a 2 character code associated with the operation unique to the * // * component. * // * * // * <isSystem> bool In * // * is true if the operation is a system operation. * // * * // * <operationDescription> const std::string & In * // * is a descrption of the operation. * // * * // * <existsErrorOK> const bool [In] * // * if true, exists errors are silently ignored. * // * * // ***************************************************************************** // * * // * Returns: PrivStatus * // * * // * STATUS_GOOD: Row added. * // * *: Create failed. A CLI error is put into the diags area. * // * * // ***************************************************************************** PrivStatus PrivMgrComponentOperations::createOperation( const std::string & componentName, const std::string & operationName, const std::string & operationCode, bool isSystem, const std::string & operationDescription, const bool existsErrorOK) { PrivMgrComponentPrivileges componentPrivileges(metadataLocation_, pDiags_); if (!ComUser::isRootUserID()&& !componentPrivileges.hasSQLPriv(ComUser::getCurrentUser(), SQLOperation::MANAGE_COMPONENTS, true)) { *pDiags_ << DgSqlCode(-CAT_NOT_AUTHORIZED); return STATUS_ERROR; } if (operationCode.size() != 2 || (operationCode.size() == 2 && (operationCode[0] == ' ' || operationCode[1] == ' '))) { *pDiags_ << DgSqlCode(-CAT_CODE_MUST_CONTAIN_2_NONBLANKS); return STATUS_ERROR; } // Determine if the component exists. PrivMgrComponents component(metadataLocation_,pDiags_); if (!component.exists(componentName)) { *pDiags_ << DgSqlCode(-CAT_TABLE_DOES_NOT_EXIST_ERROR) << DgTableName(componentName.c_str()); return STATUS_ERROR; } // Component exists, fetch data for this component std::string componentUIDString; int64_t componentUID; bool isSystemComponent; std::string tempStr; component.fetchByName(componentName, componentUIDString, componentUID, isSystemComponent, tempStr); // OK, the component is defined, what about the operation? If it already is // defined, return an error. Both the operation name and code must be // unique within a component. if (nameExists(componentUID,operationName)) { if (existsErrorOK) return STATUS_GOOD; *pDiags_ << DgSqlCode(-CAT_COMPONENT_PRIVILEGE_NAME_EXISTS) << DgString0(operationName.c_str()); return STATUS_ERROR; } if (codeExists(componentUID,operationCode)) { if (existsErrorOK) return STATUS_GOOD; *pDiags_ << DgSqlCode(-CAT_COMPONENT_PRIVILEGE_CODE_EXISTS) << DgString0(operationCode.c_str()); return STATUS_ERROR; } // An operation can only be a system operation if its component is a // system component. if (isSystem && !isSystemComponent) { *pDiags_ << DgSqlCode(-CAT_COMPONENT_NOT_SYSTEM); return STATUS_ERROR; } // Name and code are not used, add an entry. MyRow row(fullTableName_); row.componentUID_ = componentUID; row.operationCode_ = operationCode; row.operationName_ = operationName; row.operationType_ = (isSystem ? OP_TYPE_SYSTEM : OP_TYPE_USER); row.operationDescription_ = operationDescription; MyTable &myTable = static_cast<MyTable &>(myTable_); PrivStatus privStatus = myTable.insert(row); if (privStatus != STATUS_GOOD) return privStatus; // Grant authority to creator PrivMgrComponentPrivileges componentPrivilege(metadataLocation_,pDiags_); return componentPrivilege.grantPrivilegeToCreator(componentUID, operationCode, ComUser::getCurrentUser(), ComUser::getCurrentUsername()); } //************ End of PrivMgrComponentOperations::createOperation ************** // ***************************************************************************** // * * // * Function: PrivMgrComponentOperations::createOperationInternal * // * * // * Add an operation for the specified component to the * // * COMPONENT_OPERATIONS table. * // * * // ***************************************************************************** // * * // * Parameters: * // * * // * <componentUID> const int64_t In * // * is a unique ID for the component. * // * * // * <operationName> const std::string & In * // * is the name of the operation to be added. * // * * // * <operationCode> const std::string & In * // * is a 2 character code associated with the operation unique to the * // * component. * // * * // * <operationTypeUnused> const bool In * // * type of component, user, system, or unused. * // * * // * <operationDescription> const std::string & In * // * is a descrption of the operation. * // * * // * <granteeID> const int32_t In * // * is the the authID to be granted the privilege on the newly created * // * component operation. * // * * // * <granteeName> const std::string & In * // * is the name of the authID to be granted the privilege on the newly * // * created component operation. * // * * // * <grantDepth> const int32_t In * // * is the number of levels this privilege may be granted by the grantee. * // * Initially this is either 0 or -1. * // * * // ***************************************************************************** // * * // * Returns: PrivStatus * // * * // * STATUS_GOOD: Row added. * // * *: Create failed. A CLI error is put into the diags area. * // * * // ***************************************************************************** PrivStatus PrivMgrComponentOperations::createOperationInternal( const int64_t componentUID, const std::string & operationName, const std::string & operationCode, const bool operationTypeUnused, const std::string & operationDescription, const int32_t granteeID, const std::string & granteeName, const int32_t grantDepth, const bool checkExistence) { PrivStatus privStatus = STATUS_GOOD; // If operation already created, no need to create if (checkExistence && nameExists(componentUID,operationName)) return STATUS_GOOD; MyRow row(fullTableName_); row.componentUID_ = componentUID; row.operationCode_ = operationCode; row.operationName_ = operationName; row.operationType_ = (operationTypeUnused ? OP_TYPE_UNUSED : OP_TYPE_SYSTEM); row.operationDescription_ = operationDescription; MyTable &myTable = static_cast<MyTable &>(myTable_); privStatus = myTable.insert(row); if (privStatus != STATUS_GOOD) return privStatus; // Grant authority to creator PrivMgrComponentPrivileges componentPrivileges(metadataLocation_,pDiags_); std::vector<std::string> operationCodes; operationCodes.push_back(operationCode); privStatus = componentPrivileges.grantPrivilegeInternal(componentUID, operationCodes, SYSTEM_USER, ComUser::getSystemUserName(), granteeID, granteeName,grantDepth, checkExistence); return privStatus; } //************ End of PrivMgrComponentOperations::createOperation ************** // ***************************************************************************** // * * // * Function: PrivMgrComponentOperations::describeComponentOperations * // * * // * Reads all rows of componentUIDString from COMPONENT_OPERATIONS, * // * for each row, * // * generate a CREATE COMPONENT PRIVILEGE statement, * // * and call PrivMgrComponentPrivileges::describeComponentPrivileges() * // * to generate GRANT COMPONENT PRIVILEGE statements. * // * * // ***************************************************************************** // * * // * Parameters: * // * * // * componentUIDString const std::string & In * // * is the component unique ID as a numeric string. * // * * // * componentName const std::string & In * // * is the name of the component * // * * // * outlines std::vector<std::string> & Out * // * array of strings with CREATE and GRANT statements * // * * // * componentPrivileges PrivMgrComponentPrivileges * In * // * if specified use PrivMgrComponentPrivileges object * // * to generate GRANT statement for each component operation * // * * // ***************************************************************************** // * * // * Returns: PrivStatus * // * * // * STATUS_GOOD: Row read successfully, data returned. * // * * // * STATUS_NOTFOUND: No rows that matched, or error encountered. * // * * // ***************************************************************************** PrivStatus PrivMgrComponentOperations::describeComponentOperations( const std::string & componentUIDString, const std::string & componentName, std::vector<std::string> & outlines, PrivMgrComponentPrivileges * componentPrivileges) { std::vector<MyRow *> rowList; MyTable &myTable = static_cast<MyTable &>(myTable_); std::string whereClause("WHERE COMPONENT_UID = "); whereClause += componentUIDString; whereClause += " and is_system <> 'U'"; PrivStatus privStatus = myTable.selectWhere(whereClause, rowList); if (privStatus == STATUS_GOOD) { for(int i = 0; i < rowList.size(); i++) { MyRow* myRow = rowList[i]; if (myRow->operationType_ == OP_TYPE_UNUSED) continue; std::string componentText; componentText += "CREATE COMPONENT PRIVILEGE "; componentText += myRow->operationName_ + " AS "; componentText += "'" + myRow->operationCode_ + "'"; componentText += " ON " + componentName; if(myRow->operationType_ == OP_TYPE_SYSTEM) componentText += " SYSTEM"; if(!myRow->operationDescription_.empty()) componentText += " DETAIL '" + myRow->operationDescription_ + "'"; componentText += ";"; outlines.push_back(componentText); outlines.push_back(""); if(componentPrivileges) componentPrivileges->describeComponentPrivileges(componentUIDString, componentName, myRow->operationCode_, myRow->operationName_, outlines); delete myRow; outlines.push_back(""); } } return privStatus; } //****** End of PrivMgrComponentOperations::describeComponentOperations ******** // ***************************************************************************** // * * // * Function: PrivMgrComponentOperations::dropAll * // * * // * Deletes all rows in the COMPONENT_OPERATIONS table. * // * * // ***************************************************************************** // * * // * Returns: PrivStatus * // * * // * STATUS_GOOD: Row(s) deleted. * // * *: Delete failed. A CLI error is put into the diags area. * // * * // ***************************************************************************** PrivStatus PrivMgrComponentOperations::dropAll() { std::string whereClause (" "); MyTable &myTable = static_cast<MyTable &>(myTable_); PrivStatus privStatus = myTable.deleteWhere(whereClause); if (privStatus != STATUS_GOOD) return privStatus; PrivMgrComponentPrivileges componentPrivileges(metadataLocation_,pDiags_); return componentPrivileges.dropAll(); } //**************** End of PrivMgrComponentOperations::dropAll ****************** // ***************************************************************************** // * * // * Function: PrivMgrComponentOperations::dropAll * // * * // * Deletes all rows in the COMPONENT_OPERATIONS table that match the * // * specified component unique ID. In addition, and granted privileges * // * for the component are deleted. * // * * // ***************************************************************************** // * * // * Parameters: * // * * // * <componentUID> const std::string & In * // * is the component unique ID. All rows containing this UID will be * // * deleted. * // * * // ***************************************************************************** // * * // * Returns: PrivStatus * // * * // * STATUS_GOOD: Row(s) deleted. * // * *: Delete failed. A CLI error is put into the diags area. * // * * // ***************************************************************************** PrivStatus PrivMgrComponentOperations::dropAll(const std::string & componentUID) { std::string whereClause ("WHERE COMPONENT_UID = "); whereClause += componentUID; MyTable &myTable = static_cast<MyTable &>(myTable_); PrivStatus privStatus = myTable.deleteWhere(whereClause); if (privStatus != STATUS_GOOD) return privStatus; PrivMgrComponentPrivileges componentPrivileges(metadataLocation_,pDiags_); return componentPrivileges.dropAllForComponent(componentUID); } //**************** End of PrivMgrComponentOperations::dropAll ***************** // ***************************************************************************** // * * // * Function: PrivMgrComponentOperations::dropOperation * // * * // * Deletes operation for the specified component from the * // * COMPONENT_OPERATIONS table. * // * * // ***************************************************************************** // * * // * Parameters: * // * * // * <componentName> const std::string & In * // * is the component name. * // * * // * <operationName> const std::string & In * // * is the operation name. * // * * // * <dropBehavior> PrivDropBehavior In * // * indicates whether restrict or cascade behavior is requested. * // * * // ***************************************************************************** // * * // * Returns: PrivStatus * // * * // * STATUS_GOOD: Row(s) deleted. * // * *: Delete failed. A CLI error is put into the diags area. * // * * // ***************************************************************************** PrivStatus PrivMgrComponentOperations::dropOperation( const std::string & componentName, const std::string & operationName, PrivDropBehavior dropBehavior) { PrivMgrComponentPrivileges componentPrivileges(metadataLocation_, pDiags_); if (!ComUser::isRootUserID()&& !componentPrivileges.hasSQLPriv(ComUser::getCurrentUser(), SQLOperation::MANAGE_COMPONENTS, true)) { *pDiags_ << DgSqlCode(-CAT_NOT_AUTHORIZED); return STATUS_ERROR; } // Determine if the component exists. PrivMgrComponents component(metadataLocation_,pDiags_); if (!component.exists(componentName)) { *pDiags_ << DgSqlCode(-CAT_TABLE_DOES_NOT_EXIST_ERROR) << DgTableName(componentName.c_str()); return STATUS_ERROR; } // Component exists, fetch data for this component std::string componentUIDString; int64_t componentUID; bool isSystemComponent; std::string tempStr; component.fetchByName(componentName, componentUIDString, componentUID, isSystemComponent, tempStr); // OK, the component is defined, what about the operation? if (!nameExists(componentUID,operationName)) { *pDiags_ << DgSqlCode(-CAT_TABLE_DOES_NOT_EXIST_ERROR) << DgTableName(operationName.c_str()); return STATUS_ERROR; } //Operation exists, get the data. std::string operationCode; bool isSystemOperation = FALSE; fetchByName(componentUIDString,operationName,operationCode,isSystemOperation, tempStr); // // Has operation been granted to any authID? // if (dropBehavior == PrivDropBehavior::RESTRICT && componentPrivileges.isGranted(componentUIDString,operationCode,true)) { *pDiags_ << DgSqlCode(-CAT_DEPENDENT_OBJECTS_EXIST); return STATUS_ERROR; } // Either CASCADE, or RESTRICT and there are no user grants - drop away! PrivStatus privStatus = componentPrivileges.dropAllForOperation(componentUIDString, operationCode); if (privStatus != STATUS_GOOD) return privStatus; // Delete row in COMPONENT_OPERATIONS table. MyTable &myTable = static_cast<MyTable &>(myTable_); std::string whereClause("WHERE COMPONENT_UID = "); whereClause += componentUIDString; whereClause += " AND OPERATION_NAME = '"; whereClause += operationName; whereClause += "'"; return myTable.deleteWhere(whereClause); } //************* End of PrivMgrComponentOperations::dropOperation *************** // ***************************************************************************** // * * // * Function: PrivMgrComponentOperations::fetchByName * // * * // * This function reads the row in the COMPONENT_OPERATIONS tables for * // * the specified component operation and returns the associated operation * // * code and description. * // * * // ***************************************************************************** // * * // * Parameters: * // * * // * <componentUIDString> const std::string & In * // * is the component unique ID as a numeric string. * // * * // * <operationName> const std::string & In * // * is the name of the component operation in upper case. * // * * // * <operationCode> std::string & Out * // * passes back the code associated with the component operation. * // * * // * <isSystem> bool & Out * // * passes back true if the component operation is a system level * // * * // * <operationDescription> std::string & Out * // * passes back the description of the component operation. * // * * // ***************************************************************************** // * * // * Returns: PrivStatus * // * * // * STATUS_GOOD: Row read successfully, data returned. * // * * // * STATUS_NOTFOUND: No rows that matched, or error encountered. * // * * // ***************************************************************************** PrivStatus PrivMgrComponentOperations::fetchByName( const std::string & componentUIDString, const std::string & operationName, std::string & operationCode, bool isSystem, std::string & operationDescription) { MyRow row(fullTableName_); MyTable &myTable = static_cast<MyTable &>(myTable_); PrivStatus privStatus = myTable.fetchByName(componentUIDString,operationName,row); if (privStatus == STATUS_NOTFOUND || privStatus == STATUS_ERROR) return STATUS_NOTFOUND; operationCode = row.operationCode_; isSystem = (row.operationType_ == OP_TYPE_SYSTEM); operationDescription = row.operationDescription_; return STATUS_GOOD; } //*************** End of PrivMgrComponentOperations::fetchByName *************** // ***************************************************************************** // * * // * Function: PrivMgrComponentOperations::getCount * // * * // * Returns: * // * the total number of operations * // * the number of unused operations * // * * // ***************************************************************************** // * * // * Returns: PrivStatus * // * * // * STATUS_GOOD : found operations * // * STATUS_NOTFOUND : no operations were found * // * STATUS_ERROR : unexpected error reading metadata * // * * // ***************************************************************************** PrivStatus PrivMgrComponentOperations::getCount( const int64_t &componentUID, int32_t &numOps, int32_t &numUnusedOps) { char buf[getMetadataLocation().size() + 300]; snprintf (buf, sizeof(buf), "select distinct is_system, count(is_system) over " "(partition by is_system) from %s.%s where component_uid = %ld", getMetadataLocation().c_str(),PRIVMGR_COMPONENT_OPERATIONS, componentUID); // set pointer in diags area int32_t diagsMark = pDiags_->mark(); ExeCliInterface cliInterface(STMTHEAP, 0, NULL, CmpCommon::context()->sqlSession()->getParentQid()); Queue * tableQueue = NULL; int32_t cliRC = cliInterface.fetchAllRows(tableQueue, buf, 0, false, false, true); if (cliRC < 0) { cliInterface.retrieveSQLDiagnostics(CmpCommon::diags()); return STATUS_ERROR; } if (cliRC == 100) // did not find the row { pDiags_->rewind(diagsMark); return STATUS_NOTFOUND; } numOps = 0; numUnusedOps = 0; char * ptr = NULL; int32_t len = 0; char value[3]; int32_t opTypeCount; // column 0: operation type // column 1: count of rows for operation type tableQueue->position(); for (int idx = 0; idx < tableQueue->numEntries(); idx++) { OutputInfo * pCliRow = (OutputInfo*)tableQueue->getNext(); pCliRow->get(0,ptr,len); strncpy(value,ptr,len); value[len] = 0; pCliRow->get(1,ptr,len); opTypeCount = *(reinterpret_cast<int32_t*>(ptr)); numOps += opTypeCount; if (value[0] == 'U') numUnusedOps += opTypeCount; } return STATUS_GOOD; } //***************** End of PrivMgrComponentOperations::getCount **************** // ***************************************************************************** // * * // * Function: PrivMgrComponentOperations::isComponentUsed * // * * // * Determines if a component is used in the COMPONENT_OPERATIONS table. * // * * // ***************************************************************************** // * * // * Parameters: * // * * // * <componentUIDString> const std::string & In * // * is the component unique ID as a numeric string. * // * * // ***************************************************************************** // * * // * Returns: bool * // * * // * true: Component is used in COMPONENT_OPERATIONS table. * // * false: Component is used in COMPONENT_OPERATIONS table, or error trying * // * to read from COMPONENT_OPERATIONS table. * // * * // ***************************************************************************** bool PrivMgrComponentOperations::isComponentUsed(const std::string & componentUIDString) { MyRow row(fullTableName_); std::string whereClause("WHERE COMPONENT_UID = "); whereClause += componentUIDString; // set pointer in diags area int32_t diagsMark = pDiags_->mark(); MyTable &myTable = static_cast<MyTable &>(myTable_); PrivStatus privStatus = myTable.selectWhereUnique(whereClause,row); if (privStatus == STATUS_GOOD || privStatus == STATUS_WARNING) return true; // If not found or any other error is returned, rewind the diagnostics and // return false. pDiags_->rewind(diagsMark); return false; } //************* End of PrivMgrComponentOperations::isComponentUsed ************* // ***************************************************************************** // method: updateOperationCodes // // Goes through the ComponentOpStruct for the sql_operations component and // creates two lists: // list of unused operations // list of system operations. // // Updates the component_operations table and // sets is_system to "U" for unused operations // sets is_system to "Y" for system operations // // TBD - add support for all components, not just sql_operations // ***************************************************************************** PrivStatus PrivMgrComponentOperations::updateOperationCodes( const int64_t & componentUID ) { if (componentUID != SQL_OPERATIONS_COMPONENT_UID) { PRIVMGR_INTERNAL_ERROR("Invalid component UID in PrivMgrComponentOperations::updateOperationCodes"); return STATUS_ERROR; } std::string unusedItems ("where component_uid = "); unusedItems += UIDToString(componentUID); unusedItems += " and operation_code in ("; std::string systemItems(unusedItems); size_t numOps = sizeof(sqlOpList)/sizeof(ComponentOpStruct); bool firstUnusedOp = true; bool firstSystemOp = true; for (int i = 0; i < numOps; i++) { const ComponentOpStruct &opDefinition = sqlOpList[i]; if (opDefinition.unusedOp) { if (firstUnusedOp) { unusedItems += "'"; firstUnusedOp = false; } else unusedItems += ", '"; unusedItems += opDefinition.operationCode; unusedItems += "'"; } else { if (firstSystemOp) { systemItems += "'"; firstSystemOp = false; } else systemItems += ", '"; systemItems += opDefinition.operationCode; systemItems += "'"; } } MyTable &myTable = static_cast<MyTable &>(myTable_); // Change system components to unused components if (!firstUnusedOp) { unusedItems += ")"; std::string setClause("set is_system = 'U' "); if (myTable.update(setClause, unusedItems) == STATUS_ERROR) return STATUS_ERROR; } // Change unused components to system components if (!firstSystemOp) { systemItems += ")"; std::string setClause("set is_system = 'Y' "); if (myTable.update(setClause, systemItems) == STATUS_ERROR) return STATUS_ERROR; } return STATUS_GOOD; } // ***************************************************************************** // * * // * Function: PrivMgrComponentOperations::nameExists * // * * // * This function determines if a specific component operation has been * // * defined in Privilege Manager metadata. * // * * // ***************************************************************************** // * * // * Parameters: * // * * // * <componentUID> const int64_t In * // * is the unique ID associated with the component. * // * * // * <operationName> const std::string & In * // * is the name of the operation in upper case. * // * * // ***************************************************************************** // * * // * Returns: bool * // * * // * true: Operation has been created. * // * false: Operation does not exist or error encountered. * // * * // ***************************************************************************** bool PrivMgrComponentOperations::nameExists( const int64_t componentUID, const std::string & operationName) { MyRow row(fullTableName_); MyTable &myTable = static_cast<MyTable &>(myTable_); PrivStatus privStatus = myTable.fetchByName(componentUID,operationName,row); if (privStatus == STATUS_GOOD || privStatus == STATUS_WARNING) return true; return false; } //******************** End of PrivMgrComponents::nameExists ******************** // ***************************************************************************** // MyTable methods // ***************************************************************************** // ***************************************************************************** // * * // * Function: MyTable::fetchByCode * // * * // * Reads from the COMPONENT_OPERATIONS table and returns the row * // * associated with the specified operation code. * // * * // ***************************************************************************** // * * // * Parameters: * // * * // * <componentUID> const int64_t In * // * is the unique ID associated with the component. * // * * // * <operationCode> const std::string & In * // * is the two digit code associated with the operation. * // * * // * <row> MyRow & Out * // * passes back a reference to MyRow, containing the data read. * // * * // ***************************************************************************** // * * // * Returns: PrivStatus * // * * // * STATUS_GOOD: Found code, row returned. * // * *: Code not found or error encountered. * // * * // ***************************************************************************** PrivStatus MyTable::fetchByCode( const int64_t componentUID, const std::string & operationCode, MyRow & row) { // Check the last row read before reading metadata. if (lastRowRead_.lookupByCode(componentUID,operationCode, row.operationName_,row.operationType_, row.operationDescription_)) { row.componentUID_ = componentUID; return STATUS_GOOD; } // Not found in cache, look for the component name in metadata. std::string whereClause("WHERE COMPONENT_UID = "); whereClause += PrivMgr::UIDToString(componentUID); whereClause += " AND OPERATION_CODE = '"; whereClause += operationCode; whereClause += "'"; PrivStatus privStatus = selectWhereUnique(whereClause,row); switch (privStatus) { // Return status to caller to handle case STATUS_NOTFOUND: case STATUS_ERROR: return privStatus; break; // Object exists case STATUS_GOOD: case STATUS_WARNING: return STATUS_GOOD; break; // Should not occur, internal error default: PRIVMGR_INTERNAL_ERROR("Switch statement in PrivMgrComponentOperations::MyTable::fetchByCode()"); return STATUS_ERROR; break; } return STATUS_GOOD; } //********************** End of MyTable::fetchByCode *************************** // ***************************************************************************** // * * // * Function: MyTable::fetchByName * // * * // * Reads from the COMPONENT_OPERATIONS table and returns the row * // * associated with the specified operation name. * // * * // ***************************************************************************** // * * // * Parameters: * // * * // * <componentUIDString> const std::string & In * // * is the unique ID associated with the component in string format. * // * * // * <operationName> const std::string & In * // * is the name of the operation. Name is assumed to be upper case. * // * * // * <row> MyRow & Out * // * passes back a reference to MyRow, containing the data read. * // * * // ***************************************************************************** // * * // * Returns: PrivStatus * // * * // * STATUS_GOOD: Found name, row returned. * // * *: Name not found or error encountered. * // * * // ***************************************************************************** PrivStatus MyTable::fetchByName( const std::string & componentUIDString, const std::string & operationName, MyRow & row) { int64_t componentUID = atol(componentUIDString.c_str()); return fetchByName(componentUID,operationName,row); } //********************** End of MyTable::fetchByName *************************** // ***************************************************************************** // * * // * Function: MyTable::fetchByName * // * * // * Reads from the COMPONENT_OPERATIONS table and returns the row * // * associated with the specified operation name. * // * * // ***************************************************************************** // * * // * Parameters: * // * * // * <componentUID> const int64_t In * // * is the unique ID associated with the component. * // * * // * <operationName> const std::string & In * // * is the name of the operation. Name is assumed to be upper case. * // * * // * <row> MyRow & Out * // * passes back a reference to MyRow, containing the data read. * // * * // ***************************************************************************** // * * // * Returns: PrivStatus * // * * // * STATUS_GOOD: Found name, row returned. * // * *: Name not found or error encountered. * // * * // ***************************************************************************** PrivStatus MyTable::fetchByName( const int64_t componentUID, const std::string & operationName, MyRow & row) { // Check the last row read before reading metadata. if (lastRowRead_.lookupByName(componentUID,operationName, row.operationCode_,row.operationType_, row.operationDescription_)) { row.componentUID_ = componentUID; return STATUS_GOOD; } // Not found in cache, look for the component name in metadata. std::string whereClause("WHERE COMPONENT_UID = "); whereClause += PrivMgr::UIDToString(componentUID); whereClause += " AND OPERATION_NAME = '"; whereClause += operationName; whereClause += "'"; PrivStatus privStatus = selectWhereUnique(whereClause,row); switch (privStatus) { // Return status to caller to handle case STATUS_NOTFOUND: case STATUS_ERROR: return privStatus; break; // Object exists case STATUS_GOOD: case STATUS_WARNING: return STATUS_GOOD; break; // Should not occur, internal error default: PRIVMGR_INTERNAL_ERROR("Switch statement in PrivMgrComponentOperations::MyTable::fetchByName()"); return STATUS_ERROR; break; } return STATUS_GOOD; } //********************** End of MyTable::fetchByName *************************** // ***************************************************************************** // * * // * Function: MyTable::insert * // * * // * Inserts a row into the COMPONENT_OPERATIONS table. * // * * // ***************************************************************************** // * * // * Parameters: * // * * // * <rowIn> const PrivMgrMDRow & In * // * is a MyRow to be inserted. * // * * // ***************************************************************************** // * * // * Returns: PrivStatus * // * * // * STATUS_GOOD: Row inserted. * // * *: Insert failed. A CLI error is put into the diags area. * // * * // ***************************************************************************** PrivStatus MyTable::insert(const PrivMgrMDRow & rowIn) { char insertStatement[1000]; const MyRow & row = static_cast<const MyRow &>(rowIn); char operationType = PrivMgrComponentOperations::compTypeToLit(row.operationType_); sprintf(insertStatement, "insert into %s values (%ld, '%s', '%s', '%c', '%s')", tableName_.c_str(), row.componentUID_, row.operationCode_.c_str(), row.operationName_.c_str(), operationType, row.operationDescription_.c_str()); return CLIImmediate(insertStatement); } //************************** End of MyTable::insert **************************** // ***************************************************************************** // * * // * Function: MyTable::selectWhereUnique * // * * // * Selects a row from the COMPONENT_OPERATIONS table based on the * // * specified WHERE clause. * // * * // ***************************************************************************** // * * // * Parameters: * // * * // * <whereClause> const std::string & In * // * is the WHERE clause specifying a unique row. * // * * // * <rowOut> PrivMgrMDRow & Out * // * passes back a refernce to a MyRow. * // * * // ***************************************************************************** // * * // * Returns: PrivStatus * // * * // * STATUS_GOOD: Row returned. * // * *: Select failed. A CLI error is put into the diags area. * // * * // ***************************************************************************** PrivStatus MyTable::selectWhereUnique( const std::string & whereClause, PrivMgrMDRow & rowOut) { // Generate the select statement std::string selectStmt ("SELECT COMPONENT_UID, OPERATION_CODE, OPERATION_NAME, IS_SYSTEM, OPERATION_DESCRIPTION FROM "); selectStmt += tableName_; selectStmt += " "; selectStmt += whereClause; ExeCliInterface cliInterface(STMTHEAP, 0, NULL, CmpCommon::context()->sqlSession()->getParentQid()); PrivStatus privStatus = CLIFetch(cliInterface,selectStmt); if (privStatus != STATUS_GOOD && privStatus != STATUS_WARNING) return privStatus; char * ptr = NULL; Lng32 len = 0; char value[500]; MyRow & row = static_cast<MyRow &>(rowOut); // column 1: component_uid cliInterface.getPtrAndLen(1,ptr,len); row.componentUID_ = *(reinterpret_cast<int64_t*>(ptr)); // column 2: operation_code cliInterface.getPtrAndLen(2,ptr,len); strncpy(value,ptr,len); value[len] = 0; row.operationCode_ = value; // column 3: operation_name cliInterface.getPtrAndLen(3,ptr,len); strncpy(value,ptr,len); value[len] = 0; row.operationName_ = value; // column 4: is_system cliInterface.getPtrAndLen(4,ptr,len); strncpy(value,ptr,len); value[len] = 0; row.operationType_ = PrivMgrComponentOperations::compTypeToEnum(value[0]); // column 5: operation_description cliInterface.getPtrAndLen(5,ptr,len); strncpy(value,ptr,len); value[len] = 0; row.operationDescription_ = value; lastRowRead_ = row; return STATUS_GOOD; } //********************* End of MyTable::selectWhereUnique ********************** // ***************************************************************************** // method: update // // Updates metadata based on the passed in set and where clauses. // ***************************************************************************** PrivStatus MyTable::update( const std::string & setClause, const std::string & whereClause) { char updateStatement[setClause.size() + whereClause.size() + tableName_.size() + 100]; sprintf(updateStatement, "update %s %s %s", tableName_.c_str(), setClause.c_str(), whereClause.c_str()); return CLIImmediate(updateStatement); } // ***************************************************************************** // MyRow methods // ***************************************************************************** // ***************************************************************************** // * * // * Function: MyRow::lookupByCode * // * * // * Looks for a specified component operation name in cache, and if found, * // * returns the associated data. * // * * // ***************************************************************************** // * * // * Parameters: * // * * // * <componentUID> const int64_t In * // * is the unique ID associated with the component. * // * * // * <operationCode> const std::string & In * // * is the code associated with the component operation in upper case. * // * * // * <operationName> std::string & Out * // * passes back the name of the component operation. * // * * // * <operationType> OperationType & Out * // * passes back the component type, system, user, or unused. * // * * // * <operationDescription> std::string & Out * // * passes back the description of the component operation. * // * * // ***************************************************************************** // * * // * Returns: bool * // * * // * true: Component name found in cache. * // * false: Component name not found in cache. * // * * // ***************************************************************************** bool MyRow::lookupByCode( const int64_t componentUID, const std::string & operationCode, std::string & operationName, PrivMgrComponentOperations::OperationType & operationType, std::string & operationDescription) { // If componentUID_ is zero, that means data is uninitialized. if (componentUID_ == 0 || componentUID != componentUID_ || operationCode != operationCode) return false; operationType = operationType_; operationName = operationName_; operationDescription = operationDescription_; return true; } //************************ End of MyRow::lookupByCode ************************** // ***************************************************************************** // * * // * Function: MyRow::lookupByName * // * * // * Looks for a specified component operation name in cache, and if found, * // * returns the associated data. * // * * // ***************************************************************************** // * * // * Parameters: * // * * // * <componentUID> const int64_t Out * // * is the unique ID associated with the component. * // * * // * <operationName> const std::string & In * // * is the name of the operation. Name is assumed to be upper case. * // * * // * <operationCode> std::string & Out * // * passes back the code associated with the component operation. * // * * // * <OperationType> operationType & Out * // * passes back the component type, system, user, or unused. * // * * // * <operationDescription> std::string & Out * // * passes back the description of the component operation. * // * * // ***************************************************************************** // * * // * Returns: bool * // * * // * true: Component name found in cache. * // * false: Component name not found in cache. * // * * // ***************************************************************************** bool MyRow::lookupByName( const int64_t componentUID, const std::string & operationName, std::string & operationCode, PrivMgrComponentOperations::OperationType & operationType, std::string & operationDescription) { // If componentUID_ is zero, that means data is uninitialized. if (componentUID_ == 0 || componentUID != componentUID_ || operationName != operationName_) return false; operationType = operationType_; operationCode = operationCode_; operationDescription = operationDescription_; return true; } //************************ End of MyRow::lookupByName ************************** // **************************************************************************** // * method: MyTable::selectWhere // * // * Selects rows from the COMPONENT_OPERATIONS table based on the specified // * WHERE clause. // * // * Parameters: // * // * whereClause is the WHERE clause // * rowList passes back array of wanted COMPONENT_OPERATIONS rows // * // * Returns: PrivStatus // * // * STATUS_GOOD: Row returned. // * *: Select failed. A CLI error is put into the diags area. // ***************************************************************************** PrivStatus MyTable::selectWhere( const std::string & whereClause, std::vector<MyRow *> &rowList) { std::string selectStmt("SELECT COMPONENT_UID, OPERATION_CODE, OPERATION_NAME, IS_SYSTEM, TRIM(OPERATION_DESCRIPTION) FROM "); selectStmt += tableName_; selectStmt += " "; selectStmt += whereClause; // set pointer in diags area int32_t diagsMark = pDiags_->mark(); ExeCliInterface cliInterface(STMTHEAP, 0, NULL, CmpCommon::context()->sqlSession()->getParentQid()); Queue * tableQueue = NULL; int32_t cliRC = cliInterface.fetchAllRows(tableQueue, (char *)selectStmt.c_str(), 0, false, false, true); if (cliRC < 0) { cliInterface.retrieveSQLDiagnostics(CmpCommon::diags()); return STATUS_ERROR; } if (cliRC == 100) // did not find the row { pDiags_->rewind(diagsMark); return STATUS_NOTFOUND; } tableQueue->position(); for (int idx = 0; idx < tableQueue->numEntries(); idx++) { OutputInfo * pCliRow = (OutputInfo*)tableQueue->getNext(); MyRow *pRow = new MyRow(tableName_); setRow(pCliRow, *pRow); rowList.push_back(pRow); } // TBD: need code to delete the rowList return STATUS_GOOD; } // ***************************************************************************** // * method: MyTable::setRow // * // * Extract information(OutputInfo) returned from cli, // * and fill a COMPONENT_OPERATIONS row object with the information. // * // * Parameters: // * // * pCliRow row destails from the cli // * row passes back filled row object // * // * no errors should be generated // ***************************************************************************** // Row read successfully. Extract the columns. void MyTable::setRow(OutputInfo *pCliRow, MyRow &row) { char * ptr = NULL; Int32 len = 0; char value[500]; // column 1: COMPONENT_UID pCliRow->get(0,ptr,len); row.componentUID_ = *(reinterpret_cast<int64_t*>(ptr)); // column 2: OPERATION_CODE pCliRow->get(1,ptr,len); strncpy(value, ptr, len); value[len] = 0; row.operationCode_= value; // column 3: OPERATION_NAME pCliRow->get(2,ptr,len); strncpy(value, ptr, len); value[len] = 0; row.operationName_= value; // column 4: IS_SYSTEM pCliRow->get(3,ptr,len); strncpy(value,ptr,len); value[len] = 0; row.operationType_ = PrivMgrComponentOperations::compTypeToEnum(value[0]); // column 5: OPERATION_DESCRIPTION pCliRow->get(4,ptr,len); strncpy(value, ptr, len); value[len] = 0; row.operationDescription_ = value; }
apache/incubator-trafodion
core/sql/sqlcomp/PrivMgrComponentOperations.cpp
C++
apache-2.0
78,581
package org.hl7.fhir.dstu3.model.codesystems; /* Copyright (c) 2011+, HL7, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of HL7 nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // Generated on Tue, Dec 6, 2016 09:42-0500 for FHIR v1.8.0 import org.hl7.fhir.exceptions.FHIRException; public enum PaymentStatus { /** * The payment has been sent physically or electronically. */ PAID, /** * The payment has been received by the payee. */ CLEARED, /** * added to help the parsers */ NULL; public static PaymentStatus fromCode(String codeString) throws FHIRException { if (codeString == null || "".equals(codeString)) return null; if ("paid".equals(codeString)) return PAID; if ("cleared".equals(codeString)) return CLEARED; throw new FHIRException("Unknown PaymentStatus code '"+codeString+"'"); } public String toCode() { switch (this) { case PAID: return "paid"; case CLEARED: return "cleared"; default: return "?"; } } public String getSystem() { return "http://hl7.org/fhir/paymentstatus"; } public String getDefinition() { switch (this) { case PAID: return "The payment has been sent physically or electronically."; case CLEARED: return "The payment has been received by the payee."; default: return "?"; } } public String getDisplay() { switch (this) { case PAID: return "Paid"; case CLEARED: return "Cleared"; default: return "?"; } } }
Gaduo/hapi-fhir
hapi-fhir-structures-dstu3/src/main/java/org/hl7/fhir/dstu3/model/codesystems/PaymentStatus.java
Java
apache-2.0
3,286
package com.jfixby.r3.physics; import com.jfixby.r3.api.physics.Body; import com.jfixby.r3.api.physics.BodyDynamicsListener; import com.jfixby.r3.api.physics.BodyMass; import com.jfixby.r3.api.physics.BodyPosition; import com.jfixby.r3.api.physics.ForcesApplicator; import com.jfixby.r3.physics.body.BodyImpl; public class BodyDynamicsImpl implements ForcesApplicator { final private BodyImpl master; public BodyDynamicsImpl (final BodyImpl body) { this.master = body; } public void applyForcesIfNeeded () { if (this.dynamics_listener != null) { this.dynamics_listener.onApplyForcesCallBack(this); } } private BodyDynamicsListener dynamics_listener; public void setDynamicsListener (final BodyDynamicsListener dynamics_listener) { this.dynamics_listener = dynamics_listener; } @Override public BodyPosition getBodyPosition () { return this.master.warpingData(); } @Override public BodyMass getBodyMassValues () { return this.master.mass(); } @Override public void applyForce (final double force_x, final double force_y) { this.master.body_avatar.applyForce(force_x, force_y); } @Override public boolean isBody (final Body body) { return this.master == body; } public BodyDynamicsListener getDynamicsListener () { return this.dynamics_listener; } }
JFixby/RedTriplane
red-triplane-physics-red/src/com/jfixby/r3/physics/BodyDynamicsImpl.java
Java
apache-2.0
1,305
# Copyright 2017 Google, Inc # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require "rails_helper" RSpec.describe CatsController, type: :controller do let :valid_attributes do { name: "Ms. Tiger", age: 3 } end let :invalid_attributes do { name: nil, age: nil } end let(:valid_session) { {} } describe "GET #index" do it "assigns all cats as @cats" do cat = Cat.create! valid_attributes get :index, params: {}, session: valid_session expect(assigns(:cats)).to include(cat) end end describe "GET #show" do it "assigns the requested cat as @cat" do cat = Cat.create! valid_attributes get :show, params: { id: cat.to_param }, session: valid_session expect(assigns(:cat)).to eq(cat) end end describe "GET #new" do it "assigns a new cat as @cat" do get :new, params: {}, session: valid_session expect(assigns(:cat)).to be_a_new(Cat) end end describe "GET #edit" do it "assigns the requested cat as @cat" do cat = Cat.create! valid_attributes get :edit, params: { id: cat.to_param }, session: valid_session expect(assigns(:cat)).to eq(cat) end end describe "POST #create" do context "with valid params" do it "creates a new Cat" do expect { post :create, params: { cat: valid_attributes }, session: valid_session }.to change(Cat, :count).by(1) end it "assigns a newly created cat as @cat" do post :create, params: { cat: valid_attributes }, session: valid_session expect(assigns(:cat)).to be_a(Cat) expect(assigns(:cat)).to be_persisted end it "redirects to the created cat" do post :create, params: { cat: valid_attributes }, session: valid_session expect(response).to redirect_to(Cat.last) end end context "with invalid params" do it "assigns a newly created but unsaved cat as @cat" do post :create, params: { cat: invalid_attributes }, session: valid_session expect(assigns(:cat)).to be_a_new(Cat) end it "re-renders the 'new' template" do post :create, params: { cat: invalid_attributes }, session: valid_session expect(response).to render_template("new") end end end describe "PUT #update" do context "with valid params" do let :new_attributes do { name: "Mr. Whiskers", age: 4 } end it "updates the requested cat" do cat = Cat.create! valid_attributes put :update, params: { id: cat.to_param, cat: new_attributes }, session: valid_session cat.reload expect(cat.name).to eq("Mr. Whiskers") expect(cat.age).to eq(4) end it "assigns the requested cat as @cat" do cat = Cat.create! valid_attributes put :update, params: { id: cat.to_param, cat: valid_attributes }, session: valid_session expect(assigns(:cat)).to eq(cat) end it "redirects to the cat" do cat = Cat.create! valid_attributes put :update, params: { id: cat.to_param, cat: valid_attributes }, session: valid_session expect(response).to redirect_to(cat) end end context "with invalid params" do it "assigns the cat as @cat" do cat = Cat.create! valid_attributes put :update, params: { id: cat.to_param, cat: invalid_attributes }, session: valid_session expect(assigns(:cat)).to eq(cat) end it "re-renders the 'edit' template" do cat = Cat.create! valid_attributes put :update, params: { id: cat.to_param, cat: invalid_attributes }, session: valid_session expect(response).to render_template("edit") end end end describe "DELETE #destroy" do it "destroys the requested cat" do cat = Cat.create! valid_attributes expect { delete :destroy, params: { id: cat.to_param }, session: valid_session }.to change(Cat, :count).by(-1) end it "redirects to the cats list" do cat = Cat.create! valid_attributes delete :destroy, params: { id: cat.to_param }, session: valid_session expect(response).to redirect_to(cats_url) end end end
GoogleCloudPlatform/ruby-docs-samples
appengine/rails-cloudsql-postgres/spec/controllers/cats_controller_spec.rb
Ruby
apache-2.0
4,707
#ifndef AUTOBOOST_MPL_LIST_LIST40_C_HPP_INCLUDED #define AUTOBOOST_MPL_LIST_LIST40_C_HPP_INCLUDED // Copyright Aleksey Gurtovoy 2000-2004 // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // See http://www.boost.org/libs/mpl for documentation. // $Id$ // $Date$ // $Revision$ #if !defined(AUTOBOOST_MPL_PREPROCESSING_MODE) # include <autoboost/mpl/list/list30_c.hpp> #endif #include <autoboost/mpl/aux_/config/use_preprocessed.hpp> #if !defined(AUTOBOOST_MPL_CFG_NO_PREPROCESSED_HEADERS) \ && !defined(AUTOBOOST_MPL_PREPROCESSING_MODE) # define AUTOBOOST_MPL_PREPROCESSED_HEADER list40_c.hpp # include <autoboost/mpl/list/aux_/include_preprocessed.hpp> #else # include <autoboost/preprocessor/iterate.hpp> namespace autoboost { namespace mpl { # define AUTOBOOST_PP_ITERATION_PARAMS_1 \ (3,(31, 40, <autoboost/mpl/list/aux_/numbered_c.hpp>)) # include AUTOBOOST_PP_ITERATE() }} #endif // AUTOBOOST_MPL_CFG_NO_PREPROCESSED_HEADERS #endif // AUTOBOOST_MPL_LIST_LIST40_C_HPP_INCLUDED
codemercenary/autowiring
contrib/autoboost/autoboost/mpl/list/list40_c.hpp
C++
apache-2.0
1,124
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.pulsar.broker.authentication.utils; import io.jsonwebtoken.JwtBuilder; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import io.jsonwebtoken.io.Decoders; import io.jsonwebtoken.io.DecodingException; import io.jsonwebtoken.io.Encoders; import io.jsonwebtoken.security.Keys; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.security.Key; import java.security.KeyFactory; import java.security.PrivateKey; import java.security.PublicKey; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; import java.util.Date; import java.util.Optional; import javax.crypto.SecretKey; import lombok.experimental.UtilityClass; import org.apache.commons.codec.binary.Base64; import org.apache.commons.io.IOUtils; import org.apache.pulsar.client.api.url.URL; @UtilityClass public class AuthTokenUtils { public static SecretKey createSecretKey(SignatureAlgorithm signatureAlgorithm) { return Keys.secretKeyFor(signatureAlgorithm); } public static SecretKey decodeSecretKey(byte[] secretKey) { return Keys.hmacShaKeyFor(secretKey); } public static PrivateKey decodePrivateKey(byte[] key, SignatureAlgorithm algType) throws IOException { try { PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(key); KeyFactory kf = KeyFactory.getInstance(keyTypeForSignatureAlgorithm(algType)); return kf.generatePrivate(spec); } catch (Exception e) { throw new IOException("Failed to decode private key", e); } } public static PublicKey decodePublicKey(byte[] key, SignatureAlgorithm algType) throws IOException { try { X509EncodedKeySpec spec = new X509EncodedKeySpec(key); KeyFactory kf = KeyFactory.getInstance(keyTypeForSignatureAlgorithm(algType)); return kf.generatePublic(spec); } catch (Exception e) { throw new IOException("Failed to decode public key", e); } } private static String keyTypeForSignatureAlgorithm(SignatureAlgorithm alg) { if (alg.getFamilyName().equals("RSA")) { return "RSA"; } else if (alg.getFamilyName().equals("ECDSA")) { return "EC"; } else { String msg = "The " + alg.name() + " algorithm does not support Key Pairs."; throw new IllegalArgumentException(msg); } } public static String encodeKeyBase64(Key key) { return Encoders.BASE64.encode(key.getEncoded()); } public static String createToken(Key signingKey, String subject, Optional<Date> expiryTime) { JwtBuilder builder = Jwts.builder() .setSubject(subject) .signWith(signingKey); expiryTime.ifPresent(builder::setExpiration); return builder.compact(); } public static byte[] readKeyFromUrl(String keyConfUrl) throws IOException { if (keyConfUrl.startsWith("data:") || keyConfUrl.startsWith("file:")) { try { return IOUtils.toByteArray(URL.createURL(keyConfUrl)); } catch (IOException e) { throw e; } catch (Exception e) { throw new IOException(e); } } else if (Files.exists(Paths.get(keyConfUrl))) { // Assume the key content was passed in a valid file path return Files.readAllBytes(Paths.get(keyConfUrl)); } else if (Base64.isBase64(keyConfUrl.getBytes())) { // Assume the key content was passed in base64 try { return Decoders.BASE64.decode(keyConfUrl); } catch (DecodingException e) { String msg = "Illegal base64 character or Key file " + keyConfUrl + " doesn't exist"; throw new IOException(msg, e); } } else { String msg = "Secret/Public Key file " + keyConfUrl + " doesn't exist"; throw new IllegalArgumentException(msg); } } }
massakam/pulsar
pulsar-broker-common/src/main/java/org/apache/pulsar/broker/authentication/utils/AuthTokenUtils.java
Java
apache-2.0
4,890
/* * (c) Copyright 2019 EntIT Software LLC, a Micro Focus company, L.P. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Apache License v2.0 which accompany this distribution. * * The Apache License is available 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.cloudslang.content.amazon.factory; import io.cloudslang.content.amazon.entities.inputs.InputsWrapper; import io.cloudslang.content.amazon.factory.helpers.LoadBalancingUtils; import java.util.Map; import static io.cloudslang.content.amazon.entities.constants.Constants.LoadBalancingQueryApiActions.CREATE_LOAD_BALANCER; import static io.cloudslang.content.amazon.entities.constants.Constants.LoadBalancingQueryApiActions.DELETE_LOAD_BALANCER; import static io.cloudslang.content.amazon.entities.constants.Constants.LoadBalancingQueryApiActions.DESCRIBE_LOAD_BALANCERS; import static io.cloudslang.content.amazon.entities.constants.Constants.ErrorMessages.UNSUPPORTED_QUERY_API; /** * Created by TusaM * 11/10/2016. */ class LoadBalancingQueryParamsMapBuilder { private LoadBalancingQueryParamsMapBuilder() { // prevent instantiation } static Map<String, String> getLoadBalancingQueryParamsMap(InputsWrapper wrapper) { switch (wrapper.getCommonInputs().getAction()) { case CREATE_LOAD_BALANCER: return new LoadBalancingUtils().getCreateLoadBalancerQueryParamsMap(wrapper); case DELETE_LOAD_BALANCER: return new LoadBalancingUtils().getDeleteLoadBalancerQueryParamsMap(wrapper); case DESCRIBE_LOAD_BALANCERS: return new LoadBalancingUtils().getDescribeLoadBalancersQueryParamsMap(wrapper); default: throw new RuntimeException(UNSUPPORTED_QUERY_API); } } }
CloudSlang/cs-actions
cs-amazon/src/main/java/io/cloudslang/content/amazon/factory/LoadBalancingQueryParamsMapBuilder.java
Java
apache-2.0
2,183
/*************************************** *dipole.java *Andrew Knox 6/27/01 * *This class was written as a way to hold information about dipoles *for estaticterm.java. I'm not sure how usefull it would be as an *actual model of a dipole. */ package nanocad; public class dipole { private atom firstAtom, secondAtom; private double chargeConst; private double distribution; private boolean valid; public dipole(atom first, atom second, double charge, double dist) { if (first.isBondedWith(second) == true) { firstAtom = first; secondAtom = second; chargeConst = charge; distribution = dist; valid = true; } else valid = false; if (charge == 0.0 || dist == 0.0) valid = false; } public dipole(atom first, atom second) { if (first.isBondedWith(second) == true) { firstAtom = first; secondAtom = second; } chargeConst = 0.0; distribution = 0.0; valid = false; } public dipole() { valid = false; } public boolean isValid() { return valid; } public void setConst(double charge, double dist) { chargeConst = charge; distribution = dist; valid = true; } public double getChargeConst() { return chargeConst; } public double getDistribution() { return distribution; } public boolean isSameDipole(atom a, atom b) { if ((a == firstAtom && b == secondAtom) || (a == secondAtom && b == firstAtom)) return true; else return false; } public boolean isSameDipole(dipole d) { if ((firstAtom == d.firstAtom && secondAtom == d.secondAtom) || (firstAtom == d.secondAtom && secondAtom == d.firstAtom)) return true; else return false; } public boolean sharesAtomWith(dipole d) { if (firstAtom == d.firstAtom || firstAtom == d.secondAtom || secondAtom == d.firstAtom || secondAtom == d.secondAtom) return true; else return false; } public atom getFirst() { return firstAtom; } public atom getSecond() { return secondAtom; } }
SciGaP/SEAGrid-Desktop-GUI
src/main/java/nanocad/dipole.java
Java
apache-2.0
2,104
/* * (c) Copyright Christian P. Fries, Germany. Contact: email@christian-fries.de. * * Created on 14.06.2015 */ package net.finmath.montecarlo.interestrate.products.indices; import java.time.LocalDate; import java.util.Set; import net.finmath.exception.CalculationException; import net.finmath.montecarlo.interestrate.TermStructureMonteCarloSimulationModel; import net.finmath.stochastic.RandomVariable; /** * An index whose value is a function of the fixing date, for example the DAY, MONTH or NUMBER_OF_DAYS_IN_MONTH. * This index is useful in building date based interpolation formulas using other indices. * * @author Christian Fries * @version 1.0 */ public class DateIndex extends AbstractIndex { private static final long serialVersionUID = 7457336500162149869L; public enum DateIndexType { DAY, MONTH, YEAR, NUMBER_OF_DAYS_IN_MONTH } private final DateIndexType dateIndexType; /** * Construct a date index. * * @param name Name of this index. * @param currency Currency (if any - in natural situations this index is a scalar). * @param dateIndexType The date index type. */ public DateIndex(final String name, final String currency, final DateIndexType dateIndexType) { super(name, currency); this.dateIndexType = dateIndexType; } /** * Construct a date index. * * @param name Name of this index. * @param dateIndexType The date index type. */ public DateIndex(final String name, final DateIndexType dateIndexType) { super(name); this.dateIndexType = dateIndexType; } @Override public RandomVariable getValue(final double fixingTime, final TermStructureMonteCarloSimulationModel model) throws CalculationException { final LocalDate referenceDate = model.getModel().getForwardRateCurve().getReferenceDate() .plusDays((int)Math.round(fixingTime*365)); double value = 0; switch(dateIndexType) { case DAY: value = referenceDate.getDayOfMonth(); break; case MONTH: value = referenceDate.getMonthValue(); break; case YEAR: value = referenceDate.getYear(); break; case NUMBER_OF_DAYS_IN_MONTH: value = referenceDate.lengthOfMonth(); break; default: throw new IllegalArgumentException("Unknown dateIndexType " + dateIndexType + "."); } return model.getRandomVariableForConstant(value); } @Override public Set<String> queryUnderlyings() { return null; } }
finmath/finmath-lib
src/main/java8/net/finmath/montecarlo/interestrate/products/indices/DateIndex.java
Java
apache-2.0
2,386
/* FileSaver.js * A saveAs() & saveTextAs() FileSaver implementation. * 2014-06-24 * * Modify by Brian Chen * Author: Eli Grey, http://eligrey.com * License: X11/MIT * See https://github.com/eligrey/FileSaver.js/blob/master/LICENSE.md */ /*global self */ /*jslint bitwise: true, indent: 4, laxbreak: true, laxcomma: true, smarttabs: true, plusplus: true */ /*! @source http://purl.eligrey.com/github/FileSaver.js/blob/master/FileSaver.js */ var saveAs = saveAs // IE 10+ (native saveAs) || (typeof navigator !== "undefined" && navigator.msSaveOrOpenBlob && navigator.msSaveOrOpenBlob.bind(navigator)) // Everyone else || (function (view) { "use strict"; // IE <10 is explicitly unsupported if (typeof navigator !== "undefined" && /MSIE [1-9]\./.test(navigator.userAgent)) { return; } var doc = view.document // only get URL when necessary in case Blob.js hasn't overridden it yet , get_URL = function () { return view.URL || view.webkitURL || view; } , save_link = doc.createElementNS("http://www.w3.org/1999/xhtml", "a") , can_use_save_link = !view.externalHost && "download" in save_link , click = function (node) { var event = doc.createEvent("MouseEvents"); event.initMouseEvent( "click", true, false, view, 0, 0, 0, 0, 0 , false, false, false, false, 0, null ); node.dispatchEvent(event); } , webkit_req_fs = view.webkitRequestFileSystem , req_fs = view.requestFileSystem || webkit_req_fs || view.mozRequestFileSystem , throw_outside = function (ex) { (view.setImmediate || view.setTimeout)(function () { throw ex; }, 0); } , force_saveable_type = "application/octet-stream" , fs_min_size = 0 , deletion_queue = [] , process_deletion_queue = function () { var i = deletion_queue.length; while (i--) { var file = deletion_queue[i]; if (typeof file === "string") { // file is an object URL get_URL().revokeObjectURL(file); } else { // file is a File file.remove(); } } deletion_queue.length = 0; // clear queue } , dispatch = function (filesaver, event_types, event) { event_types = [].concat(event_types); var i = event_types.length; while (i--) { var listener = filesaver["on" + event_types[i]]; if (typeof listener === "function") { try { listener.call(filesaver, event || filesaver); } catch (ex) { throw_outside(ex); } } } } , FileSaver = function (blob, name) { // First try a.download, then web filesystem, then object URLs var filesaver = this , type = blob.type , blob_changed = false , object_url , target_view , get_object_url = function () { var object_url = get_URL().createObjectURL(blob); deletion_queue.push(object_url); return object_url; } , dispatch_all = function () { dispatch(filesaver, "writestart progress write writeend".split(" ")); } // on any filesys errors revert to saving with object URLs , fs_error = function () { // don't create more object URLs than needed if (blob_changed || !object_url) { object_url = get_object_url(blob); } if (target_view) { target_view.location.href = object_url; } else { window.open(object_url, "_blank"); } filesaver.readyState = filesaver.DONE; dispatch_all(); } , abortable = function (func) { return function () { if (filesaver.readyState !== filesaver.DONE) { return func.apply(this, arguments); } }; } , create_if_not_found = { create: true, exclusive: false } , slice ; filesaver.readyState = filesaver.INIT; if (!name) { name = "download"; } if (can_use_save_link) { object_url = get_object_url(blob); save_link.href = object_url; save_link.download = name; click(save_link); filesaver.readyState = filesaver.DONE; dispatch_all(); return; } // Object and web filesystem URLs have a problem saving in Google Chrome when // viewed in a tab, so I force save with application/octet-stream // http://code.google.com/p/chromium/issues/detail?id=91158 if (view.chrome && type && type !== force_saveable_type) { slice = blob.slice || blob.webkitSlice; blob = slice.call(blob, 0, blob.size, force_saveable_type); blob_changed = true; } // Since I can't be sure that the guessed media type will trigger a download // in WebKit, I append .download to the filename. // https://bugs.webkit.org/show_bug.cgi?id=65440 if (webkit_req_fs && name !== "download") { name += ".download"; } if (type === force_saveable_type || webkit_req_fs) { target_view = view; } if (!req_fs) { fs_error(); return; } fs_min_size += blob.size; req_fs(view.TEMPORARY, fs_min_size, abortable(function (fs) { fs.root.getDirectory("saved", create_if_not_found, abortable(function (dir) { var save = function () { dir.getFile(name, create_if_not_found, abortable(function (file) { file.createWriter(abortable(function (writer) { writer.onwriteend = function (event) { target_view.location.href = file.toURL(); deletion_queue.push(file); filesaver.readyState = filesaver.DONE; dispatch(filesaver, "writeend", event); }; writer.onerror = function () { var error = writer.error; if (error.code !== error.ABORT_ERR) { fs_error(); } }; "writestart progress write abort".split(" ").forEach(function (event) { writer["on" + event] = filesaver["on" + event]; }); writer.write(blob); filesaver.abort = function () { writer.abort(); filesaver.readyState = filesaver.DONE; }; filesaver.readyState = filesaver.WRITING; }), fs_error); }), fs_error); }; dir.getFile(name, { create: false }, abortable(function (file) { // delete file if it already exists file.remove(); save(); }), abortable(function (ex) { if (ex.code === ex.NOT_FOUND_ERR) { save(); } else { fs_error(); } })); }), fs_error); }), fs_error); } , FS_proto = FileSaver.prototype , saveAs = function (blob, name) { return new FileSaver(blob, name); } ; FS_proto.abort = function () { var filesaver = this; filesaver.readyState = filesaver.DONE; dispatch(filesaver, "abort"); }; FS_proto.readyState = FS_proto.INIT = 0; FS_proto.WRITING = 1; FS_proto.DONE = 2; FS_proto.error = FS_proto.onwritestart = FS_proto.onprogress = FS_proto.onwrite = FS_proto.onabort = FS_proto.onerror = FS_proto.onwriteend = null; view.addEventListener("unload", process_deletion_queue, false); saveAs.unload = function () { process_deletion_queue(); view.removeEventListener("unload", process_deletion_queue, false); }; return saveAs; }( typeof self !== "undefined" && self || typeof window !== "undefined" && window || this.content )); // `self` is undefined in Firefox for Android content script context // while `this` is nsIContentFrameMessageManager // with an attribute `content` that corresponds to the window if (typeof module !== "undefined" && module !== null) { module.exports = saveAs; } else if ((typeof define !== "undefined" && define !== null) && (define.amd != null)) { define([], function () { return saveAs; }); } String.prototype.endsWithAny = function () { var strArray = Array.prototype.slice.call(arguments), $this = this.toLowerCase().toString(); for (var i = 0; i < strArray.length; i++) { if ($this.indexOf(strArray[i], $this.length - strArray[i].length) !== -1) return true; } return false; }; var saveTextAs = saveTextAs || (function (textContent, fileName, charset) { fileName = fileName || 'download.txt'; charset = charset || 'utf-8'; textContent = (textContent || '').replace(/\r?\n/g, "\r\n"); if (saveAs && Blob) { var blob = new Blob([textContent], { type: "text/plain;charset=" + charset }); saveAs(blob, fileName); return true; } else {//IE9- var saveTxtWindow = window.frames.saveTxtWindow; if (!saveTxtWindow) { saveTxtWindow = document.createElement('iframe'); saveTxtWindow.id = 'saveTxtWindow'; saveTxtWindow.style.display = 'none'; document.body.insertBefore(saveTxtWindow, null); saveTxtWindow = window.frames.saveTxtWindow; if (!saveTxtWindow) { saveTxtWindow = window.open('', '_temp', 'width=100,height=100'); if (!saveTxtWindow) { window.alert('Sorry, download file could not be created.'); return false; } } } var doc = saveTxtWindow.document; doc.open('text/html', 'replace'); doc.charset = charset; if (fileName.endsWithAny('.htm', '.html')) { doc.close(); doc.body.innerHTML = '\r\n' + textContent + '\r\n'; } else { if (!fileName.endsWithAny('.txt')) fileName += '.txt'; doc.write(textContent); doc.close(); } var retValue = doc.execCommand('SaveAs', null, fileName); saveTxtWindow.close(); return retValue; } })
PTRPlay/PrompterPro
Main/SoftServe.ITA.PrompterPro/PrompterPro.WebApplication/Scripts/FileSaver.js
JavaScript
apache-2.0
12,241
package io.dropwizard.migrations; import com.google.common.base.Charsets; import io.dropwizard.Configuration; import io.dropwizard.db.DatabaseConfiguration; import liquibase.Liquibase; import liquibase.diff.DiffGeneratorFactory; import liquibase.diff.DiffResult; import liquibase.diff.compare.CompareControl; import liquibase.diff.output.DiffOutputControl; import liquibase.diff.output.changelog.DiffToChangeLog; import liquibase.structure.DatabaseObject; import liquibase.structure.core.*; import net.sourceforge.argparse4j.impl.Arguments; import net.sourceforge.argparse4j.inf.ArgumentGroup; import net.sourceforge.argparse4j.inf.Namespace; import net.sourceforge.argparse4j.inf.Subparser; import java.io.PrintStream; import java.util.HashSet; import java.util.Set; public class DbDumpCommand<T extends Configuration> extends AbstractLiquibaseCommand<T> { public DbDumpCommand(DatabaseConfiguration<T> strategy, Class<T> configurationClass) { super("dump", "Generate a dump of the existing database state.", strategy, configurationClass); } @Override public void configure(Subparser subparser) { super.configure(subparser); subparser.addArgument("-o", "--output") .dest("output") .help("Write output to <file> instead of stdout"); final ArgumentGroup tables = subparser.addArgumentGroup("Tables"); tables.addArgument("--tables") .action(Arguments.storeTrue()) .dest("tables") .help("Check for added or removed tables (default)"); tables.addArgument("--ignore-tables") .action(Arguments.storeFalse()) .dest("tables") .help("Ignore tables"); final ArgumentGroup columns = subparser.addArgumentGroup("Columns"); columns.addArgument("--columns") .action(Arguments.storeTrue()) .dest("columns") .help("Check for added, removed, or modified tables (default)"); columns.addArgument("--ignore-columns") .action(Arguments.storeFalse()) .dest("columns") .help("Ignore columns"); final ArgumentGroup views = subparser.addArgumentGroup("Views"); views.addArgument("--views") .action(Arguments.storeTrue()) .dest("views") .help("Check for added, removed, or modified views (default)"); views.addArgument("--ignore-views") .action(Arguments.storeFalse()) .dest("views") .help("Ignore views"); final ArgumentGroup primaryKeys = subparser.addArgumentGroup("Primary Keys"); primaryKeys.addArgument("--primary-keys") .action(Arguments.storeTrue()) .dest("primary-keys") .help("Check for changed primary keys (default)"); primaryKeys.addArgument("--ignore-primary-keys") .action(Arguments.storeFalse()) .dest("primary-keys") .help("Ignore primary keys"); final ArgumentGroup uniqueConstraints = subparser.addArgumentGroup("Unique Constraints"); uniqueConstraints.addArgument("--unique-constraints") .action(Arguments.storeTrue()) .dest("unique-constraints") .help("Check for changed unique constraints (default)"); uniqueConstraints.addArgument("--ignore-unique-constraints") .action(Arguments.storeFalse()) .dest("unique-constraints") .help("Ignore unique constraints"); final ArgumentGroup indexes = subparser.addArgumentGroup("Indexes"); indexes.addArgument("--indexes") .action(Arguments.storeTrue()) .dest("indexes") .help("Check for changed indexes (default)"); indexes.addArgument("--ignore-indexes") .action(Arguments.storeFalse()) .dest("indexes") .help("Ignore indexes"); final ArgumentGroup foreignKeys = subparser.addArgumentGroup("Foreign Keys"); foreignKeys.addArgument("--foreign-keys") .action(Arguments.storeTrue()) .dest("foreign-keys") .help("Check for changed foreign keys (default)"); foreignKeys.addArgument("--ignore-foreign-keys") .action(Arguments.storeFalse()) .dest("foreign-keys") .help("Ignore foreign keys"); final ArgumentGroup sequences = subparser.addArgumentGroup("Sequences"); sequences.addArgument("--sequences") .action(Arguments.storeTrue()) .dest("sequences") .help("Check for changed sequences (default)"); sequences.addArgument("--ignore-sequences") .action(Arguments.storeFalse()) .dest("sequences") .help("Ignore foreign keys"); final ArgumentGroup data = subparser.addArgumentGroup("Data"); data.addArgument("--data") .action(Arguments.storeTrue()) .dest("data") .help("Check for changed data") .setDefault(Boolean.FALSE); data.addArgument("--ignore-data") .action(Arguments.storeFalse()) .dest("data") .help("Ignore data (default)") .setDefault(Boolean.FALSE); } @Override @SuppressWarnings("UseOfSystemOutOrSystemErr") public void run(Namespace namespace, Liquibase liquibase) throws Exception { final Set<Class<? extends DatabaseObject>> compareTypes = new HashSet<>(); if (namespace.getBoolean("columns")) { compareTypes.add(Column.class); } if (namespace.getBoolean("data")) { compareTypes.add(Data.class); } if (namespace.getBoolean("foreign-keys")) { compareTypes.add(ForeignKey.class); } if (namespace.getBoolean("indexes")) { compareTypes.add(Index.class); } if (namespace.getBoolean("primary-keys")) { compareTypes.add(PrimaryKey.class); } if (namespace.getBoolean("sequences")) { compareTypes.add(Sequence.class); } if (namespace.getBoolean("tables")) { compareTypes.add(Table.class); } if (namespace.getBoolean("unique-constraints")) { compareTypes.add(UniqueConstraint.class); } if (namespace.getBoolean("views")) { compareTypes.add(View.class); } final DiffResult diffResult = DiffGeneratorFactory.getInstance().compare( liquibase.getDatabase(), null, new CompareControl(compareTypes)); final DiffToChangeLog diffToChangeLog = new DiffToChangeLog(diffResult, new DiffOutputControl()); final String filename = namespace.getString("output"); if (filename != null) { try (PrintStream file = new PrintStream(filename, Charsets.UTF_8.name())) { diffToChangeLog.print(file); } } else { diffToChangeLog.print(System.out); } } }
vimond/dropwizard
dropwizard-migrations/src/main/java/io/dropwizard/migrations/DbDumpCommand.java
Java
apache-2.0
7,326
package org.alien4cloud.tosca.exceptions; import alien4cloud.exception.TechnicalException; /** * Base class for all constraint related exceptions * * @author mkv * */ public class ConstraintTechnicalException extends TechnicalException { private static final long serialVersionUID = 5829360730980521567L; public ConstraintTechnicalException(String message, Throwable cause) { super(message, cause); } public ConstraintTechnicalException(String message) { super(message); } }
alien4cloud/alien4cloud
alien4cloud-tosca/src/main/java/org/alien4cloud/tosca/exceptions/ConstraintTechnicalException.java
Java
apache-2.0
524
// This file was generated by counterfeiter package fakes import ( "sync" "github.com/cloudfoundry/cli/cf/api" "github.com/cloudfoundry/cli/cf/api/resources" "github.com/cloudfoundry/cli/cf/models" ) type FakeServiceRepository struct { PurgeServiceOfferingStub func(offering models.ServiceOffering) error purgeServiceOfferingMutex sync.RWMutex purgeServiceOfferingArgsForCall []struct { offering models.ServiceOffering } purgeServiceOfferingReturns struct { result1 error } GetServiceOfferingByGuidStub func(serviceGuid string) (offering models.ServiceOffering, apiErr error) getServiceOfferingByGuidMutex sync.RWMutex getServiceOfferingByGuidArgsForCall []struct { serviceGuid string } getServiceOfferingByGuidReturns struct { result1 models.ServiceOffering result2 error } FindServiceOfferingsByLabelStub func(name string) (offering models.ServiceOfferings, apiErr error) findServiceOfferingsByLabelMutex sync.RWMutex findServiceOfferingsByLabelArgsForCall []struct { name string } findServiceOfferingsByLabelReturns struct { result1 models.ServiceOfferings result2 error } FindServiceOfferingByLabelAndProviderStub func(name, provider string) (offering models.ServiceOffering, apiErr error) findServiceOfferingByLabelAndProviderMutex sync.RWMutex findServiceOfferingByLabelAndProviderArgsForCall []struct { name string provider string } findServiceOfferingByLabelAndProviderReturns struct { result1 models.ServiceOffering result2 error } FindServiceOfferingsForSpaceByLabelStub func(spaceGuid, name string) (offering models.ServiceOfferings, apiErr error) findServiceOfferingsForSpaceByLabelMutex sync.RWMutex findServiceOfferingsForSpaceByLabelArgsForCall []struct { spaceGuid string name string } findServiceOfferingsForSpaceByLabelReturns struct { result1 models.ServiceOfferings result2 error } GetAllServiceOfferingsStub func() (offerings models.ServiceOfferings, apiErr error) getAllServiceOfferingsMutex sync.RWMutex getAllServiceOfferingsArgsForCall []struct{} getAllServiceOfferingsReturns struct { result1 models.ServiceOfferings result2 error } GetServiceOfferingsForSpaceStub func(spaceGuid string) (offerings models.ServiceOfferings, apiErr error) getServiceOfferingsForSpaceMutex sync.RWMutex getServiceOfferingsForSpaceArgsForCall []struct { spaceGuid string } getServiceOfferingsForSpaceReturns struct { result1 models.ServiceOfferings result2 error } FindInstanceByNameStub func(name string) (instance models.ServiceInstance, apiErr error) findInstanceByNameMutex sync.RWMutex findInstanceByNameArgsForCall []struct { name string } findInstanceByNameReturns struct { result1 models.ServiceInstance result2 error } PurgeServiceInstanceStub func(instance models.ServiceInstance) error purgeServiceInstanceMutex sync.RWMutex purgeServiceInstanceArgsForCall []struct { instance models.ServiceInstance } purgeServiceInstanceReturns struct { result1 error } CreateServiceInstanceStub func(name, planGuid string, params map[string]interface{}, tags []string) (apiErr error) createServiceInstanceMutex sync.RWMutex createServiceInstanceArgsForCall []struct { name string planGuid string params map[string]interface{} tags []string } createServiceInstanceReturns struct { result1 error } UpdateServiceInstanceStub func(instanceGuid, planGuid string, params map[string]interface{}, tags []string) (apiErr error) updateServiceInstanceMutex sync.RWMutex updateServiceInstanceArgsForCall []struct { instanceGuid string planGuid string params map[string]interface{} tags []string } updateServiceInstanceReturns struct { result1 error } RenameServiceStub func(instance models.ServiceInstance, newName string) (apiErr error) renameServiceMutex sync.RWMutex renameServiceArgsForCall []struct { instance models.ServiceInstance newName string } renameServiceReturns struct { result1 error } DeleteServiceStub func(instance models.ServiceInstance) (apiErr error) deleteServiceMutex sync.RWMutex deleteServiceArgsForCall []struct { instance models.ServiceInstance } deleteServiceReturns struct { result1 error } FindServicePlanByDescriptionStub func(planDescription resources.ServicePlanDescription) (planGuid string, apiErr error) findServicePlanByDescriptionMutex sync.RWMutex findServicePlanByDescriptionArgsForCall []struct { planDescription resources.ServicePlanDescription } findServicePlanByDescriptionReturns struct { result1 string result2 error } ListServicesFromBrokerStub func(brokerGuid string) (services []models.ServiceOffering, err error) listServicesFromBrokerMutex sync.RWMutex listServicesFromBrokerArgsForCall []struct { brokerGuid string } listServicesFromBrokerReturns struct { result1 []models.ServiceOffering result2 error } ListServicesFromManyBrokersStub func(brokerGuids []string) (services []models.ServiceOffering, err error) listServicesFromManyBrokersMutex sync.RWMutex listServicesFromManyBrokersArgsForCall []struct { brokerGuids []string } listServicesFromManyBrokersReturns struct { result1 []models.ServiceOffering result2 error } GetServiceInstanceCountForServicePlanStub func(v1PlanGuid string) (count int, apiErr error) getServiceInstanceCountForServicePlanMutex sync.RWMutex getServiceInstanceCountForServicePlanArgsForCall []struct { v1PlanGuid string } getServiceInstanceCountForServicePlanReturns struct { result1 int result2 error } MigrateServicePlanFromV1ToV2Stub func(v1PlanGuid, v2PlanGuid string) (changedCount int, apiErr error) migrateServicePlanFromV1ToV2Mutex sync.RWMutex migrateServicePlanFromV1ToV2ArgsForCall []struct { v1PlanGuid string v2PlanGuid string } migrateServicePlanFromV1ToV2Returns struct { result1 int result2 error } } func (fake *FakeServiceRepository) PurgeServiceOffering(offering models.ServiceOffering) error { fake.purgeServiceOfferingMutex.Lock() fake.purgeServiceOfferingArgsForCall = append(fake.purgeServiceOfferingArgsForCall, struct { offering models.ServiceOffering }{offering}) fake.purgeServiceOfferingMutex.Unlock() if fake.PurgeServiceOfferingStub != nil { return fake.PurgeServiceOfferingStub(offering) } else { return fake.purgeServiceOfferingReturns.result1 } } func (fake *FakeServiceRepository) PurgeServiceOfferingCallCount() int { fake.purgeServiceOfferingMutex.RLock() defer fake.purgeServiceOfferingMutex.RUnlock() return len(fake.purgeServiceOfferingArgsForCall) } func (fake *FakeServiceRepository) PurgeServiceOfferingArgsForCall(i int) models.ServiceOffering { fake.purgeServiceOfferingMutex.RLock() defer fake.purgeServiceOfferingMutex.RUnlock() return fake.purgeServiceOfferingArgsForCall[i].offering } func (fake *FakeServiceRepository) PurgeServiceOfferingReturns(result1 error) { fake.PurgeServiceOfferingStub = nil fake.purgeServiceOfferingReturns = struct { result1 error }{result1} } func (fake *FakeServiceRepository) GetServiceOfferingByGuid(serviceGuid string) (offering models.ServiceOffering, apiErr error) { fake.getServiceOfferingByGuidMutex.Lock() fake.getServiceOfferingByGuidArgsForCall = append(fake.getServiceOfferingByGuidArgsForCall, struct { serviceGuid string }{serviceGuid}) fake.getServiceOfferingByGuidMutex.Unlock() if fake.GetServiceOfferingByGuidStub != nil { return fake.GetServiceOfferingByGuidStub(serviceGuid) } else { return fake.getServiceOfferingByGuidReturns.result1, fake.getServiceOfferingByGuidReturns.result2 } } func (fake *FakeServiceRepository) GetServiceOfferingByGuidCallCount() int { fake.getServiceOfferingByGuidMutex.RLock() defer fake.getServiceOfferingByGuidMutex.RUnlock() return len(fake.getServiceOfferingByGuidArgsForCall) } func (fake *FakeServiceRepository) GetServiceOfferingByGuidArgsForCall(i int) string { fake.getServiceOfferingByGuidMutex.RLock() defer fake.getServiceOfferingByGuidMutex.RUnlock() return fake.getServiceOfferingByGuidArgsForCall[i].serviceGuid } func (fake *FakeServiceRepository) GetServiceOfferingByGuidReturns(result1 models.ServiceOffering, result2 error) { fake.GetServiceOfferingByGuidStub = nil fake.getServiceOfferingByGuidReturns = struct { result1 models.ServiceOffering result2 error }{result1, result2} } func (fake *FakeServiceRepository) FindServiceOfferingsByLabel(name string) (offering models.ServiceOfferings, apiErr error) { fake.findServiceOfferingsByLabelMutex.Lock() fake.findServiceOfferingsByLabelArgsForCall = append(fake.findServiceOfferingsByLabelArgsForCall, struct { name string }{name}) fake.findServiceOfferingsByLabelMutex.Unlock() if fake.FindServiceOfferingsByLabelStub != nil { return fake.FindServiceOfferingsByLabelStub(name) } else { return fake.findServiceOfferingsByLabelReturns.result1, fake.findServiceOfferingsByLabelReturns.result2 } } func (fake *FakeServiceRepository) FindServiceOfferingsByLabelCallCount() int { fake.findServiceOfferingsByLabelMutex.RLock() defer fake.findServiceOfferingsByLabelMutex.RUnlock() return len(fake.findServiceOfferingsByLabelArgsForCall) } func (fake *FakeServiceRepository) FindServiceOfferingsByLabelArgsForCall(i int) string { fake.findServiceOfferingsByLabelMutex.RLock() defer fake.findServiceOfferingsByLabelMutex.RUnlock() return fake.findServiceOfferingsByLabelArgsForCall[i].name } func (fake *FakeServiceRepository) FindServiceOfferingsByLabelReturns(result1 models.ServiceOfferings, result2 error) { fake.FindServiceOfferingsByLabelStub = nil fake.findServiceOfferingsByLabelReturns = struct { result1 models.ServiceOfferings result2 error }{result1, result2} } func (fake *FakeServiceRepository) FindServiceOfferingByLabelAndProvider(name string, provider string) (offering models.ServiceOffering, apiErr error) { fake.findServiceOfferingByLabelAndProviderMutex.Lock() fake.findServiceOfferingByLabelAndProviderArgsForCall = append(fake.findServiceOfferingByLabelAndProviderArgsForCall, struct { name string provider string }{name, provider}) fake.findServiceOfferingByLabelAndProviderMutex.Unlock() if fake.FindServiceOfferingByLabelAndProviderStub != nil { return fake.FindServiceOfferingByLabelAndProviderStub(name, provider) } else { return fake.findServiceOfferingByLabelAndProviderReturns.result1, fake.findServiceOfferingByLabelAndProviderReturns.result2 } } func (fake *FakeServiceRepository) FindServiceOfferingByLabelAndProviderCallCount() int { fake.findServiceOfferingByLabelAndProviderMutex.RLock() defer fake.findServiceOfferingByLabelAndProviderMutex.RUnlock() return len(fake.findServiceOfferingByLabelAndProviderArgsForCall) } func (fake *FakeServiceRepository) FindServiceOfferingByLabelAndProviderArgsForCall(i int) (string, string) { fake.findServiceOfferingByLabelAndProviderMutex.RLock() defer fake.findServiceOfferingByLabelAndProviderMutex.RUnlock() return fake.findServiceOfferingByLabelAndProviderArgsForCall[i].name, fake.findServiceOfferingByLabelAndProviderArgsForCall[i].provider } func (fake *FakeServiceRepository) FindServiceOfferingByLabelAndProviderReturns(result1 models.ServiceOffering, result2 error) { fake.FindServiceOfferingByLabelAndProviderStub = nil fake.findServiceOfferingByLabelAndProviderReturns = struct { result1 models.ServiceOffering result2 error }{result1, result2} } func (fake *FakeServiceRepository) FindServiceOfferingsForSpaceByLabel(spaceGuid string, name string) (offering models.ServiceOfferings, apiErr error) { fake.findServiceOfferingsForSpaceByLabelMutex.Lock() fake.findServiceOfferingsForSpaceByLabelArgsForCall = append(fake.findServiceOfferingsForSpaceByLabelArgsForCall, struct { spaceGuid string name string }{spaceGuid, name}) fake.findServiceOfferingsForSpaceByLabelMutex.Unlock() if fake.FindServiceOfferingsForSpaceByLabelStub != nil { return fake.FindServiceOfferingsForSpaceByLabelStub(spaceGuid, name) } else { return fake.findServiceOfferingsForSpaceByLabelReturns.result1, fake.findServiceOfferingsForSpaceByLabelReturns.result2 } } func (fake *FakeServiceRepository) FindServiceOfferingsForSpaceByLabelCallCount() int { fake.findServiceOfferingsForSpaceByLabelMutex.RLock() defer fake.findServiceOfferingsForSpaceByLabelMutex.RUnlock() return len(fake.findServiceOfferingsForSpaceByLabelArgsForCall) } func (fake *FakeServiceRepository) FindServiceOfferingsForSpaceByLabelArgsForCall(i int) (string, string) { fake.findServiceOfferingsForSpaceByLabelMutex.RLock() defer fake.findServiceOfferingsForSpaceByLabelMutex.RUnlock() return fake.findServiceOfferingsForSpaceByLabelArgsForCall[i].spaceGuid, fake.findServiceOfferingsForSpaceByLabelArgsForCall[i].name } func (fake *FakeServiceRepository) FindServiceOfferingsForSpaceByLabelReturns(result1 models.ServiceOfferings, result2 error) { fake.FindServiceOfferingsForSpaceByLabelStub = nil fake.findServiceOfferingsForSpaceByLabelReturns = struct { result1 models.ServiceOfferings result2 error }{result1, result2} } func (fake *FakeServiceRepository) GetAllServiceOfferings() (offerings models.ServiceOfferings, apiErr error) { fake.getAllServiceOfferingsMutex.Lock() fake.getAllServiceOfferingsArgsForCall = append(fake.getAllServiceOfferingsArgsForCall, struct{}{}) fake.getAllServiceOfferingsMutex.Unlock() if fake.GetAllServiceOfferingsStub != nil { return fake.GetAllServiceOfferingsStub() } else { return fake.getAllServiceOfferingsReturns.result1, fake.getAllServiceOfferingsReturns.result2 } } func (fake *FakeServiceRepository) GetAllServiceOfferingsCallCount() int { fake.getAllServiceOfferingsMutex.RLock() defer fake.getAllServiceOfferingsMutex.RUnlock() return len(fake.getAllServiceOfferingsArgsForCall) } func (fake *FakeServiceRepository) GetAllServiceOfferingsReturns(result1 models.ServiceOfferings, result2 error) { fake.GetAllServiceOfferingsStub = nil fake.getAllServiceOfferingsReturns = struct { result1 models.ServiceOfferings result2 error }{result1, result2} } func (fake *FakeServiceRepository) GetServiceOfferingsForSpace(spaceGuid string) (offerings models.ServiceOfferings, apiErr error) { fake.getServiceOfferingsForSpaceMutex.Lock() fake.getServiceOfferingsForSpaceArgsForCall = append(fake.getServiceOfferingsForSpaceArgsForCall, struct { spaceGuid string }{spaceGuid}) fake.getServiceOfferingsForSpaceMutex.Unlock() if fake.GetServiceOfferingsForSpaceStub != nil { return fake.GetServiceOfferingsForSpaceStub(spaceGuid) } else { return fake.getServiceOfferingsForSpaceReturns.result1, fake.getServiceOfferingsForSpaceReturns.result2 } } func (fake *FakeServiceRepository) GetServiceOfferingsForSpaceCallCount() int { fake.getServiceOfferingsForSpaceMutex.RLock() defer fake.getServiceOfferingsForSpaceMutex.RUnlock() return len(fake.getServiceOfferingsForSpaceArgsForCall) } func (fake *FakeServiceRepository) GetServiceOfferingsForSpaceArgsForCall(i int) string { fake.getServiceOfferingsForSpaceMutex.RLock() defer fake.getServiceOfferingsForSpaceMutex.RUnlock() return fake.getServiceOfferingsForSpaceArgsForCall[i].spaceGuid } func (fake *FakeServiceRepository) GetServiceOfferingsForSpaceReturns(result1 models.ServiceOfferings, result2 error) { fake.GetServiceOfferingsForSpaceStub = nil fake.getServiceOfferingsForSpaceReturns = struct { result1 models.ServiceOfferings result2 error }{result1, result2} } func (fake *FakeServiceRepository) FindInstanceByName(name string) (instance models.ServiceInstance, apiErr error) { fake.findInstanceByNameMutex.Lock() fake.findInstanceByNameArgsForCall = append(fake.findInstanceByNameArgsForCall, struct { name string }{name}) fake.findInstanceByNameMutex.Unlock() if fake.FindInstanceByNameStub != nil { return fake.FindInstanceByNameStub(name) } else { return fake.findInstanceByNameReturns.result1, fake.findInstanceByNameReturns.result2 } } func (fake *FakeServiceRepository) FindInstanceByNameCallCount() int { fake.findInstanceByNameMutex.RLock() defer fake.findInstanceByNameMutex.RUnlock() return len(fake.findInstanceByNameArgsForCall) } func (fake *FakeServiceRepository) FindInstanceByNameArgsForCall(i int) string { fake.findInstanceByNameMutex.RLock() defer fake.findInstanceByNameMutex.RUnlock() return fake.findInstanceByNameArgsForCall[i].name } func (fake *FakeServiceRepository) FindInstanceByNameReturns(result1 models.ServiceInstance, result2 error) { fake.FindInstanceByNameStub = nil fake.findInstanceByNameReturns = struct { result1 models.ServiceInstance result2 error }{result1, result2} } func (fake *FakeServiceRepository) PurgeServiceInstance(instance models.ServiceInstance) error { fake.purgeServiceInstanceMutex.Lock() fake.purgeServiceInstanceArgsForCall = append(fake.purgeServiceInstanceArgsForCall, struct { instance models.ServiceInstance }{instance}) fake.purgeServiceInstanceMutex.Unlock() if fake.PurgeServiceInstanceStub != nil { return fake.PurgeServiceInstanceStub(instance) } else { return fake.purgeServiceInstanceReturns.result1 } } func (fake *FakeServiceRepository) PurgeServiceInstanceCallCount() int { fake.purgeServiceInstanceMutex.RLock() defer fake.purgeServiceInstanceMutex.RUnlock() return len(fake.purgeServiceInstanceArgsForCall) } func (fake *FakeServiceRepository) PurgeServiceInstanceArgsForCall(i int) models.ServiceInstance { fake.purgeServiceInstanceMutex.RLock() defer fake.purgeServiceInstanceMutex.RUnlock() return fake.purgeServiceInstanceArgsForCall[i].instance } func (fake *FakeServiceRepository) PurgeServiceInstanceReturns(result1 error) { fake.PurgeServiceInstanceStub = nil fake.purgeServiceInstanceReturns = struct { result1 error }{result1} } func (fake *FakeServiceRepository) CreateServiceInstance(name string, planGuid string, params map[string]interface{}, tags []string) (apiErr error) { fake.createServiceInstanceMutex.Lock() fake.createServiceInstanceArgsForCall = append(fake.createServiceInstanceArgsForCall, struct { name string planGuid string params map[string]interface{} tags []string }{name, planGuid, params, tags}) fake.createServiceInstanceMutex.Unlock() if fake.CreateServiceInstanceStub != nil { return fake.CreateServiceInstanceStub(name, planGuid, params, tags) } else { return fake.createServiceInstanceReturns.result1 } } func (fake *FakeServiceRepository) CreateServiceInstanceCallCount() int { fake.createServiceInstanceMutex.RLock() defer fake.createServiceInstanceMutex.RUnlock() return len(fake.createServiceInstanceArgsForCall) } func (fake *FakeServiceRepository) CreateServiceInstanceArgsForCall(i int) (string, string, map[string]interface{}, []string) { fake.createServiceInstanceMutex.RLock() defer fake.createServiceInstanceMutex.RUnlock() return fake.createServiceInstanceArgsForCall[i].name, fake.createServiceInstanceArgsForCall[i].planGuid, fake.createServiceInstanceArgsForCall[i].params, fake.createServiceInstanceArgsForCall[i].tags } func (fake *FakeServiceRepository) CreateServiceInstanceReturns(result1 error) { fake.CreateServiceInstanceStub = nil fake.createServiceInstanceReturns = struct { result1 error }{result1} } func (fake *FakeServiceRepository) UpdateServiceInstance(instanceGuid string, planGuid string, params map[string]interface{}, tags []string) (apiErr error) { fake.updateServiceInstanceMutex.Lock() fake.updateServiceInstanceArgsForCall = append(fake.updateServiceInstanceArgsForCall, struct { instanceGuid string planGuid string params map[string]interface{} tags []string }{instanceGuid, planGuid, params, tags}) fake.updateServiceInstanceMutex.Unlock() if fake.UpdateServiceInstanceStub != nil { return fake.UpdateServiceInstanceStub(instanceGuid, planGuid, params, tags) } else { return fake.updateServiceInstanceReturns.result1 } } func (fake *FakeServiceRepository) UpdateServiceInstanceCallCount() int { fake.updateServiceInstanceMutex.RLock() defer fake.updateServiceInstanceMutex.RUnlock() return len(fake.updateServiceInstanceArgsForCall) } func (fake *FakeServiceRepository) UpdateServiceInstanceArgsForCall(i int) (string, string, map[string]interface{}, []string) { fake.updateServiceInstanceMutex.RLock() defer fake.updateServiceInstanceMutex.RUnlock() return fake.updateServiceInstanceArgsForCall[i].instanceGuid, fake.updateServiceInstanceArgsForCall[i].planGuid, fake.updateServiceInstanceArgsForCall[i].params, fake.updateServiceInstanceArgsForCall[i].tags } func (fake *FakeServiceRepository) UpdateServiceInstanceReturns(result1 error) { fake.UpdateServiceInstanceStub = nil fake.updateServiceInstanceReturns = struct { result1 error }{result1} } func (fake *FakeServiceRepository) RenameService(instance models.ServiceInstance, newName string) (apiErr error) { fake.renameServiceMutex.Lock() fake.renameServiceArgsForCall = append(fake.renameServiceArgsForCall, struct { instance models.ServiceInstance newName string }{instance, newName}) fake.renameServiceMutex.Unlock() if fake.RenameServiceStub != nil { return fake.RenameServiceStub(instance, newName) } else { return fake.renameServiceReturns.result1 } } func (fake *FakeServiceRepository) RenameServiceCallCount() int { fake.renameServiceMutex.RLock() defer fake.renameServiceMutex.RUnlock() return len(fake.renameServiceArgsForCall) } func (fake *FakeServiceRepository) RenameServiceArgsForCall(i int) (models.ServiceInstance, string) { fake.renameServiceMutex.RLock() defer fake.renameServiceMutex.RUnlock() return fake.renameServiceArgsForCall[i].instance, fake.renameServiceArgsForCall[i].newName } func (fake *FakeServiceRepository) RenameServiceReturns(result1 error) { fake.RenameServiceStub = nil fake.renameServiceReturns = struct { result1 error }{result1} } func (fake *FakeServiceRepository) DeleteService(instance models.ServiceInstance) (apiErr error) { fake.deleteServiceMutex.Lock() fake.deleteServiceArgsForCall = append(fake.deleteServiceArgsForCall, struct { instance models.ServiceInstance }{instance}) fake.deleteServiceMutex.Unlock() if fake.DeleteServiceStub != nil { return fake.DeleteServiceStub(instance) } else { return fake.deleteServiceReturns.result1 } } func (fake *FakeServiceRepository) DeleteServiceCallCount() int { fake.deleteServiceMutex.RLock() defer fake.deleteServiceMutex.RUnlock() return len(fake.deleteServiceArgsForCall) } func (fake *FakeServiceRepository) DeleteServiceArgsForCall(i int) models.ServiceInstance { fake.deleteServiceMutex.RLock() defer fake.deleteServiceMutex.RUnlock() return fake.deleteServiceArgsForCall[i].instance } func (fake *FakeServiceRepository) DeleteServiceReturns(result1 error) { fake.DeleteServiceStub = nil fake.deleteServiceReturns = struct { result1 error }{result1} } func (fake *FakeServiceRepository) FindServicePlanByDescription(planDescription resources.ServicePlanDescription) (planGuid string, apiErr error) { fake.findServicePlanByDescriptionMutex.Lock() fake.findServicePlanByDescriptionArgsForCall = append(fake.findServicePlanByDescriptionArgsForCall, struct { planDescription resources.ServicePlanDescription }{planDescription}) fake.findServicePlanByDescriptionMutex.Unlock() if fake.FindServicePlanByDescriptionStub != nil { return fake.FindServicePlanByDescriptionStub(planDescription) } else { return fake.findServicePlanByDescriptionReturns.result1, fake.findServicePlanByDescriptionReturns.result2 } } func (fake *FakeServiceRepository) FindServicePlanByDescriptionCallCount() int { fake.findServicePlanByDescriptionMutex.RLock() defer fake.findServicePlanByDescriptionMutex.RUnlock() return len(fake.findServicePlanByDescriptionArgsForCall) } func (fake *FakeServiceRepository) FindServicePlanByDescriptionArgsForCall(i int) resources.ServicePlanDescription { fake.findServicePlanByDescriptionMutex.RLock() defer fake.findServicePlanByDescriptionMutex.RUnlock() return fake.findServicePlanByDescriptionArgsForCall[i].planDescription } func (fake *FakeServiceRepository) FindServicePlanByDescriptionReturns(result1 string, result2 error) { fake.FindServicePlanByDescriptionStub = nil fake.findServicePlanByDescriptionReturns = struct { result1 string result2 error }{result1, result2} } func (fake *FakeServiceRepository) ListServicesFromBroker(brokerGuid string) (services []models.ServiceOffering, err error) { fake.listServicesFromBrokerMutex.Lock() fake.listServicesFromBrokerArgsForCall = append(fake.listServicesFromBrokerArgsForCall, struct { brokerGuid string }{brokerGuid}) fake.listServicesFromBrokerMutex.Unlock() if fake.ListServicesFromBrokerStub != nil { return fake.ListServicesFromBrokerStub(brokerGuid) } else { return fake.listServicesFromBrokerReturns.result1, fake.listServicesFromBrokerReturns.result2 } } func (fake *FakeServiceRepository) ListServicesFromBrokerCallCount() int { fake.listServicesFromBrokerMutex.RLock() defer fake.listServicesFromBrokerMutex.RUnlock() return len(fake.listServicesFromBrokerArgsForCall) } func (fake *FakeServiceRepository) ListServicesFromBrokerArgsForCall(i int) string { fake.listServicesFromBrokerMutex.RLock() defer fake.listServicesFromBrokerMutex.RUnlock() return fake.listServicesFromBrokerArgsForCall[i].brokerGuid } func (fake *FakeServiceRepository) ListServicesFromBrokerReturns(result1 []models.ServiceOffering, result2 error) { fake.ListServicesFromBrokerStub = nil fake.listServicesFromBrokerReturns = struct { result1 []models.ServiceOffering result2 error }{result1, result2} } func (fake *FakeServiceRepository) ListServicesFromManyBrokers(brokerGuids []string) (services []models.ServiceOffering, err error) { fake.listServicesFromManyBrokersMutex.Lock() fake.listServicesFromManyBrokersArgsForCall = append(fake.listServicesFromManyBrokersArgsForCall, struct { brokerGuids []string }{brokerGuids}) fake.listServicesFromManyBrokersMutex.Unlock() if fake.ListServicesFromManyBrokersStub != nil { return fake.ListServicesFromManyBrokersStub(brokerGuids) } else { return fake.listServicesFromManyBrokersReturns.result1, fake.listServicesFromManyBrokersReturns.result2 } } func (fake *FakeServiceRepository) ListServicesFromManyBrokersCallCount() int { fake.listServicesFromManyBrokersMutex.RLock() defer fake.listServicesFromManyBrokersMutex.RUnlock() return len(fake.listServicesFromManyBrokersArgsForCall) } func (fake *FakeServiceRepository) ListServicesFromManyBrokersArgsForCall(i int) []string { fake.listServicesFromManyBrokersMutex.RLock() defer fake.listServicesFromManyBrokersMutex.RUnlock() return fake.listServicesFromManyBrokersArgsForCall[i].brokerGuids } func (fake *FakeServiceRepository) ListServicesFromManyBrokersReturns(result1 []models.ServiceOffering, result2 error) { fake.ListServicesFromManyBrokersStub = nil fake.listServicesFromManyBrokersReturns = struct { result1 []models.ServiceOffering result2 error }{result1, result2} } func (fake *FakeServiceRepository) GetServiceInstanceCountForServicePlan(v1PlanGuid string) (count int, apiErr error) { fake.getServiceInstanceCountForServicePlanMutex.Lock() fake.getServiceInstanceCountForServicePlanArgsForCall = append(fake.getServiceInstanceCountForServicePlanArgsForCall, struct { v1PlanGuid string }{v1PlanGuid}) fake.getServiceInstanceCountForServicePlanMutex.Unlock() if fake.GetServiceInstanceCountForServicePlanStub != nil { return fake.GetServiceInstanceCountForServicePlanStub(v1PlanGuid) } else { return fake.getServiceInstanceCountForServicePlanReturns.result1, fake.getServiceInstanceCountForServicePlanReturns.result2 } } func (fake *FakeServiceRepository) GetServiceInstanceCountForServicePlanCallCount() int { fake.getServiceInstanceCountForServicePlanMutex.RLock() defer fake.getServiceInstanceCountForServicePlanMutex.RUnlock() return len(fake.getServiceInstanceCountForServicePlanArgsForCall) } func (fake *FakeServiceRepository) GetServiceInstanceCountForServicePlanArgsForCall(i int) string { fake.getServiceInstanceCountForServicePlanMutex.RLock() defer fake.getServiceInstanceCountForServicePlanMutex.RUnlock() return fake.getServiceInstanceCountForServicePlanArgsForCall[i].v1PlanGuid } func (fake *FakeServiceRepository) GetServiceInstanceCountForServicePlanReturns(result1 int, result2 error) { fake.GetServiceInstanceCountForServicePlanStub = nil fake.getServiceInstanceCountForServicePlanReturns = struct { result1 int result2 error }{result1, result2} } func (fake *FakeServiceRepository) MigrateServicePlanFromV1ToV2(v1PlanGuid string, v2PlanGuid string) (changedCount int, apiErr error) { fake.migrateServicePlanFromV1ToV2Mutex.Lock() fake.migrateServicePlanFromV1ToV2ArgsForCall = append(fake.migrateServicePlanFromV1ToV2ArgsForCall, struct { v1PlanGuid string v2PlanGuid string }{v1PlanGuid, v2PlanGuid}) fake.migrateServicePlanFromV1ToV2Mutex.Unlock() if fake.MigrateServicePlanFromV1ToV2Stub != nil { return fake.MigrateServicePlanFromV1ToV2Stub(v1PlanGuid, v2PlanGuid) } else { return fake.migrateServicePlanFromV1ToV2Returns.result1, fake.migrateServicePlanFromV1ToV2Returns.result2 } } func (fake *FakeServiceRepository) MigrateServicePlanFromV1ToV2CallCount() int { fake.migrateServicePlanFromV1ToV2Mutex.RLock() defer fake.migrateServicePlanFromV1ToV2Mutex.RUnlock() return len(fake.migrateServicePlanFromV1ToV2ArgsForCall) } func (fake *FakeServiceRepository) MigrateServicePlanFromV1ToV2ArgsForCall(i int) (string, string) { fake.migrateServicePlanFromV1ToV2Mutex.RLock() defer fake.migrateServicePlanFromV1ToV2Mutex.RUnlock() return fake.migrateServicePlanFromV1ToV2ArgsForCall[i].v1PlanGuid, fake.migrateServicePlanFromV1ToV2ArgsForCall[i].v2PlanGuid } func (fake *FakeServiceRepository) MigrateServicePlanFromV1ToV2Returns(result1 int, result2 error) { fake.MigrateServicePlanFromV1ToV2Stub = nil fake.migrateServicePlanFromV1ToV2Returns = struct { result1 int result2 error }{result1, result2} } var _ api.ServiceRepository = new(FakeServiceRepository)
pivotal-cf/cf-watch
vendor/github.com/cloudfoundry/cli/cf/api/fakes/fake_service_repository.go
GO
apache-2.0
30,330
# # Cookbook:: lvm # Library:: provider_lvm_thin_pool # # Copyright:: 2016-2017, Ontario Systems, 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. # require_relative 'provider_lvm_logical_volume' class Chef class Provider # The provider for lvm_thin_pool resource # class LvmThinPool < Chef::Provider::LvmLogicalVolume # Loads the current resource attributes # # @return [Chef::Resource::LvmThinPool] the lvm_logical_volume resource # def load_current_resource @current_resource ||= Chef::Resource::LvmThinPool.new(@new_resource.name) @current_resource end def action_create super process_thin_volumes(:create) end def action_resize super process_thin_volumes(:resize) end protected def create_command super.sub('--name', '--thinpool') end private def process_thin_volumes(action) updates = [] new_resource.thin_volumes.each do |tv| tv.group new_resource.group tv.pool new_resource.name tv.run_action action updates << tv.updated? end new_resource.updated_by_last_action(updates.any?) end end end end
ChiefAlexander/lvm
libraries/provider_lvm_thin_pool.rb
Ruby
apache-2.0
1,755
(function(angular){ 'use strict'; var app = angular.module('bernhardposselt.enhancetext', ['ngSanitize']); app.factory('TextEnhancer', ["SmileyEnhancer", "VideoEnhancer", "NewLineEnhancer", "ImageEnhancer", "YouTubeEnhancer", "LinkEnhancer", function (SmileyEnhancer, VideoEnhancer, NewLineEnhancer, ImageEnhancer, YouTubeEnhancer, LinkEnhancer) { return function (text, options) { text = escapeHtml(text); text = SmileyEnhancer(text, options.smilies); if (options.embedImages) { text = ImageEnhancer(text, options.embeddedImagesHeight, options.embeddedVideosWidth, options.embeddedLinkTarget); } if (options.embedVideos) { text = VideoEnhancer(text, options.embeddedImagesHeight, options.embeddedVideosWidth); } if (options.embedYoutube) { text = YouTubeEnhancer(text, options.embeddedYoutubeHeight, options.embeddedYoutubeWidth); } if (options.newLineToBr) { text = NewLineEnhancer(text); } if (options.embedLinks) { text = LinkEnhancer(text, options.embeddedLinkTarget); } return text; }; }]); app.factory('ImageEnhancer', function () { return function (text, height, width, target) { if(target === undefined) { target = '_blank'; } var imgRegex = /((?:https?):\/\/\S*\.(?:gif|jpg|jpeg|tiff|png|svg|webp))(\s&lt;\1&gt;){0,1}/gi; var imgDimensions = getDimensionsHtml(height, width); var img = '<a href="$1" target="' + target + '">' + '<img ' + imgDimensions + 'alt="image" src="$1"/>$1</a>'; return text.replace(imgRegex, img); }; }); app.factory('LinkEnhancer', function () { return function (text, target) { if(target === undefined) { target = '_blank'; } var regex = /((href|src)=["']|)(\b(https?|ftp|file):\/\/((?!&gt;)[-A-Z0-9+&@#\/%?=~_|!:,.;])*((?!&gt;)[-A-Z0-9+&@#\/%=~_|]))/ig; return text.replace(regex, function() { return arguments[1] ? arguments[0] : '<a target="' + target + '" href="'+ arguments[3] + '">' + arguments[3] + '</a>'; }); }; }); app.factory('NewLineEnhancer', function () { return function (text) { return text.replace(/\n/g, '<br/>').replace(/&#10;/g, '<br/>'); }; }); app.factory('SmileyEnhancer', function () { return function(text, smilies) { var smileyKeys = Object.keys(smilies); // split input into lines to avoid dealing with tons of // additional complexity/combinations arising from new lines var lines = text.split('\n'); var smileyReplacer = function (smiley, replacement, line) { // four possibilities: at the beginning, at the end, in the // middle or only the smiley var startSmiley = "^" + escapeRegExp(smiley) + " "; var endSmiley = " " + escapeRegExp(smiley) + "$"; var middleSmiley = " " + escapeRegExp(smiley) + " "; var onlySmiley = "^" + escapeRegExp(smiley) + "$"; return line. replace(new RegExp(startSmiley), replacement + " "). replace(new RegExp(endSmiley), " " + replacement). replace(new RegExp(middleSmiley), " " + replacement + " "). replace(new RegExp(onlySmiley), replacement); }; // loop over smilies and replace them in the text for (var i=0; i<smileyKeys.length; i++) { var smiley = smileyKeys[i]; var replacement = '<img alt="' + smiley + '" src="' + smilies[smiley] + '"/>'; // partially apply the replacer function to set the replacement // string var replacer = smileyReplacer.bind(null, smiley, replacement); lines = lines.map(replacer); } return lines.join('\n'); }; }); app.factory('VideoEnhancer', function () { return function (text, height, width) { var regex = /((?:https?):\/\/\S*\.(?:ogv|webm))/gi; var dimensions = getDimensionsHtml(height, width); var vid = '<video ' + dimensions + 'src="$1" controls preload="none"></video>'; return text.replace(regex, vid); }; }); app.factory('YouTubeEnhancer', function () { return function (text, height, width) { var regex = /https?:\/\/(?:[0-9A-Z-]+\.)?(?:youtu\.be\/|youtube\.com(?:\/embed\/|\/v\/|\/watch\?v=|\/ytscreeningroom\?v=|\/feeds\/api\/videos\/|\/user\S*[^\w\-\s]|\S*[^\w\-\s]))([\w\-]{11})[?=&+%\w-]*/gi; var dimensions = getDimensionsHtml(height, width); var html = '<iframe ' + dimensions + 'src="https://www.youtube.com/embed/$1" ' + 'frameborder="0" allowfullscreen></iframe>'; return text.replace(regex, html); }; }); app.provider('enhanceTextFilter', function () { var options = { cache: true, newLineToBr: true, embedLinks: true, embeddedLinkTarget: '_blank', embedImages: true, embeddedImagesHeight: undefined, embeddedImagesWidth: undefined, embedVideos: true, embeddedVideosHeight: undefined, embeddedVideosWidth: undefined, embedYoutube: true, embeddedYoutubeHeight: undefined, embeddedYoutubeWidth: undefined, smilies: {} }, textCache = {}; this.setOptions = function (customOptions) { angular.extend(options, customOptions); }; /* @ngInject */ this.$get = function ($sce, TextEnhancer) { return function (text) { var originalText = text; // hit cache first before replacing if (options.cache) { var cachedResult = textCache[text]; if (angular.isDefined(cachedResult)) { return cachedResult; } } text = TextEnhancer(text, options); // trust result to able to use it in ng-bind-html text = $sce.trustAsHtml(text); // cache result if (options.cache) { textCache[originalText] = text; } return text; }; }; this.$get.$inject = ["$sce", "TextEnhancer"]; }); function escapeHtml(str) { var div = document.createElement('div'); div.appendChild(document.createTextNode(str)); return div.innerHTML; } // taken from https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions function escapeRegExp (str) { return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"); } function getDimensionsHtml (height, width) { var dimensions = ''; if (angular.isDefined(height)) { dimensions += 'height="' + height + '" '; } if (angular.isDefined(width)) { dimensions += 'width="' + width + '" '; } return dimensions; } })(angular, undefined);
gzwfdy/zone
src/main/webapp/static/app/js/vendor/angular-enhance-text.min.js
JavaScript
apache-2.0
7,184
# Copyright The Cloud Custodian Authors. # SPDX-License-Identifier: Apache-2.0 from common_openstack import OpenStackTest class ServerTest(OpenStackTest): def test_server_query(self): factory = self.replay_flight_data() p = self.load_policy({ 'name': 'all-servers', 'resource': 'openstack.server'}, session_factory=factory) resources = p.run() self.assertEqual(len(resources), 2) def test_server_filter_name(self): factory = self.replay_flight_data() policy = { 'name': 'get-server-c7n-test-1', 'resource': 'openstack.server', 'filters': [ { "type": "value", "key": "name", "value": "c7n-test-1", }, ], } p = self.load_policy(policy, session_factory=factory) resources = p.run() self.assertEqual(len(resources), 1) self.assertEqual(resources[0].name, "c7n-test-1") def test_server_filter_flavor(self): factory = self.replay_flight_data() policy = { 'name': 'get-server-c7n-test-1', 'resource': 'openstack.server', 'filters': [ { "type": "flavor", "flavor_name": "m1.tiny", }, ], } p = self.load_policy(policy, session_factory=factory) resources = p.run() self.assertEqual(len(resources), 1) self.assertEqual(resources[0].name, "c7n-test-1") def test_server_filter_tags(self): factory = self.replay_flight_data() policy = { 'name': 'get-server-c7n-test-1', 'resource': 'openstack.server', 'filters': [ { "type": "tags", "tags": [ { "key": "a", "value": "a", }, { "key": "b", "value": "b", }, ], "op": "all", }, ], } p = self.load_policy(policy, session_factory=factory) resources = p.run() self.assertEqual(len(resources), 1) self.assertEqual(resources[0].name, "c7n-test-2")
thisisshi/cloud-custodian
tools/c7n_openstack/tests/test_server.py
Python
apache-2.0
2,461
# Copyright date_value0(date_value - 1)7 Google Inc. All rights reserved. # # Licensed under the Apache License, Version date_value.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require "spanner_helper" describe "Spanner Client", :params, :date, :spanner do let(:db) { spanner_client } let(:date_value) { Date.today } it "queries and returns a date parameter" do results = db.execute_query "SELECT @value AS value", params: { value: date_value } _(results).must_be_kind_of Google::Cloud::Spanner::Results _(results.fields[:value]).must_equal :DATE _(results.rows.first[:value]).must_equal date_value end it "queries and returns a NULL date parameter" do results = db.execute_query "SELECT @value AS value", params: { value: nil }, types: { value: :DATE } _(results).must_be_kind_of Google::Cloud::Spanner::Results _(results.fields[:value]).must_equal :DATE _(results.rows.first[:value]).must_be :nil? end it "queries and returns an array of date parameters" do results = db.execute_query "SELECT @value AS value", params: { value: [(date_value - 1), date_value, (date_value + 1)] } _(results).must_be_kind_of Google::Cloud::Spanner::Results _(results.fields[:value]).must_equal [:DATE] _(results.rows.first[:value]).must_equal [(date_value - 1), date_value, (date_value + 1)] end it "queries and returns an array of date parameters with a nil value" do results = db.execute_query "SELECT @value AS value", params: { value: [nil, (date_value - 1), date_value, (date_value + 1)] } _(results).must_be_kind_of Google::Cloud::Spanner::Results _(results.fields[:value]).must_equal [:DATE] _(results.rows.first[:value]).must_equal [nil, (date_value - 1), date_value, (date_value + 1)] end it "queries and returns an empty array of date parameters" do results = db.execute_query "SELECT @value AS value", params: { value: [] }, types: { value: [:DATE] } _(results).must_be_kind_of Google::Cloud::Spanner::Results _(results.fields[:value]).must_equal [:DATE] _(results.rows.first[:value]).must_equal [] end it "queries and returns a NULL array of date parameters" do results = db.execute_query "SELECT @value AS value", params: { value: nil }, types: { value: [:DATE] } _(results).must_be_kind_of Google::Cloud::Spanner::Results _(results.fields[:value]).must_equal [:DATE] _(results.rows.first[:value]).must_be :nil? end end
dazuma/google-cloud-ruby
google-cloud-spanner/acceptance/spanner/client/params/date_test.rb
Ruby
apache-2.0
2,907
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/eks/model/DeregisterClusterRequest.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::EKS::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; DeregisterClusterRequest::DeregisterClusterRequest() : m_nameHasBeenSet(false) { } Aws::String DeregisterClusterRequest::SerializePayload() const { return {}; }
awslabs/aws-sdk-cpp
aws-cpp-sdk-eks/source/model/DeregisterClusterRequest.cpp
C++
apache-2.0
512
/** * 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-2017 the original author or authors. */ package org.assertj.core.api.offsetdatetime; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.catchThrowable; import static org.mockito.Mockito.verify; import java.time.OffsetDateTime; import java.time.format.DateTimeParseException; import org.assertj.core.api.OffsetDateTimeAssert; import org.junit.Test; public class OffsetDateTimeAssert_isBetween_with_String_parameters_Test extends org.assertj.core.api.OffsetDateTimeAssertBaseTest { private OffsetDateTime before = now.minusSeconds(1); private OffsetDateTime after = now.plusSeconds(1); @Override protected OffsetDateTimeAssert invoke_api_method() { return assertions.isBetween(before.toString(), after.toString()); } @Override protected void verify_internal_effects() { verify(comparables).assertIsBetween(getInfo(assertions), getActual(assertions), before, after, true, true); } @Test public void should_throw_a_DateTimeParseException_if_start_String_parameter_cant_be_converted() { // GIVEN String abc = "abc"; // WHEN Throwable thrown = catchThrowable(() -> assertions.isBetween(abc, after.toString())); // THEN assertThat(thrown).isInstanceOf(DateTimeParseException.class); } @Test public void should_throw_a_DateTimeParseException_if_end_String_parameter_cant_be_converted() { // GIVEN String abc = "abc"; // WHEN Throwable thrown = catchThrowable(() -> assertions.isBetween(before.toString(), abc)); // THEN assertThat(thrown).isInstanceOf(DateTimeParseException.class); } }
ChrisCanCompute/assertj-core
src/test/java/org/assertj/core/api/offsetdatetime/OffsetDateTimeAssert_isBetween_with_String_parameters_Test.java
Java
apache-2.0
2,198
/* * Copyright 2014 NAVER 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 com.navercorp.pinpoint.profiler.instrument; import java.lang.reflect.Method; import com.navercorp.pinpoint.bootstrap.instrument.*; import com.navercorp.pinpoint.bootstrap.interceptor.scope.InterceptorScope; import com.navercorp.pinpoint.profiler.instrument.interceptor.*; import com.navercorp.pinpoint.profiler.metadata.ApiMetaDataService; import com.navercorp.pinpoint.profiler.objectfactory.ObjectBinderFactory; import javassist.CannotCompileException; import javassist.CtBehavior; import javassist.CtClass; import javassist.CtConstructor; import javassist.CtMethod; import javassist.Modifier; import javassist.NotFoundException; import javassist.bytecode.BadBytecode; import javassist.bytecode.Bytecode; import javassist.bytecode.CodeAttribute; import javassist.bytecode.CodeIterator; import javassist.bytecode.ConstPool; import javassist.bytecode.Descriptor; import javassist.compiler.CompileError; import javassist.compiler.Javac; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.navercorp.pinpoint.bootstrap.context.MethodDescriptor; import com.navercorp.pinpoint.bootstrap.interceptor.Interceptor; import com.navercorp.pinpoint.bootstrap.interceptor.scope.ExecutionPolicy; import com.navercorp.pinpoint.bootstrap.interceptor.registry.InterceptorRegistry; import com.navercorp.pinpoint.common.util.Assert; import com.navercorp.pinpoint.profiler.context.DefaultMethodDescriptor; import com.navercorp.pinpoint.profiler.interceptor.factory.AnnotatedInterceptorFactory; import com.navercorp.pinpoint.profiler.interceptor.registry.InterceptorRegistryBinder; import com.navercorp.pinpoint.profiler.util.JavaAssistUtils; public class JavassistMethod implements InstrumentMethod { private final Logger logger = LoggerFactory.getLogger(this.getClass()); private final boolean isDebug = logger.isDebugEnabled(); private final ObjectBinderFactory objectBinderFactory; private final InstrumentContext pluginContext; private final InterceptorRegistryBinder interceptorRegistryBinder; private final ApiMetaDataService apiMetaDataService; private final CtBehavior behavior; private final InstrumentClass declaringClass; private final MethodDescriptor descriptor; // TODO fix inject InterceptorDefinitionFactory private static final InterceptorDefinitionFactory interceptorDefinitionFactory = new InterceptorDefinitionFactory(); // TODO fix inject ScopeFactory private static final ScopeFactory scopeFactory = new ScopeFactory(); public JavassistMethod(ObjectBinderFactory objectBinderFactory, InstrumentContext pluginContext, InterceptorRegistryBinder interceptorRegistryBinder, ApiMetaDataService apiMetaDataService, InstrumentClass declaringClass, CtBehavior behavior) { if (objectBinderFactory == null) { throw new NullPointerException("objectBinderFactory must not be null"); } if (pluginContext == null) { throw new NullPointerException("pluginContext must not be null"); } this.objectBinderFactory = objectBinderFactory; this.pluginContext = pluginContext; this.interceptorRegistryBinder = interceptorRegistryBinder; this.apiMetaDataService = apiMetaDataService; this.behavior = behavior; this.declaringClass = declaringClass; String[] parameterVariableNames = JavaAssistUtils.getParameterVariableName(behavior); int lineNumber = JavaAssistUtils.getLineNumber(behavior); DefaultMethodDescriptor descriptor = new DefaultMethodDescriptor(behavior.getDeclaringClass().getName(), behavior.getName(), getParameterTypes(), parameterVariableNames); descriptor.setLineNumber(lineNumber); this.descriptor = descriptor; } @Override public String getName() { return behavior.getName(); } @Override public String[] getParameterTypes() { return JavaAssistUtils.parseParameterSignature(behavior.getSignature()); } @Override public String getReturnType() { if (behavior instanceof CtMethod) { try { return ((CtMethod) behavior).getReturnType().getName(); } catch (NotFoundException e) { return null; } } return null; } @Override public int getModifiers() { return behavior.getModifiers(); } @Override public boolean isConstructor() { return behavior instanceof CtConstructor; } @Override public MethodDescriptor getDescriptor() { return descriptor; } @Override public int addInterceptor(String interceptorClassName) throws InstrumentException { Assert.requireNonNull(interceptorClassName, "interceptorClassName must not be null"); return addInterceptor0(interceptorClassName, null, null, null); } @Override public int addInterceptor(String interceptorClassName, Object[] constructorArgs) throws InstrumentException { Assert.requireNonNull(interceptorClassName, "interceptorClassName must not be null"); Assert.requireNonNull(constructorArgs, "constructorArgs must not be null"); return addInterceptor0(interceptorClassName, constructorArgs, null, null); } @Override public int addScopedInterceptor(String interceptorClassName, String scopeName) throws InstrumentException { Assert.requireNonNull(interceptorClassName, "interceptorClassName must not be null"); Assert.requireNonNull(scopeName, "scopeName must not be null"); final InterceptorScope interceptorScope = this.pluginContext.getInterceptorScope(scopeName); return addInterceptor0(interceptorClassName, null, interceptorScope, null); } @Override public int addScopedInterceptor(String interceptorClassName, InterceptorScope scope) throws InstrumentException { Assert.requireNonNull(interceptorClassName, "interceptorClassName must not be null"); Assert.requireNonNull(scope, "scope must not be null"); return addInterceptor0(interceptorClassName, null, scope, null); } @Override public int addScopedInterceptor(String interceptorClassName, String scopeName, ExecutionPolicy executionPolicy) throws InstrumentException { Assert.requireNonNull(interceptorClassName, "interceptorClassName must not be null"); Assert.requireNonNull(scopeName, "scopeName must not be null"); Assert.requireNonNull(executionPolicy, "executionPolicy must not be null"); final InterceptorScope interceptorScope = this.pluginContext.getInterceptorScope(scopeName); return addInterceptor0(interceptorClassName, null, interceptorScope, executionPolicy); } @Override public int addScopedInterceptor(String interceptorClassName, InterceptorScope scope, ExecutionPolicy executionPolicy) throws InstrumentException { Assert.requireNonNull(interceptorClassName, "interceptorClassName must not be null"); Assert.requireNonNull(scope, "scope must not be null"); Assert.requireNonNull(executionPolicy, "executionPolicy must not be null"); return addInterceptor0(interceptorClassName, null, scope, executionPolicy); } @Override public int addScopedInterceptor(String interceptorClassName, Object[] constructorArgs, String scopeName) throws InstrumentException { Assert.requireNonNull(interceptorClassName, "interceptorClassName must not be null"); Assert.requireNonNull(constructorArgs, "constructorArgs must not be null"); Assert.requireNonNull(scopeName, "scopeName must not be null"); final InterceptorScope interceptorScope = this.pluginContext.getInterceptorScope(scopeName); return addInterceptor0(interceptorClassName, constructorArgs, interceptorScope, null); } @Override public int addScopedInterceptor(String interceptorClassName, Object[] constructorArgs, InterceptorScope scope) throws InstrumentException { Assert.requireNonNull(interceptorClassName, "interceptorClassName must not be null"); Assert.requireNonNull(constructorArgs, "constructorArgs must not be null"); Assert.requireNonNull(scope, "scope"); return addInterceptor0(interceptorClassName, constructorArgs, scope, null); } @Override public int addScopedInterceptor(String interceptorClassName, Object[] constructorArgs, String scopeName, ExecutionPolicy executionPolicy) throws InstrumentException { Assert.requireNonNull(interceptorClassName, "interceptorClassName must not be null"); Assert.requireNonNull(constructorArgs, "constructorArgs must not be null"); Assert.requireNonNull(scopeName, "scopeName must not be null"); Assert.requireNonNull(executionPolicy, "executionPolicy must not be null"); final InterceptorScope interceptorScope = this.pluginContext.getInterceptorScope(scopeName); return addInterceptor0(interceptorClassName, constructorArgs, interceptorScope, executionPolicy); } @Override public int addScopedInterceptor(String interceptorClassName, Object[] constructorArgs, InterceptorScope scope, ExecutionPolicy executionPolicy) throws InstrumentException { Assert.requireNonNull(interceptorClassName, "interceptorClassName must not be null"); Assert.requireNonNull(constructorArgs, "constructorArgs must not be null"); Assert.requireNonNull(scope, "scope must not be null"); Assert.requireNonNull(executionPolicy, "executionPolicy must not be null"); return addInterceptor0(interceptorClassName, constructorArgs, scope, executionPolicy); } @Override public void addInterceptor(int interceptorId) throws InstrumentException { Interceptor interceptor = InterceptorRegistry.getInterceptor(interceptorId); try { addInterceptor0(interceptor, interceptorId); } catch (Exception e) { throw new InstrumentException("Failed to add interceptor " + interceptor.getClass().getName() + " to " + behavior.getLongName(), e); } } // for internal api int addInterceptorInternal(String interceptorClassName, Object[] constructorArgs, InterceptorScope scope, ExecutionPolicy executionPolicy) throws InstrumentException { if (interceptorClassName == null) { throw new NullPointerException("interceptorClassName must not be null"); } return addInterceptor0(interceptorClassName, constructorArgs, scope, executionPolicy); } private int addInterceptor0(String interceptorClassName, Object[] constructorArgs, InterceptorScope scope, ExecutionPolicy executionPolicy) throws InstrumentException { try { final ClassLoader classLoader = declaringClass.getClassLoader(); final ScopeInfo scopeInfo = scopeFactory.newScopeInfo(classLoader, pluginContext, interceptorClassName, scope, executionPolicy); Interceptor interceptor = createInterceptor(classLoader, interceptorClassName, scopeInfo, constructorArgs); int interceptorId = interceptorRegistryBinder.getInterceptorRegistryAdaptor().addInterceptor(interceptor); addInterceptor0(interceptor, interceptorId); return interceptorId; } catch (CannotCompileException ccex) { throw new InstrumentException("Failed to add interceptor " + interceptorClassName + " to " + behavior.getLongName(), ccex); } catch (NotFoundException nex) { throw new InstrumentException("Failed to add interceptor " + interceptorClassName + " to " + behavior.getLongName(), nex); } } private Interceptor createInterceptor(ClassLoader classLoader, String interceptorClassName, ScopeInfo scopeInfo, Object[] constructorArgs) { AnnotatedInterceptorFactory factory = objectBinderFactory.newAnnotatedInterceptorFactory(pluginContext); Interceptor interceptor = factory.getInterceptor(classLoader, interceptorClassName, constructorArgs, scopeInfo, declaringClass, this); return interceptor; } private void addInterceptor0(Interceptor interceptor, int interceptorId) throws CannotCompileException, NotFoundException { if (interceptor == null) { throw new NullPointerException("interceptor must not be null"); } final InterceptorDefinition interceptorDefinition = interceptorDefinitionFactory.createInterceptorDefinition(interceptor.getClass()); final String localVariableName = initializeLocalVariable(interceptorId); int originalCodeOffset = insertBefore(-1, localVariableName); boolean localVarsInitialized = false; final int offset = addBeforeInterceptor(interceptorDefinition, interceptorId, originalCodeOffset); if (offset != -1) { localVarsInitialized = true; originalCodeOffset = offset; } addAfterInterceptor(interceptorDefinition, interceptorId, localVarsInitialized, originalCodeOffset); } private String initializeLocalVariable(int interceptorId) throws CannotCompileException, NotFoundException { final String interceptorInstanceVar = InvokeCodeGenerator.getInterceptorVar(interceptorId); addLocalVariable(interceptorInstanceVar, Interceptor.class); final StringBuilder initVars = new StringBuilder(); initVars.append(interceptorInstanceVar); initVars.append(" = null;"); return initVars.toString(); } private void addAfterInterceptor(InterceptorDefinition interceptorDefinition, int interceptorId, boolean localVarsInitialized, int originalCodeOffset) throws NotFoundException, CannotCompileException { final Class<?> interceptorClass = interceptorDefinition.getInterceptorClass(); final CaptureType captureType = interceptorDefinition.getCaptureType(); if (!isAfterInterceptor(captureType)) { return; } final Method interceptorMethod = interceptorDefinition.getAfterMethod(); if (interceptorMethod == null) { if (isDebug) { logger.debug("Skip adding after interceptor because the interceptor doesn't have after method: {}", interceptorClass.getName()); } return; } InvokeAfterCodeGenerator catchGenerator = new InvokeAfterCodeGenerator(interceptorId, interceptorDefinition, declaringClass, this, apiMetaDataService, localVarsInitialized, true); String catchCode = catchGenerator.generate(); if (isDebug) { logger.debug("addAfterInterceptor catch behavior:{} code:{}", behavior.getLongName(), catchCode); } CtClass throwable = behavior.getDeclaringClass().getClassPool().get("java.lang.Throwable"); insertCatch(originalCodeOffset, catchCode, throwable, "$e"); InvokeAfterCodeGenerator afterGenerator = new InvokeAfterCodeGenerator(interceptorId, interceptorDefinition, declaringClass, this, apiMetaDataService, localVarsInitialized, false); final String afterCode = afterGenerator.generate(); if (isDebug) { logger.debug("addAfterInterceptor after behavior:{} code:{}", behavior.getLongName(), afterCode); } behavior.insertAfter(afterCode); } private boolean isAfterInterceptor(CaptureType captureType) { return CaptureType.AFTER == captureType || CaptureType.AROUND == captureType; } private int addBeforeInterceptor(InterceptorDefinition interceptorDefinition, int interceptorId, int pos) throws CannotCompileException, NotFoundException { final Class<?> interceptorClass = interceptorDefinition.getInterceptorClass(); final CaptureType captureType = interceptorDefinition.getCaptureType(); if (!isBeforeInterceptor(captureType)) { return -1; } final Method interceptorMethod = interceptorDefinition.getBeforeMethod(); if (interceptorMethod == null) { if (isDebug) { logger.debug("Skip adding before interceptorDefinition because the interceptorDefinition doesn't have before method: {}", interceptorClass.getName()); } return -1; } final InvokeBeforeCodeGenerator generator = new InvokeBeforeCodeGenerator(interceptorId, interceptorDefinition, declaringClass, this, apiMetaDataService); final String beforeCode = generator.generate(); if (isDebug) { logger.debug("addBeforeInterceptor before behavior:{} code:{}", behavior.getLongName(), beforeCode); } return insertBefore(pos, beforeCode); } private boolean isBeforeInterceptor(CaptureType captureType) { return CaptureType.BEFORE == captureType || CaptureType.AROUND == captureType; } private void addLocalVariable(String name, Class<?> type) throws CannotCompileException, NotFoundException { final String interceptorClassName = type.getName(); final CtClass interceptorCtClass = behavior.getDeclaringClass().getClassPool().get(interceptorClassName); behavior.addLocalVariable(name, interceptorCtClass); } private int insertBefore(int pos, String src) throws CannotCompileException { if (isConstructor()) { return insertBeforeConstructor(pos, src); } else { return insertBeforeMethod(pos, src); } } private int insertBeforeMethod(int pos, String src) throws CannotCompileException { CtClass cc = behavior.getDeclaringClass(); CodeAttribute ca = behavior.getMethodInfo().getCodeAttribute(); if (ca == null) throw new CannotCompileException("no method body"); CodeIterator iterator = ca.iterator(); Javac jv = new Javac(cc); try { int nvars = jv.recordParams(behavior.getParameterTypes(), Modifier.isStatic(getModifiers())); jv.recordParamNames(ca, nvars); jv.recordLocalVariables(ca, 0); jv.recordType(getReturnType0()); jv.compileStmnt(src); Bytecode b = jv.getBytecode(); int stack = b.getMaxStack(); int locals = b.getMaxLocals(); if (stack > ca.getMaxStack()) ca.setMaxStack(stack); if (locals > ca.getMaxLocals()) ca.setMaxLocals(locals); if (pos != -1) { iterator.insertEx(pos, b.get()); } else { pos = iterator.insertEx(b.get()); } iterator.insert(b.getExceptionTable(), pos); behavior.getMethodInfo().rebuildStackMapIf6(cc.getClassPool(), cc.getClassFile2()); return pos + b.length(); } catch (NotFoundException e) { throw new CannotCompileException(e); } catch (CompileError e) { throw new CannotCompileException(e); } catch (BadBytecode e) { throw new CannotCompileException(e); } } private int insertBeforeConstructor(int pos, String src) throws CannotCompileException { CtClass cc = behavior.getDeclaringClass(); CodeAttribute ca = behavior.getMethodInfo().getCodeAttribute(); CodeIterator iterator = ca.iterator(); Bytecode b = new Bytecode(behavior.getMethodInfo().getConstPool(), ca.getMaxStack(), ca.getMaxLocals()); b.setStackDepth(ca.getMaxStack()); Javac jv = new Javac(b, cc); try { jv.recordParams(behavior.getParameterTypes(), false); jv.recordLocalVariables(ca, 0); jv.compileStmnt(src); ca.setMaxStack(b.getMaxStack()); ca.setMaxLocals(b.getMaxLocals()); iterator.skipConstructor(); if (pos != -1) { iterator.insertEx(pos, b.get()); } else { pos = iterator.insertEx(b.get()); } iterator.insert(b.getExceptionTable(), pos); behavior.getMethodInfo().rebuildStackMapIf6(cc.getClassPool(), cc.getClassFile2()); return pos + b.length(); } catch (NotFoundException e) { throw new CannotCompileException(e); } catch (CompileError e) { throw new CannotCompileException(e); } catch (BadBytecode e) { throw new CannotCompileException(e); } } private void insertCatch(int from, String src, CtClass exceptionType, String exceptionName) throws CannotCompileException { CtClass cc = behavior.getDeclaringClass(); ConstPool cp = behavior.getMethodInfo().getConstPool(); CodeAttribute ca = behavior.getMethodInfo().getCodeAttribute(); CodeIterator iterator = ca.iterator(); Bytecode b = new Bytecode(cp, ca.getMaxStack(), ca.getMaxLocals()); b.setStackDepth(1); Javac jv = new Javac(b, cc); try { jv.recordParams(behavior.getParameterTypes(), Modifier.isStatic(getModifiers())); jv.recordLocalVariables(ca, from); int var = jv.recordVariable(exceptionType, exceptionName); b.addAstore(var); jv.compileStmnt(src); int stack = b.getMaxStack(); int locals = b.getMaxLocals(); if (stack > ca.getMaxStack()) ca.setMaxStack(stack); if (locals > ca.getMaxLocals()) ca.setMaxLocals(locals); int len = iterator.getCodeLength(); int pos = iterator.append(b.get()); ca.getExceptionTable().add(from, len, len, cp.addClassInfo(exceptionType)); iterator.append(b.getExceptionTable(), pos); behavior.getMethodInfo().rebuildStackMapIf6(cc.getClassPool(), cc.getClassFile2()); } catch (NotFoundException e) { throw new CannotCompileException(e); } catch (CompileError e) { throw new CannotCompileException(e); } catch (BadBytecode e) { throw new CannotCompileException(e); } } private CtClass getReturnType0() throws NotFoundException { return Descriptor.getReturnType(behavior.getMethodInfo().getDescriptor(), behavior.getDeclaringClass().getClassPool()); } }
majinkai/pinpoint
profiler/src/main/java/com/navercorp/pinpoint/profiler/instrument/JavassistMethod.java
Java
apache-2.0
23,027
/* * 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.component.olingo4.api.impl; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.UUID; import java.util.function.Consumer; import org.apache.camel.component.olingo4.api.Olingo4App; import org.apache.camel.component.olingo4.api.Olingo4ResponseHandler; import org.apache.camel.component.olingo4.api.batch.Olingo4BatchChangeRequest; import org.apache.camel.component.olingo4.api.batch.Olingo4BatchQueryRequest; import org.apache.camel.component.olingo4.api.batch.Olingo4BatchRequest; import org.apache.camel.component.olingo4.api.batch.Olingo4BatchResponse; import org.apache.camel.component.olingo4.api.batch.Operation; import org.apache.camel.util.IOHelper; import org.apache.camel.util.ObjectHelper; import org.apache.commons.io.IOUtils; import org.apache.commons.io.LineIterator; import org.apache.commons.lang3.StringUtils; import org.apache.http.Consts; import org.apache.http.Header; import org.apache.http.HttpException; import org.apache.http.HttpHeaders; import org.apache.http.HttpResponse; import org.apache.http.HttpResponseFactory; import org.apache.http.HttpVersion; import org.apache.http.StatusLine; import org.apache.http.client.entity.DecompressingEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpDelete; import org.apache.http.client.methods.HttpEntityEnclosingRequestBase; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPatch; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPut; import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.concurrent.FutureCallback; import org.apache.http.config.MessageConstraints; import org.apache.http.entity.AbstractHttpEntity; import org.apache.http.entity.ByteArrayEntity; import org.apache.http.entity.StringEntity; import org.apache.http.impl.DefaultHttpResponseFactory; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.conn.DefaultHttpResponseParser; import org.apache.http.impl.io.HttpTransportMetricsImpl; import org.apache.http.impl.io.SessionInputBufferImpl; import org.apache.http.impl.nio.client.CloseableHttpAsyncClient; import org.apache.http.impl.nio.client.HttpAsyncClientBuilder; import org.apache.http.impl.nio.client.HttpAsyncClients; import org.apache.http.message.BasicLineParser; import org.apache.olingo.client.api.ODataBatchConstants; import org.apache.olingo.client.api.ODataClient; import org.apache.olingo.client.api.communication.request.ODataStreamer; import org.apache.olingo.client.api.communication.request.batch.ODataBatchLineIterator; import org.apache.olingo.client.api.domain.ClientEntity; import org.apache.olingo.client.api.domain.ClientPrimitiveValue; import org.apache.olingo.client.api.domain.ClientProperty; import org.apache.olingo.client.api.serialization.ODataReader; import org.apache.olingo.client.api.serialization.ODataWriter; import org.apache.olingo.client.api.uri.SegmentType; import org.apache.olingo.client.core.ODataClientFactory; import org.apache.olingo.client.core.communication.request.batch.ODataBatchController; import org.apache.olingo.client.core.communication.request.batch.ODataBatchLineIteratorImpl; import org.apache.olingo.client.core.communication.request.batch.ODataBatchUtilities; import org.apache.olingo.client.core.http.HttpMerge; import org.apache.olingo.commons.api.Constants; import org.apache.olingo.commons.api.edm.Edm; import org.apache.olingo.commons.api.edm.EdmPrimitiveTypeKind; import org.apache.olingo.commons.api.edm.EdmReturnType; import org.apache.olingo.commons.api.edm.constants.ODataServiceVersion; import org.apache.olingo.commons.api.ex.ODataException; import org.apache.olingo.commons.api.format.ContentType; import org.apache.olingo.commons.api.http.HttpHeader; import org.apache.olingo.commons.api.http.HttpStatusCode; import org.apache.olingo.server.api.OData; import org.apache.olingo.server.api.uri.UriInfo; import org.apache.olingo.server.api.uri.UriInfoKind; import org.apache.olingo.server.api.uri.UriParameter; import org.apache.olingo.server.api.uri.UriResource; import org.apache.olingo.server.api.uri.UriResourceEntitySet; import org.apache.olingo.server.api.uri.UriResourceFunction; import org.apache.olingo.server.api.uri.UriResourceKind; import org.apache.olingo.server.core.uri.parser.Parser; import static org.apache.camel.component.olingo4.api.impl.Olingo4Helper.getContentTypeHeader; /** * Application API used by Olingo4 Component. */ public final class Olingo4AppImpl implements Olingo4App { private static final String SEPARATOR = "/"; private static final String BOUNDARY_PREFIX = "batch_"; private static final String BOUNDARY_PARAMETER = "; boundary="; private static final String BOUNDARY_DOUBLE_DASH = "--"; private static final String MULTIPART_MIME_TYPE = "multipart/"; private static final String CONTENT_ID_HEADER = "Content-ID"; private static final String CLIENT_ENTITY_FAKE_MARKER = "('X')"; private static final ContentType DEFAULT_CONTENT_TYPE = ContentType.create(ContentType.APPLICATION_JSON, ContentType.PARAMETER_CHARSET, Constants.UTF8); private static final ContentType METADATA_CONTENT_TYPE = ContentType.create(ContentType.APPLICATION_XML, ContentType.PARAMETER_CHARSET, Constants.UTF8); private static final ContentType TEXT_PLAIN_WITH_CS_UTF_8 = ContentType.create(ContentType.TEXT_PLAIN, ContentType.PARAMETER_CHARSET, Constants.UTF8); private static final ContentType SERVICE_DOCUMENT_CONTENT_TYPE = ContentType.APPLICATION_JSON; private static final ContentType BATCH_CONTENT_TYPE = ContentType.MULTIPART_MIXED; /** * Reference to CloseableHttpAsyncClient (default) or CloseableHttpClient */ private final Closeable client; /** * Reference to ODataClient reader and writer */ private final ODataClient odataClient = ODataClientFactory.getClient(); private final ODataReader odataReader = odataClient.getReader(); private final ODataWriter odataWriter = odataClient.getWriter(); private String serviceUri; private ContentType contentType; private Map<String, String> httpHeaders; /** * Create Olingo4 Application with default HTTP configuration. */ public Olingo4AppImpl(String serviceUri) { // By default create HTTP asynchronous client this(serviceUri, (HttpClientBuilder)null); } /** * Create Olingo4 Application with custom HTTP Asynchronous client builder. * * @param serviceUri Service Application base URI. * @param builder custom HTTP client builder. */ public Olingo4AppImpl(String serviceUri, HttpAsyncClientBuilder builder) { setServiceUri(serviceUri); CloseableHttpAsyncClient asyncClient; if (builder == null) { asyncClient = HttpAsyncClients.createDefault(); } else { asyncClient = builder.build(); } asyncClient.start(); this.client = asyncClient; this.contentType = DEFAULT_CONTENT_TYPE; } /** * Create Olingo4 Application with custom HTTP Synchronous client builder. * * @param serviceUri Service Application base URI. * @param builder Custom HTTP Synchronous client builder. */ public Olingo4AppImpl(String serviceUri, HttpClientBuilder builder) { setServiceUri(serviceUri); if (builder == null) { this.client = HttpClients.createDefault(); } else { this.client = builder.build(); } this.contentType = DEFAULT_CONTENT_TYPE; } @Override public void setServiceUri(String serviceUri) { if (serviceUri == null || serviceUri.isEmpty()) { throw new IllegalArgumentException("serviceUri is not set"); } this.serviceUri = serviceUri.endsWith(SEPARATOR) ? serviceUri.substring(0, serviceUri.length() - 1) : serviceUri; } @Override public String getServiceUri() { return serviceUri; } @Override public Map<String, String> getHttpHeaders() { return httpHeaders; } @Override public void setHttpHeaders(Map<String, String> httpHeaders) { this.httpHeaders = httpHeaders; } @Override public String getContentType() { return contentType.toContentTypeString(); } @Override public void setContentType(String contentType) { this.contentType = ContentType.parse(contentType); } @Override public void close() { IOHelper.close(client); } @Override public <T> void read(final Edm edm, final String resourcePath, final Map<String, String> queryParams, final Map<String, String> endpointHttpHeaders, final Olingo4ResponseHandler<T> responseHandler) { final String queryOptions = concatQueryParams(queryParams); final UriInfo uriInfo = parseUri(edm, resourcePath, queryOptions, serviceUri); execute(new HttpGet(createUri(resourcePath, queryOptions)), getResourceContentType(uriInfo), endpointHttpHeaders, new AbstractFutureCallback<T>(responseHandler) { @Override public void onCompleted(HttpResponse result) throws IOException { readContent(uriInfo, result.getEntity() != null ? result.getEntity().getContent() : null, headersToMap(result.getAllHeaders()), responseHandler); } }); } @Override public void uread(final Edm edm, final String resourcePath, final Map<String, String> queryParams, final Map<String, String> endpointHttpHeaders, final Olingo4ResponseHandler<InputStream> responseHandler) { final String queryOptions = concatQueryParams(queryParams); final UriInfo uriInfo = parseUri(edm, resourcePath, queryOptions, serviceUri); execute(new HttpGet(createUri(resourcePath, queryOptions)), getResourceContentType(uriInfo), endpointHttpHeaders, new AbstractFutureCallback<InputStream>(responseHandler) { @Override public void onCompleted(HttpResponse result) throws IOException { InputStream responseStream = result.getEntity() != null ? result.getEntity().getContent() : null; if (responseStream != null && result.getEntity() instanceof DecompressingEntity) { // In case of GZIP compression it's necessary to create // InputStream from the source byte array responseHandler.onResponse(new ByteArrayInputStream(IOUtils.toByteArray(responseStream)), headersToMap(result.getAllHeaders())); } else { responseHandler.onResponse(responseStream, headersToMap(result.getAllHeaders())); } } }); } @Override public <T> void create(final Edm edm, final String resourcePath, final Map<String, String> endpointHttpHeaders, final Object data, final Olingo4ResponseHandler<T> responseHandler) { final UriInfo uriInfo = parseUri(edm, resourcePath, null, serviceUri); writeContent(edm, new HttpPost(createUri(resourcePath, null)), uriInfo, data, endpointHttpHeaders, responseHandler); } @Override public <T> void update(final Edm edm, final String resourcePath, final Map<String, String> endpointHttpHeaders, final Object data, final Olingo4ResponseHandler<T> responseHandler) { final UriInfo uriInfo = parseUri(edm, resourcePath, null, serviceUri); augmentWithETag(edm, resourcePath, endpointHttpHeaders, new HttpPut(createUri(resourcePath, null)), request -> writeContent(edm, (HttpPut)request, uriInfo, data, endpointHttpHeaders, responseHandler), responseHandler); } @Override public void delete(final String resourcePath, final Map<String, String> endpointHttpHeaders, final Olingo4ResponseHandler<HttpStatusCode> responseHandler) { HttpDelete deleteRequest = new HttpDelete(createUri(resourcePath)); Consumer<HttpRequestBase> deleteFunction = request -> { execute(request, contentType, endpointHttpHeaders, new AbstractFutureCallback<HttpStatusCode>(responseHandler) { @Override public void onCompleted(HttpResponse result) { final StatusLine statusLine = result.getStatusLine(); responseHandler.onResponse(HttpStatusCode.fromStatusCode(statusLine.getStatusCode()), headersToMap(result.getAllHeaders())); } }); }; augmentWithETag(null, resourcePath, endpointHttpHeaders, deleteRequest, deleteFunction, responseHandler); } @Override public <T> void patch(final Edm edm, final String resourcePath, final Map<String, String> endpointHttpHeaders, final Object data, final Olingo4ResponseHandler<T> responseHandler) { final UriInfo uriInfo = parseUri(edm, resourcePath, null, serviceUri); augmentWithETag(edm, resourcePath, endpointHttpHeaders, new HttpPatch(createUri(resourcePath, null)), request -> writeContent(edm, (HttpPatch)request, uriInfo, data, endpointHttpHeaders, responseHandler), responseHandler); } @Override public <T> void merge(final Edm edm, final String resourcePath, final Map<String, String> endpointHttpHeaders, final Object data, final Olingo4ResponseHandler<T> responseHandler) { final UriInfo uriInfo = parseUri(edm, resourcePath, null, serviceUri); augmentWithETag(edm, resourcePath, endpointHttpHeaders, new HttpMerge(createUri(resourcePath, null)), request -> writeContent(edm, (HttpMerge)request, uriInfo, data, endpointHttpHeaders, responseHandler), responseHandler); } @Override public void batch(final Edm edm, final Map<String, String> endpointHttpHeaders, final Object data, final Olingo4ResponseHandler<List<Olingo4BatchResponse>> responseHandler) { final UriInfo uriInfo = parseUri(edm, SegmentType.BATCH.getValue(), null, serviceUri); writeContent(edm, new HttpPost(createUri(SegmentType.BATCH.getValue(), null)), uriInfo, data, endpointHttpHeaders, responseHandler); } @Override public <T> void action(final Edm edm, final String resourcePath, final Map<String, String> endpointHttpHeaders, final Object data, final Olingo4ResponseHandler<T> responseHandler) { final UriInfo uriInfo = parseUri(edm, resourcePath, null, serviceUri); writeContent(edm, new HttpPost(createUri(resourcePath, null)), uriInfo, data, endpointHttpHeaders, responseHandler); } private ContentType getResourceContentType(UriInfo uriInfo) { ContentType resourceContentType; switch (uriInfo.getKind()) { case service: // service document resourceContentType = SERVICE_DOCUMENT_CONTENT_TYPE; break; case metadata: // metadata resourceContentType = METADATA_CONTENT_TYPE; break; case resource: List<UriResource> listResource = uriInfo.getUriResourceParts(); UriResourceKind lastResourceKind = listResource.get(listResource.size() - 1).getKind(); // is it a $value or $count URI?? if (lastResourceKind == UriResourceKind.count || lastResourceKind == UriResourceKind.value) { resourceContentType = TEXT_PLAIN_WITH_CS_UTF_8; } else { resourceContentType = contentType; } break; default: resourceContentType = contentType; } return resourceContentType; } /** * On occasion, some resources are protected with Optimistic Concurrency via * the use of eTags. This will first conduct a read on the given entity * resource, find its eTag then perform the given delegate request function, * augmenting the request with the eTag, if appropriate. Since read * operations may be asynchronous, it is necessary to chain together the * methods via the use of a {@link Consumer} function. Only when the * response from the read returns will this delegate function be executed. * * @param edm the Edm object to be interrogated * @param resourcePath the resource path of the entity to be operated on * @param endpointHttpHeaders the headers provided from the endpoint which * may be required for the read operation * @param httpRequest the request to be updated, if appropriate, with the * eTag and provided to the delegate request function * @param delegateRequestFn the function to be invoked in response to the * read operation * @param delegateResponseHandler the response handler to respond if any * errors occur during the read operation */ private <T> void augmentWithETag(final Edm edm, final String resourcePath, final Map<String, String> endpointHttpHeaders, final HttpRequestBase httpRequest, final Consumer<HttpRequestBase> delegateRequestFn, final Olingo4ResponseHandler<T> delegateResponseHandler) { if (edm == null) { // Can be the case if calling a delete then need to do a metadata // call first final Olingo4ResponseHandler<Edm> edmResponseHandler = new Olingo4ResponseHandler<Edm>() { @Override public void onResponse(Edm response, Map<String, String> responseHeaders) { // // Call this method again with an intact edm object // augmentWithETag(response, resourcePath, endpointHttpHeaders, httpRequest, delegateRequestFn, delegateResponseHandler); } @Override public void onException(Exception ex) { delegateResponseHandler.onException(ex); } @Override public void onCanceled() { delegateResponseHandler.onCanceled(); } }; // // Reads the metadata to establish an Edm object // then the response handler invokes this method again with the new // edm object // read(null, Constants.METADATA, null, null, edmResponseHandler); } else { // // The handler that responds to the read operation and supplies an // ETag if necessary // and invokes the delegate request function // Olingo4ResponseHandler<T> eTagReadHandler = new Olingo4ResponseHandler<T>() { @Override public void onResponse(T response, Map<String, String> responseHeaders) { if (response instanceof ClientEntity) { ClientEntity e = (ClientEntity)response; Optional.ofNullable(e.getETag()).ifPresent(v -> httpRequest.addHeader("If-Match", v)); } // Invoke the delegate request function providing the // modified request delegateRequestFn.accept(httpRequest); } @Override public void onException(Exception ex) { delegateResponseHandler.onException(ex); } @Override public void onCanceled() { delegateResponseHandler.onCanceled(); } }; read(edm, resourcePath, null, endpointHttpHeaders, eTagReadHandler); } } private <T> void readContent(UriInfo uriInfo, InputStream content, Map<String, String> endpointHttpHeaders, Olingo4ResponseHandler<T> responseHandler) { try { responseHandler.onResponse(this.<T> readContent(uriInfo, content), endpointHttpHeaders); } catch (Exception e) { responseHandler.onException(e); } catch (Error e) { responseHandler.onException(new ODataException("Runtime Error Occurred", e)); } } @SuppressWarnings("unchecked") private <T> T readContent(UriInfo uriInfo, InputStream content) throws ODataException { T response = null; switch (uriInfo.getKind()) { case service: // service document response = (T)odataReader.readServiceDocument(content, SERVICE_DOCUMENT_CONTENT_TYPE); break; case metadata: // $metadata response = (T)odataReader.readMetadata(content); break; case resource: // any resource entity List<UriResource> listResource = uriInfo.getUriResourceParts(); UriResourceKind lastResourceKind = listResource.get(listResource.size() - 1).getKind(); switch (lastResourceKind) { case entitySet: UriResourceEntitySet uriResourceEntitySet = (UriResourceEntitySet)listResource.get(listResource.size() - 1); List<UriParameter> keyPredicates = uriResourceEntitySet.getKeyPredicates(); // Check result type: single Entity or EntitySet based // on key predicate detection if (keyPredicates.size() == 1) { response = (T)odataReader.readEntity(content, getResourceContentType(uriInfo)); } else { response = (T)odataReader.readEntitySet(content, getResourceContentType(uriInfo)); } break; case count: String stringCount = null; try { stringCount = IOUtils.toString(content, Consts.UTF_8); response = (T)Long.valueOf(stringCount); } catch (IOException e) { throw new ODataException("Error during $count value deserialization", e); } catch (NumberFormatException e) { throw new ODataException("Error during $count value conversion: " + stringCount, e); } break; case value: try { ClientPrimitiveValue value = odataClient.getObjectFactory().newPrimitiveValueBuilder().setType(EdmPrimitiveTypeKind.String) .setValue(IOUtils.toString(content, Consts.UTF_8)).build(); response = (T)value; } catch (IOException e) { throw new ODataException("Error during $value deserialization", e); } break; case primitiveProperty: case complexProperty: ClientProperty property = odataReader.readProperty(content, getResourceContentType(uriInfo)); if (property.hasPrimitiveValue()) { response = (T)property.getPrimitiveValue(); } else if (property.hasComplexValue()) { response = (T)property.getComplexValue(); } else if (property.hasCollectionValue()) { response = (T)property.getCollectionValue(); } else { throw new ODataException("Unsupported property: " + property.getName()); } break; case function: UriResourceFunction uriResourceFunction = (UriResourceFunction)listResource.get(listResource.size() - 1); EdmReturnType functionReturnType = uriResourceFunction.getFunction().getReturnType(); switch (functionReturnType.getType().getKind()) { case ENTITY: if (functionReturnType.isCollection()) { response = (T)odataReader.readEntitySet(content, getResourceContentType(uriInfo)); } else { response = (T)odataReader.readEntity(content, getResourceContentType(uriInfo)); } break; case PRIMITIVE: case COMPLEX: ClientProperty functionProperty = odataReader.readProperty(content, getResourceContentType(uriInfo)); if (functionProperty.hasPrimitiveValue()) { response = (T)functionProperty.getPrimitiveValue(); } else if (functionProperty.hasComplexValue()) { response = (T)functionProperty.getComplexValue(); } else if (functionProperty.hasCollectionValue()) { response = (T)functionProperty.getCollectionValue(); } else { throw new ODataException("Unsupported property: " + functionProperty.getName()); } break; default: throw new ODataException("Unsupported function return type " + uriInfo.getKind().name()); } break; default: throw new ODataException("Unsupported resource type: " + lastResourceKind.name()); } break; default: throw new ODataException("Unsupported resource type " + uriInfo.getKind().name()); } return response; } private <T> void writeContent(final Edm edm, HttpEntityEnclosingRequestBase httpEntityRequest, final UriInfo uriInfo, final Object content, final Map<String, String> endpointHttpHeaders, final Olingo4ResponseHandler<T> responseHandler) { try { httpEntityRequest.setEntity(writeContent(edm, uriInfo, content)); final Header requestContentTypeHeader = httpEntityRequest.getEntity().getContentType(); final ContentType requestContentType = requestContentTypeHeader != null ? ContentType.parse(requestContentTypeHeader.getValue()) : contentType; execute(httpEntityRequest, requestContentType, endpointHttpHeaders, new AbstractFutureCallback<T>(responseHandler) { @SuppressWarnings("unchecked") @Override public void onCompleted(HttpResponse result) throws IOException, ODataException { // if a entity is created (via POST request) the response // body contains the new created entity HttpStatusCode statusCode = HttpStatusCode.fromStatusCode(result.getStatusLine().getStatusCode()); // look for no content, or no response body!!! final boolean noEntity = result.getEntity() == null || result.getEntity().getContentLength() == 0; if (statusCode == HttpStatusCode.NO_CONTENT || noEntity) { responseHandler.onResponse((T)HttpStatusCode.fromStatusCode(result.getStatusLine().getStatusCode()), headersToMap(result.getAllHeaders())); } else { if (uriInfo.getKind() == UriInfoKind.resource) { List<UriResource> listResource = uriInfo.getUriResourceParts(); UriResourceKind lastResourceKind = listResource.get(listResource.size() - 1).getKind(); switch (lastResourceKind) { case action: case entitySet: ClientEntity entity = odataReader.readEntity(result.getEntity().getContent(), ContentType.parse(result.getEntity().getContentType().getValue())); responseHandler.onResponse((T)entity, headersToMap(result.getAllHeaders())); break; default: break; } } else if (uriInfo.getKind() == UriInfoKind.batch) { List<Olingo4BatchResponse> batchResponse = parseBatchResponse(edm, result, (List<Olingo4BatchRequest>)content); responseHandler.onResponse((T)batchResponse, headersToMap(result.getAllHeaders())); } else { throw new ODataException("Unsupported resource type: " + uriInfo.getKind().name()); } } } }); } catch (Exception e) { responseHandler.onException(e); } catch (Error e) { responseHandler.onException(new ODataException("Runtime Error Occurred", e)); } } private AbstractHttpEntity writeContent(final Edm edm, final UriInfo uriInfo, final Object content) throws ODataException { AbstractHttpEntity httpEntity; if (uriInfo.getKind() == UriInfoKind.resource) { // any resource entity List<UriResource> listResource = uriInfo.getUriResourceParts(); UriResourceKind lastResourceKind = listResource.get(listResource.size() - 1).getKind(); switch (lastResourceKind) { case action: if (content == null) { // actions may have no input httpEntity = new ByteArrayEntity(new byte[0]); } else { httpEntity = writeContent(uriInfo, content); } break; case entitySet: httpEntity = writeContent(uriInfo, content); break; default: throw new ODataException("Unsupported resource type: " + lastResourceKind); } } else if (uriInfo.getKind() == UriInfoKind.batch) { final String boundary = BOUNDARY_PREFIX + UUID.randomUUID(); final String contentHeader = BATCH_CONTENT_TYPE + BOUNDARY_PARAMETER + boundary; final List<Olingo4BatchRequest> batchParts = (List<Olingo4BatchRequest>)content; final InputStream requestStream = serializeBatchRequest(edm, batchParts, BOUNDARY_DOUBLE_DASH + boundary); httpEntity = writeContent(requestStream); httpEntity.setContentType(contentHeader); } else { throw new ODataException("Unsupported resource type: " + uriInfo.getKind().name()); } return httpEntity; } private AbstractHttpEntity writeContent(UriInfo uriInfo, Object content) throws ODataException { AbstractHttpEntity httpEntity; if (content instanceof ClientEntity) { final InputStream requestStream = odataWriter.writeEntity((ClientEntity)content, getResourceContentType(uriInfo)); httpEntity = writeContent(requestStream); } else if (content instanceof String) { httpEntity = new StringEntity((String)content, org.apache.http.entity.ContentType.APPLICATION_JSON); } else { throw new ODataException("Unsupported content type: " + content); } httpEntity.setChunked(false); return httpEntity; } private AbstractHttpEntity writeContent(InputStream inputStream) throws ODataException { AbstractHttpEntity httpEntity; try { httpEntity = new ByteArrayEntity(IOUtils.toByteArray(inputStream)); } catch (IOException e) { throw new ODataException("Error during converting input stream to byte array", e); } httpEntity.setChunked(false); return httpEntity; } private InputStream serializeBatchRequest(final Edm edm, final List<Olingo4BatchRequest> batchParts, String boundary) throws ODataException { final ByteArrayOutputStream batchRequestHeaderOutputStream = new ByteArrayOutputStream(); try { batchRequestHeaderOutputStream.write(boundary.getBytes(Constants.UTF8)); batchRequestHeaderOutputStream.write(ODataStreamer.CRLF); for (Olingo4BatchRequest batchPart : batchParts) { writeHttpHeader(batchRequestHeaderOutputStream, HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_HTTP.toContentTypeString()); writeHttpHeader(batchRequestHeaderOutputStream, ODataBatchConstants.ITEM_TRANSFER_ENCODING_LINE, null); if (batchPart instanceof Olingo4BatchQueryRequest) { final Olingo4BatchQueryRequest batchQueryPart = (Olingo4BatchQueryRequest)batchPart; final String batchQueryUri = createUri(StringUtils.isBlank(batchQueryPart.getResourceUri()) ? serviceUri : batchQueryPart.getResourceUri(), batchQueryPart.getResourcePath(), concatQueryParams(batchQueryPart.getQueryParams())); final UriInfo uriInfo = parseUri(edm, batchQueryPart.getResourcePath(), concatQueryParams(batchQueryPart.getQueryParams()), serviceUri); batchRequestHeaderOutputStream.write(ODataStreamer.CRLF); batchRequestHeaderOutputStream.write((HttpGet.METHOD_NAME + " " + batchQueryUri + " " + HttpVersion.HTTP_1_1).getBytes(Constants.UTF8)); batchRequestHeaderOutputStream.write(ODataStreamer.CRLF); final ContentType acceptType = getResourceContentType(uriInfo); final String acceptCharset = acceptType.getParameter(ContentType.PARAMETER_CHARSET); writeHttpHeader(batchRequestHeaderOutputStream, HttpHeaders.ACCEPT, contentType.getType().toLowerCase() + "/" + contentType.getSubtype().toLowerCase()); if (null != acceptCharset) { writeHttpHeader(batchRequestHeaderOutputStream, HttpHeaders.ACCEPT_CHARSET, acceptCharset.toLowerCase()); } batchRequestHeaderOutputStream.write(ODataStreamer.CRLF); batchRequestHeaderOutputStream.write(boundary.getBytes(Constants.UTF8)); batchRequestHeaderOutputStream.write(ODataStreamer.CRLF); } else if (batchPart instanceof Olingo4BatchChangeRequest) { final Olingo4BatchChangeRequest batchChangePart = (Olingo4BatchChangeRequest)batchPart; final String batchChangeUri = createUri(StringUtils.isBlank(batchChangePart.getResourceUri()) ? serviceUri : batchChangePart.getResourceUri(), batchChangePart.getResourcePath(), null); final UriInfo uriInfo = parseUri(edm, batchChangePart.getResourcePath(), null, serviceUri); if (batchChangePart.getOperation() != Operation.DELETE) { writeHttpHeader(batchRequestHeaderOutputStream, CONTENT_ID_HEADER, batchChangePart.getContentId()); } batchRequestHeaderOutputStream.write(ODataStreamer.CRLF); batchRequestHeaderOutputStream .write((batchChangePart.getOperation().getHttpMethod() + " " + batchChangeUri + " " + HttpVersion.HTTP_1_1).getBytes(Constants.UTF8)); batchRequestHeaderOutputStream.write(ODataStreamer.CRLF); writeHttpHeader(batchRequestHeaderOutputStream, HttpHeader.ODATA_VERSION, ODataServiceVersion.V40.toString()); final ContentType acceptType = getResourceContentType(uriInfo); final String acceptCharset = acceptType.getParameter(ContentType.PARAMETER_CHARSET); writeHttpHeader(batchRequestHeaderOutputStream, HttpHeaders.ACCEPT, contentType.getType().toLowerCase() + "/" + contentType.getSubtype().toLowerCase()); if (null != acceptCharset) { writeHttpHeader(batchRequestHeaderOutputStream, HttpHeaders.ACCEPT_CHARSET, acceptCharset.toLowerCase()); } writeHttpHeader(batchRequestHeaderOutputStream, HttpHeaders.CONTENT_TYPE, acceptType.toContentTypeString()); if (batchChangePart.getOperation() != Operation.DELETE) { batchRequestHeaderOutputStream.write(ODataStreamer.CRLF); AbstractHttpEntity httpEnity = writeContent(edm, uriInfo, batchChangePart.getBody()); batchRequestHeaderOutputStream.write(IOUtils.toByteArray(httpEnity.getContent())); batchRequestHeaderOutputStream.write(ODataStreamer.CRLF); batchRequestHeaderOutputStream.write(ODataStreamer.CRLF); } else { batchRequestHeaderOutputStream.write(ODataStreamer.CRLF); } batchRequestHeaderOutputStream.write(boundary.getBytes(Constants.UTF8)); batchRequestHeaderOutputStream.write(ODataStreamer.CRLF); } else { throw new ODataException("Unsupported batch part request object type: " + batchPart); } } } catch (Exception e) { throw new ODataException("Error during batch request serialization", e); } return new ByteArrayInputStream(batchRequestHeaderOutputStream.toByteArray()); } private void writeHttpHeader(ByteArrayOutputStream headerOutputStream, String headerName, String headerValue) throws IOException { headerOutputStream.write(createHttpHeader(headerName, headerValue).getBytes(Constants.UTF8)); headerOutputStream.write(ODataStreamer.CRLF); } private String createHttpHeader(String headerName, String headerValue) { return headerName + (StringUtils.isBlank(headerValue) ? "" : (": " + headerValue)); } private List<Olingo4BatchResponse> parseBatchResponse(final Edm edm, HttpResponse response, List<Olingo4BatchRequest> batchRequest) throws ODataException { List<Olingo4BatchResponse> batchResponse = new <Olingo4BatchResponse> ArrayList(); try { final Header[] contentHeaders = response.getHeaders(HttpHeader.CONTENT_TYPE); final ODataBatchLineIterator batchLineIterator = new ODataBatchLineIteratorImpl(IOUtils.lineIterator(response.getEntity().getContent(), Constants.UTF8)); final String batchBoundary = ODataBatchUtilities.getBoundaryFromHeader(getHeadersCollection(contentHeaders)); final ODataBatchController batchController = new ODataBatchController(batchLineIterator, batchBoundary); batchController.getBatchLineIterator().next(); int batchRequestIndex = 0; while (batchController.getBatchLineIterator().hasNext()) { OutputStream os = new ByteArrayOutputStream(); ODataBatchUtilities.readBatchPart(batchController, os, false); Object content = null; final Olingo4BatchRequest batchPartRequest = batchRequest.get(batchRequestIndex); final HttpResponse batchPartHttpResponse = constructBatchPartHttpResponse(new ByteArrayInputStream(((ByteArrayOutputStream)os).toByteArray())); final StatusLine batchPartStatusLine = batchPartHttpResponse.getStatusLine(); final int batchPartLineStatusCode = batchPartStatusLine.getStatusCode(); Map<String, String> batchPartHeaders = getHeadersValueMap(batchPartHttpResponse.getAllHeaders()); if (batchPartRequest instanceof Olingo4BatchQueryRequest) { Olingo4BatchQueryRequest batchPartQueryRequest = (Olingo4BatchQueryRequest)batchPartRequest; final UriInfo uriInfo = parseUri(edm, batchPartQueryRequest.getResourcePath(), null, serviceUri); if (HttpStatusCode.BAD_REQUEST.getStatusCode() <= batchPartLineStatusCode && batchPartLineStatusCode <= AbstractFutureCallback.NETWORK_CONNECT_TIMEOUT_ERROR) { final ContentType responseContentType = getContentTypeHeader(batchPartHttpResponse); content = odataReader.readError(batchPartHttpResponse.getEntity().getContent(), responseContentType); } else if (batchPartLineStatusCode == HttpStatusCode.NO_CONTENT.getStatusCode()) { // nothing to do if NO_CONTENT returning } else { content = readContent(uriInfo, batchPartHttpResponse.getEntity().getContent()); } Olingo4BatchResponse batchPartResponse = new Olingo4BatchResponse(batchPartStatusLine.getStatusCode(), batchPartStatusLine.getReasonPhrase(), null, batchPartHeaders, content); batchResponse.add(batchPartResponse); } else if (batchPartRequest instanceof Olingo4BatchChangeRequest) { Olingo4BatchChangeRequest batchPartChangeRequest = (Olingo4BatchChangeRequest)batchPartRequest; if (batchPartLineStatusCode != HttpStatusCode.NO_CONTENT.getStatusCode()) { if (HttpStatusCode.BAD_REQUEST.getStatusCode() <= batchPartLineStatusCode && batchPartLineStatusCode <= AbstractFutureCallback.NETWORK_CONNECT_TIMEOUT_ERROR) { final ContentType responseContentType = ContentType.parse(batchPartHttpResponse.getFirstHeader(HttpHeaders.CONTENT_TYPE).getValue()); content = odataReader.readError(response.getEntity().getContent(), responseContentType); } else { final UriInfo uriInfo = parseUri(edm, batchPartChangeRequest.getResourcePath() + (batchPartChangeRequest.getOperation() == Operation.CREATE ? CLIENT_ENTITY_FAKE_MARKER : ""), null, serviceUri); content = readContent(uriInfo, batchPartHttpResponse.getEntity().getContent()); } } Olingo4BatchResponse batchPartResponse = new Olingo4BatchResponse(batchPartStatusLine.getStatusCode(), batchPartStatusLine.getReasonPhrase(), batchPartChangeRequest.getContentId(), batchPartHeaders, content); batchResponse.add(batchPartResponse); } else { throw new ODataException("Unsupported batch part request object type: " + batchPartRequest); } batchRequestIndex++; } } catch (IOException | HttpException e) { throw new ODataException(e); } return batchResponse; } private HttpResponse constructBatchPartHttpResponse(InputStream batchPartStream) throws IOException, HttpException { final LineIterator lines = IOUtils.lineIterator(batchPartStream, Constants.UTF8); final ByteArrayOutputStream headerOutputStream = new ByteArrayOutputStream(); final ByteArrayOutputStream bodyOutputStream = new ByteArrayOutputStream(); boolean startBatchPartHeader = false; boolean startBatchPartBody = false; // Iterate through lines in the batch part while (lines.hasNext()) { String line = lines.nextLine().trim(); // Ignore all lines below HTTP/1.1 line if (line.startsWith(HttpVersion.HTTP)) { // This is the first header line startBatchPartHeader = true; } // Body starts with empty string after header lines if (startBatchPartHeader && StringUtils.isBlank(line)) { startBatchPartHeader = false; startBatchPartBody = true; } if (startBatchPartHeader) { // Write header to the output stream headerOutputStream.write(line.getBytes(Constants.UTF8)); headerOutputStream.write(ODataStreamer.CRLF); } else if (startBatchPartBody && StringUtils.isNotBlank(line)) { // Write body to the output stream bodyOutputStream.write(line.getBytes(Constants.UTF8)); bodyOutputStream.write(ODataStreamer.CRLF); } } // Prepare for parsing headers in to the HttpResponse object HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); SessionInputBufferImpl sessionInputBuffer = new SessionInputBufferImpl(metrics, 2048); HttpResponseFactory responseFactory = new DefaultHttpResponseFactory(); sessionInputBuffer.bind(new ByteArrayInputStream(headerOutputStream.toByteArray())); DefaultHttpResponseParser responseParser = new DefaultHttpResponseParser(sessionInputBuffer, new BasicLineParser(), responseFactory, MessageConstraints.DEFAULT); // Parse HTTP response and headers HttpResponse response = responseParser.parse(); // Set body inside entity response.setEntity(new ByteArrayEntity(bodyOutputStream.toByteArray())); return response; } private Collection<String> getHeadersCollection(Header[] headers) { Collection<String> headersCollection = new ArrayList(); for (Header header : Arrays.asList(headers)) { headersCollection.add(header.getValue()); } return headersCollection; } private Map<String, String> getHeadersValueMap(Header[] headers) { Map<String, String> headersValueMap = new HashMap(); for (Header header : Arrays.asList(headers)) { headersValueMap.put(header.getName(), header.getValue()); } return headersValueMap; } private String createUri(String resourcePath) { return createUri(serviceUri, resourcePath, null); } private String createUri(String resourcePath, String queryOptions) { return createUri(serviceUri, resourcePath, queryOptions); } private String createUri(String resourceUri, String resourcePath, String queryOptions) { final StringBuilder absolutUri = new StringBuilder(resourceUri).append(SEPARATOR).append(resourcePath); if (queryOptions != null && !queryOptions.isEmpty()) { absolutUri.append("?" + queryOptions); } return absolutUri.toString(); } private String concatQueryParams(final Map<String, String> queryParams) { final StringBuilder concatQuery = new StringBuilder(""); if (queryParams != null && !queryParams.isEmpty()) { int nParams = queryParams.size(); int index = 0; for (Map.Entry<String, String> entry : queryParams.entrySet()) { concatQuery.append(entry.getKey()).append('=').append(entry.getValue()); if (++index < nParams) { concatQuery.append('&'); } } } return concatQuery.toString().replaceAll(" *", "%20"); } private static UriInfo parseUri(Edm edm, String resourcePath, String queryOptions, String serviceUri) { Parser parser = new Parser(edm, OData.newInstance()); UriInfo result; try { result = parser.parseUri(resourcePath, queryOptions, null, serviceUri); } catch (Exception e) { throw new IllegalArgumentException("parseUri (" + resourcePath + "," + queryOptions + "): " + e.getMessage(), e); } return result; } private static Map<String, String> headersToMap(final Header[] headers) { final Map<String, String> responseHeaders = new HashMap<>(); for (Header header : headers) { responseHeaders.put(header.getName(), header.getValue()); } return responseHeaders; } public void execute(HttpUriRequest httpUriRequest, ContentType contentType, final Map<String, String> endpointHttpHeaders, FutureCallback<HttpResponse> callback) { // add accept header when its not a form or multipart if (!ContentType.APPLICATION_FORM_URLENCODED.equals(contentType) && !contentType.toContentTypeString().startsWith(MULTIPART_MIME_TYPE)) { // otherwise accept what is being sent httpUriRequest.addHeader(HttpHeaders.ACCEPT, contentType.getType().toLowerCase() + "/" + contentType.getSubtype().toLowerCase()); final String acceptCharset = contentType.getParameter(ContentType.PARAMETER_CHARSET); if (null != acceptCharset) { httpUriRequest.addHeader(HttpHeaders.ACCEPT_CHARSET, acceptCharset.toLowerCase()); } } // is something being sent? if (httpUriRequest instanceof HttpEntityEnclosingRequestBase && httpUriRequest.getFirstHeader(HttpHeaders.CONTENT_TYPE) == null) { httpUriRequest.addHeader(HttpHeaders.CONTENT_TYPE, contentType.toString()); } // set user specified custom headers if (ObjectHelper.isNotEmpty(httpHeaders)) { for (Map.Entry<String, String> entry : httpHeaders.entrySet()) { httpUriRequest.setHeader(entry.getKey(), entry.getValue()); } } // set user specified endpoint headers if (ObjectHelper.isNotEmpty(endpointHttpHeaders)) { for (Map.Entry<String, String> entry : endpointHttpHeaders.entrySet()) { httpUriRequest.setHeader(entry.getKey(), entry.getValue()); } } // add 'Accept-Charset' header to avoid BOM marker presents inside // response stream if (!httpUriRequest.containsHeader(HttpHeaders.ACCEPT_CHARSET)) { httpUriRequest.addHeader(HttpHeaders.ACCEPT_CHARSET, Constants.UTF8.toLowerCase()); } // add client protocol version if not specified if (!httpUriRequest.containsHeader(HttpHeader.ODATA_VERSION)) { httpUriRequest.addHeader(HttpHeader.ODATA_VERSION, ODataServiceVersion.V40.toString()); } if (!httpUriRequest.containsHeader(HttpHeader.ODATA_MAX_VERSION)) { httpUriRequest.addHeader(HttpHeader.ODATA_MAX_VERSION, ODataServiceVersion.V40.toString()); } // execute request if (client instanceof CloseableHttpAsyncClient) { ((CloseableHttpAsyncClient)client).execute(httpUriRequest, callback); } else { // invoke the callback methods explicitly after executing the // request synchronously try { CloseableHttpResponse result = ((CloseableHttpClient)client).execute(httpUriRequest); callback.completed(result); } catch (IOException e) { callback.failed(e); } } } }
objectiser/camel
components/camel-olingo4/camel-olingo4-api/src/main/java/org/apache/camel/component/olingo4/api/impl/Olingo4AppImpl.java
Java
apache-2.0
52,209