repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
jentfoo/aws-sdk-java
aws-java-sdk-codepipeline/src/main/java/com/amazonaws/services/codepipeline/model/AcknowledgeThirdPartyJobResult.java
4797
/* * Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.codepipeline.model; import java.io.Serializable; import javax.annotation.Generated; /** * <p> * Represents the output of an AcknowledgeThirdPartyJob action. * </p> * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/AcknowledgeThirdPartyJob" * target="_top">AWS API Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class AcknowledgeThirdPartyJobResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable { /** * <p> * The status information for the third party job, if any. * </p> */ private String status; /** * <p> * The status information for the third party job, if any. * </p> * * @param status * The status information for the third party job, if any. * @see JobStatus */ public void setStatus(String status) { this.status = status; } /** * <p> * The status information for the third party job, if any. * </p> * * @return The status information for the third party job, if any. * @see JobStatus */ public String getStatus() { return this.status; } /** * <p> * The status information for the third party job, if any. * </p> * * @param status * The status information for the third party job, if any. * @return Returns a reference to this object so that method calls can be chained together. * @see JobStatus */ public AcknowledgeThirdPartyJobResult withStatus(String status) { setStatus(status); return this; } /** * <p> * The status information for the third party job, if any. * </p> * * @param status * The status information for the third party job, if any. * @see JobStatus */ public void setStatus(JobStatus status) { withStatus(status); } /** * <p> * The status information for the third party job, if any. * </p> * * @param status * The status information for the third party job, if any. * @return Returns a reference to this object so that method calls can be chained together. * @see JobStatus */ public AcknowledgeThirdPartyJobResult withStatus(JobStatus status) { this.status = status.toString(); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getStatus() != null) sb.append("Status: ").append(getStatus()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof AcknowledgeThirdPartyJobResult == false) return false; AcknowledgeThirdPartyJobResult other = (AcknowledgeThirdPartyJobResult) obj; if (other.getStatus() == null ^ this.getStatus() == null) return false; if (other.getStatus() != null && other.getStatus().equals(this.getStatus()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getStatus() == null) ? 0 : getStatus().hashCode()); return hashCode; } @Override public AcknowledgeThirdPartyJobResult clone() { try { return (AcknowledgeThirdPartyJobResult) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
apache-2.0
odnoklassniki/apache-cassandra
test/unit/org/apache/cassandra/io/SSTableUtils.java
4186
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.cassandra.io; import java.io.File; import java.io.IOException; import java.util.Map; import java.util.SortedMap; import java.util.Set; import java.util.TreeMap; import org.apache.cassandra.config.DatabaseDescriptor; import org.apache.cassandra.db.Column; import org.apache.cassandra.db.ColumnFamily; import org.apache.cassandra.db.Table; import org.apache.cassandra.service.StorageService; import org.apache.cassandra.io.util.DataOutputBuffer; /** * TODO: These methods imitate Memtable.writeSortedKeys to some degree, but * because it is so monolithic, we can't reuse much. */ public class SSTableUtils { // first configured table and cf public static String TABLENAME; public static String CFNAME; static { try { TABLENAME = DatabaseDescriptor.getTables().iterator().next(); CFNAME = Table.open(TABLENAME).getColumnFamilies().iterator().next(); } catch(IOException e) { throw new RuntimeException(e); } } public static File tempSSTableFile(String tablename, String cfname) throws IOException { File tempdir = File.createTempFile(tablename, cfname); if(!tempdir.delete() || !tempdir.mkdir()) throw new IOException("Temporary directory creation failed."); tempdir.deleteOnExit(); File tabledir = new File(tempdir, tablename); tabledir.mkdir(); tabledir.deleteOnExit(); return File.createTempFile(cfname + "-", "-" + SSTable.TEMPFILE_MARKER + "-Data.db", tabledir); } public static SSTableReader writeSSTable(Set<String> keys) throws IOException { TreeMap<String, ColumnFamily> map = new TreeMap<String, ColumnFamily>(); for (String key : keys) { ColumnFamily cf = ColumnFamily.create(TABLENAME, CFNAME); cf.addColumn(new Column(key.getBytes(), key.getBytes(), 0)); map.put(key, cf); } return writeSSTable(map); } public static SSTableReader writeSSTable(SortedMap<String, ColumnFamily> entries) throws IOException { TreeMap<String, byte[]> map = new TreeMap<String, byte[]>(); for (Map.Entry<String, ColumnFamily> entry : entries.entrySet()) { DataOutputBuffer buffer = new DataOutputBuffer(); ColumnFamily.serializer().serializeWithIndexes(entry.getValue(), buffer, false); map.put(entry.getKey(), buffer.getData()); } return writeRawSSTable(TABLENAME, CFNAME, map); } public static SSTableReader writeRawSSTable(String tablename, String cfname, SortedMap<String, byte[]> entries) throws IOException { File f = tempSSTableFile(tablename, cfname); SSTableWriter writer = new SSTableWriter(f.getAbsolutePath(), entries.size(), entries.size()*10, StorageService.getPartitioner()); assert !writer.getBloomFilterWriter().isBloomColumns(); for (Map.Entry<String, byte[]> entry : entries.entrySet()) writer.append(writer.partitioner.decorateKey(entry.getKey()), entry.getValue()); new File(writer.indexFilename()).deleteOnExit(); new File(writer.filterFilename()).deleteOnExit(); return writer.closeAndOpenReader(); } }
apache-2.0
gawkermedia/googleads-java-lib
modules/dfp_axis/src/main/java/com/google/api/ads/dfp/axis/v201511/LiveStreamEventServiceLocator.java
6167
/** * LiveStreamEventServiceLocator.java * * This file was auto-generated from WSDL * by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter. */ package com.google.api.ads.dfp.axis.v201511; public class LiveStreamEventServiceLocator extends org.apache.axis.client.Service implements com.google.api.ads.dfp.axis.v201511.LiveStreamEventService { public LiveStreamEventServiceLocator() { } public LiveStreamEventServiceLocator(org.apache.axis.EngineConfiguration config) { super(config); } public LiveStreamEventServiceLocator(java.lang.String wsdlLoc, javax.xml.namespace.QName sName) throws javax.xml.rpc.ServiceException { super(wsdlLoc, sName); } // Use to get a proxy class for LiveStreamEventServiceInterfacePort private java.lang.String LiveStreamEventServiceInterfacePort_address = "https://ads.google.com/apis/ads/publisher/v201511/LiveStreamEventService"; public java.lang.String getLiveStreamEventServiceInterfacePortAddress() { return LiveStreamEventServiceInterfacePort_address; } // The WSDD service name defaults to the port name. private java.lang.String LiveStreamEventServiceInterfacePortWSDDServiceName = "LiveStreamEventServiceInterfacePort"; public java.lang.String getLiveStreamEventServiceInterfacePortWSDDServiceName() { return LiveStreamEventServiceInterfacePortWSDDServiceName; } public void setLiveStreamEventServiceInterfacePortWSDDServiceName(java.lang.String name) { LiveStreamEventServiceInterfacePortWSDDServiceName = name; } public com.google.api.ads.dfp.axis.v201511.LiveStreamEventServiceInterface getLiveStreamEventServiceInterfacePort() throws javax.xml.rpc.ServiceException { java.net.URL endpoint; try { endpoint = new java.net.URL(LiveStreamEventServiceInterfacePort_address); } catch (java.net.MalformedURLException e) { throw new javax.xml.rpc.ServiceException(e); } return getLiveStreamEventServiceInterfacePort(endpoint); } public com.google.api.ads.dfp.axis.v201511.LiveStreamEventServiceInterface getLiveStreamEventServiceInterfacePort(java.net.URL portAddress) throws javax.xml.rpc.ServiceException { try { com.google.api.ads.dfp.axis.v201511.LiveStreamEventServiceSoapBindingStub _stub = new com.google.api.ads.dfp.axis.v201511.LiveStreamEventServiceSoapBindingStub(portAddress, this); _stub.setPortName(getLiveStreamEventServiceInterfacePortWSDDServiceName()); return _stub; } catch (org.apache.axis.AxisFault e) { return null; } } public void setLiveStreamEventServiceInterfacePortEndpointAddress(java.lang.String address) { LiveStreamEventServiceInterfacePort_address = address; } /** * For the given interface, get the stub implementation. * If this service has no port for the given interface, * then ServiceException is thrown. */ public java.rmi.Remote getPort(Class serviceEndpointInterface) throws javax.xml.rpc.ServiceException { try { if (com.google.api.ads.dfp.axis.v201511.LiveStreamEventServiceInterface.class.isAssignableFrom(serviceEndpointInterface)) { com.google.api.ads.dfp.axis.v201511.LiveStreamEventServiceSoapBindingStub _stub = new com.google.api.ads.dfp.axis.v201511.LiveStreamEventServiceSoapBindingStub(new java.net.URL(LiveStreamEventServiceInterfacePort_address), this); _stub.setPortName(getLiveStreamEventServiceInterfacePortWSDDServiceName()); return _stub; } } catch (java.lang.Throwable t) { throw new javax.xml.rpc.ServiceException(t); } throw new javax.xml.rpc.ServiceException("There is no stub implementation for the interface: " + (serviceEndpointInterface == null ? "null" : serviceEndpointInterface.getName())); } /** * For the given interface, get the stub implementation. * If this service has no port for the given interface, * then ServiceException is thrown. */ public java.rmi.Remote getPort(javax.xml.namespace.QName portName, Class serviceEndpointInterface) throws javax.xml.rpc.ServiceException { if (portName == null) { return getPort(serviceEndpointInterface); } java.lang.String inputPortName = portName.getLocalPart(); if ("LiveStreamEventServiceInterfacePort".equals(inputPortName)) { return getLiveStreamEventServiceInterfacePort(); } else { java.rmi.Remote _stub = getPort(serviceEndpointInterface); ((org.apache.axis.client.Stub) _stub).setPortName(portName); return _stub; } } public javax.xml.namespace.QName getServiceName() { return new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201511", "LiveStreamEventService"); } private java.util.HashSet ports = null; public java.util.Iterator getPorts() { if (ports == null) { ports = new java.util.HashSet(); ports.add(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201511", "LiveStreamEventServiceInterfacePort")); } return ports.iterator(); } /** * Set the endpoint address for the specified port name. */ public void setEndpointAddress(java.lang.String portName, java.lang.String address) throws javax.xml.rpc.ServiceException { if ("LiveStreamEventServiceInterfacePort".equals(portName)) { setLiveStreamEventServiceInterfacePortEndpointAddress(address); } else { // Unknown Port Name throw new javax.xml.rpc.ServiceException(" Cannot set Endpoint Address for Unknown Port" + portName); } } /** * Set the endpoint address for the specified port name. */ public void setEndpointAddress(javax.xml.namespace.QName portName, java.lang.String address) throws javax.xml.rpc.ServiceException { setEndpointAddress(portName.getLocalPart(), address); } }
apache-2.0
mxzs1314/Aviations
app/src/main/java/com/example/administrator/aviation/http/house/HttpPrepareHouse.java
3298
package com.example.administrator.aviation.http.house; import android.util.Log; import com.example.administrator.aviation.http.HttpCommons; import org.ksoap2.SoapEnvelope; import org.ksoap2.serialization.SoapObject; import org.ksoap2.serialization.SoapSerializationEnvelope; import org.ksoap2.transport.HttpTransportSE; import org.kxml2.kdom.Element; import org.kxml2.kdom.Node; /** * house提交信息到服务器获取返回值 */ public class HttpPrepareHouse { public static SoapObject getHouseDetail(String userBumen, String userName, String userPass, String loginFlag, String xml){ // 定义SoapHeader,加入4个节点 Element[] healder = new Element[1]; healder[0] = new Element().createElement(HttpCommons.NAME_SPACE, "AuthHeaderNKG"); Element userBumenE = new Element().createElement(HttpCommons.NAME_SPACE, "IATACode"); userBumenE.addChild(Node.TEXT, userBumen); healder[0].addChild(Node.ELEMENT, userBumenE); Element userNameE = new Element().createElement(HttpCommons.NAME_SPACE, "LoginID"); userNameE.addChild(Node.TEXT, userName); healder[0].addChild(Node.ELEMENT, userNameE); Element userPassE = new Element().createElement(HttpCommons.NAME_SPACE, "Password"); userPassE.addChild(Node.TEXT, userPass); healder[0].addChild(Node.ELEMENT, userPassE); Element loginFlagE = new Element().createElement(HttpCommons.NAME_SPACE, "LoginFlag"); loginFlagE.addChild(Node.TEXT, loginFlag); healder[0].addChild(Node.ELEMENT, loginFlagE); // 指定WebService的命名空间和调用的方法名 SoapObject rpc = new SoapObject(HttpCommons.NAME_SPACE, HttpCommons.HOUSE_SEARCH_METHOD_NAME); // 设置调用webservice接口需要传入的参数 rpc.addProperty("whsXml", xml); rpc.addProperty("ErrString", ""); // 生成调用WebService方法的SOAP请求信息,并指定SOAP的版本 SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); envelope.headerOut = healder; envelope.bodyOut = rpc; // 设置是否调用的是dotNet开发的WebService envelope.dotNet = true; envelope.setOutputSoapObject(rpc); HttpTransportSE transportSE = new HttpTransportSE(HttpCommons.END_POINT); try { // 调用webservice transportSE.call(HttpCommons.HOUSE_SEARCH_METHOD_ACTION, envelope); } catch (Exception e){ e.printStackTrace(); } // 获取返回数据 SoapObject object = (SoapObject) envelope.bodyIn; // 获取返回结果 if (object != null) { String result = object.toString(); Log.e("text",result); } return object; } public static String getHouseXml(String Mawb, String begintime, String endTime, String Dest) { String xml = new String("<DomExportWarehouse>" +"<whsInfo>" +"<Mawb>"+Mawb+"</Mawb>" +"<OPDate>"+begintime+"</OPDate>" +"<PaperTime>"+endTime+"</PaperTime>" +"<Dest>"+Dest+"</Dest>" +"</whsInfo>" +"</DomExportWarehouse>"); return xml; } }
apache-2.0
apache/incubator-kylin
server-base/src/main/java/org/apache/kylin/rest/controller/BasicController.java
5962
/* * 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.kylin.rest.controller; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Locale; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.kylin.rest.constant.Constant; import org.apache.kylin.rest.exception.BadRequestException; import org.apache.kylin.rest.exception.ForbiddenException; import org.apache.kylin.rest.exception.InternalErrorException; import org.apache.kylin.rest.exception.NotFoundException; import org.apache.kylin.rest.exception.TooManyRequestException; import org.apache.kylin.rest.exception.UnauthorizedException; import org.apache.kylin.rest.msg.Message; import org.apache.kylin.rest.msg.MsgPicker; import org.apache.kylin.rest.response.ErrorResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; /** */ public class BasicController { private static final Logger logger = LoggerFactory.getLogger(BasicController.class); @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) @ExceptionHandler(Exception.class) @ResponseBody ErrorResponse handleError(HttpServletRequest req, Exception ex) { logger.error("", ex); Message msg = MsgPicker.getMsg(); Throwable cause = ex; while (cause != null) { if (cause.getClass().getPackage().getName().startsWith("org.apache.hadoop.hbase")) { return new ErrorResponse(req.getRequestURL().toString(), new InternalErrorException( String.format(Locale.ROOT, msg.getHBASE_FAIL(), ex.getMessage()), ex)); } cause = cause.getCause(); } return new ErrorResponse(req.getRequestURL().toString(), ex); } @ResponseStatus(HttpStatus.FORBIDDEN) @ExceptionHandler(ForbiddenException.class) @ResponseBody ErrorResponse handleForbidden(HttpServletRequest req, Exception ex) { return new ErrorResponse(req.getRequestURL().toString(), ex); } @ResponseStatus(HttpStatus.NOT_FOUND) @ExceptionHandler(NotFoundException.class) @ResponseBody ErrorResponse handleNotFound(HttpServletRequest req, Exception ex) { return new ErrorResponse(req.getRequestURL().toString(), ex); } @ResponseStatus(HttpStatus.BAD_REQUEST) @ExceptionHandler(BadRequestException.class) @ResponseBody ErrorResponse handleBadRequest(HttpServletRequest req, Exception ex) { logger.error("", ex); return new ErrorResponse(req.getRequestURL().toString(), ex); } @ResponseStatus(HttpStatus.UNAUTHORIZED) @ExceptionHandler(UnauthorizedException.class) @ResponseBody ErrorResponse handleUnauthorized(HttpServletRequest req, Exception ex) { return new ErrorResponse(req.getRequestURL().toString(), ex); } @ResponseStatus(HttpStatus.TOO_MANY_REQUESTS) @ExceptionHandler(TooManyRequestException.class) @ResponseBody ErrorResponse handleTooManyRequest(HttpServletRequest req, Exception ex) { return new ErrorResponse(req.getRequestURL().toString(), ex); } protected void checkRequiredArg(String fieldName, Object fieldValue) { if (fieldValue == null || StringUtils.isEmpty(String.valueOf(fieldValue))) { throw new BadRequestException(fieldName + " is required"); } } protected void setDownloadResponse(String downloadFile, final HttpServletResponse response) { File file = new File(downloadFile); try (InputStream fileInputStream = new FileInputStream(file); OutputStream output = response.getOutputStream()) { response.reset(); response.setContentType("application/octet-stream"); response.setContentLength((int) (file.length())); response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\""); IOUtils.copyLarge(fileInputStream, output); output.flush(); } catch (IOException e) { throw new InternalErrorException("Failed to download file: " + e.getMessage(), e); } } public boolean isAdmin() { boolean isAdmin = false; Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication != null) { for (GrantedAuthority auth : authentication.getAuthorities()) { if (auth.getAuthority().equals(Constant.ROLE_ADMIN)) { isAdmin = true; break; } } } return isAdmin; } }
apache-2.0
no-hope/java-toolkit
projects/cassandra-map-service/src/test/java/org/nohope/cassandra/mapservice/CMapIT.java
18623
package org.nohope.cassandra.mapservice; import com.google.common.base.Optional; import com.google.common.collect.Lists; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.nohope.cassandra.factory.CassandraFactory; import org.nohope.cassandra.factory.ITHelpers; import org.nohope.cassandra.mapservice.CPreparedGet.PreparedGetExecutor; import org.nohope.cassandra.mapservice.cfilter.CFilter; import org.nohope.cassandra.mapservice.cfilter.CFilters; import org.nohope.cassandra.mapservice.columns.CColumn; import org.nohope.cassandra.mapservice.ctypes.CoreConverter; import org.nohope.cassandra.mapservice.ctypes.custom.UTCDateTimeType; import org.nohope.cassandra.util.RowNotFoundException; import org.nohope.test.ContractUtils; import java.util.*; import static java.lang.Thread.sleep; import static org.junit.Assert.*; import static org.nohope.cassandra.mapservice.QuoteTestGenerator.newQuote; import static org.nohope.cassandra.mapservice.ctypes.CoreConverter.TEXT; /** */ public class CMapIT { private static final CColumn<String, String> COL_QUOTES = CColumn.of("quotes", TEXT); private static final CColumn<DateTime, String> COL_TIMESTAMP = CColumn.of("timestamp", UTCDateTimeType.INSTANCE); private static final CColumn<UUID, UUID> COL_QUOTE_UUID = CColumn.of("quoteuuid", CoreConverter.UUID); private static final TableScheme SCHEME = new CMapBuilder("RingOfPower") .addColumn(COL_QUOTES) .addColumn(COL_TIMESTAMP) .end() .setPartition(COL_QUOTES) .withoutClustering() .buildScheme(); private static final TableScheme THREE_COLUMN_SCHEME = new CMapBuilder("RingOfStupidity") .addColumn(COL_QUOTES) .addColumn(COL_TIMESTAMP) .addColumn(COL_QUOTE_UUID) .end() .setPartition(COL_QUOTES) .withoutClustering().buildScheme(); private CMapSync testMap; private CassandraFactory cassandraFactory; @Before public void setUp() { cassandraFactory = ITHelpers.cassandraFactory(); testMap = new CMapSync(SCHEME, cassandraFactory); } @After public void tearDown() { ITHelpers.destroy(cassandraFactory); } @Test public void inQueryWorks() { final CQuery cQuery = CQueryBuilder .createPreparedQuery() .of(COL_QUOTES) .addFilters() .in(COL_QUOTES) .noMoreFilters() .noFiltering(); final CMapService service = new CMapService(cassandraFactory, SCHEME); final String quote = newQuote(); final ValueTuple valueToPut = ValueTuple.of(COL_QUOTES, quote) .with(COL_TIMESTAMP, DateTime.now(DateTimeZone.UTC)); final CPutQuery putQuery = new CPutQuery(valueToPut); testMap.put(putQuery); final CPreparedGet ringOfPower = service.prepareGet("RingOfPower", cQuery); final PreparedGetExecutor executor = ringOfPower.bind().bindTo(COL_QUOTES.asList(), Arrays.asList(quote)).stopBinding(); final List<ValueTuple> result = Lists.newArrayList(executor.all()); assertEquals(1, result.size()); } @Test public void contractTest() { final CMapSync testMap1 = new CMapSync(SCHEME, cassandraFactory); final CMapSync testMap2 = new CMapSync(SCHEME, cassandraFactory); ContractUtils.assertStrongEquality(testMap1, testMap2); } @Test(expected = IllegalArgumentException.class) public void testQuotedKeyspaceTest() { cassandraFactory.setKeyspace("\"test_Keyspace\""); } @Test public void severalPartitionKeysTest() { final CColumn<String, String> good = CColumn.of("Good", TEXT); final CColumn<String, String> bad = CColumn.of("Bad", TEXT); final CColumn<String, String> ugly = CColumn.of("Ugly", TEXT); final TableScheme scheme = new CMapBuilder("testmap") .addColumn(good) .addColumn(bad) .addColumn(ugly) .end() .setPartition(good) .setClustering(bad, ugly) .buildScheme(); new CMapSync(scheme, cassandraFactory); } @Test public void getOneTrivialTypeTest() throws RowNotFoundException { final ValueTuple valueToPut = ValueTuple.of(COL_QUOTES, newQuote()) .with(COL_TIMESTAMP, DateTime.now(DateTimeZone.UTC)); final CPutQuery putQuery = new CPutQuery(valueToPut); final CQuery query = new CQuery(COL_QUOTES, COL_TIMESTAMP); testMap.put(putQuery); final ValueTuple returnValue = testMap.getOne(query); assertEquals(returnValue, valueToPut); } @Test(expected = CQueryException.class) public void getOneWrongColumnTest() throws RowNotFoundException { final CQuery query = new CQuery(COL_QUOTES, CColumn.of("someColumn", CoreConverter.TEXT)); testMap.getOne(query); } @Test public void getOneFiltersTrivialTypeTest() throws RowNotFoundException { final String quote = newQuote(); final ValueTuple valueToPut = ValueTuple.of(COL_QUOTES, quote) .with(COL_TIMESTAMP, DateTime.now(DateTimeZone.UTC)); final CPutQuery putQuery = new CPutQuery(valueToPut); final CQuery query = CQueryBuilder.createQuery() .of(COL_QUOTES, COL_TIMESTAMP) .addFilters() .eq(COL_QUOTES, quote) .noMoreFilters() .end(); testMap.put(putQuery); final ValueTuple returnValue = testMap.getOne(query); assertEquals(returnValue, valueToPut); } @Test public void getAllTrivialTypeTest() { final CMapSync testMap = new CMapSync(THREE_COLUMN_SCHEME, cassandraFactory); final ValueTuple valueToPut = ValueTuple.of(COL_QUOTES, newQuote()) .with(COL_TIMESTAMP, DateTime.now(DateTimeZone.UTC)) .with(COL_QUOTE_UUID, UUID.randomUUID()); final ValueTuple valueToPut2 = ValueTuple.of(COL_QUOTES, newQuote()) .with(COL_TIMESTAMP, DateTime.now(DateTimeZone.UTC)) .with(COL_QUOTE_UUID, UUID.randomUUID()); testMap.put(new CPutQuery(valueToPut)); testMap.put(new CPutQuery(valueToPut2)); final List<ValueTuple> returnValue = Lists.newArrayList(testMap.all()); assertEquals(2, returnValue.size()); assertTrue(returnValue.contains(valueToPut2)); assertTrue(returnValue.contains(valueToPut)); } @Test public void getTrivialTypeTest() { testMap = new CMapSync(THREE_COLUMN_SCHEME, cassandraFactory); final String quoteToPutAndToGet = newQuote(); final DateTime dateToPutAndToGet = DateTime.now(DateTimeZone.UTC); final ValueTuple valueToPut = ValueTuple.of(COL_QUOTES, quoteToPutAndToGet) .with(COL_TIMESTAMP, dateToPutAndToGet) .with(COL_QUOTE_UUID, UUID.randomUUID()); final ValueTuple valueToPut2 = ValueTuple.of(COL_QUOTES, newQuote()) .with(COL_TIMESTAMP, DateTime.now(DateTimeZone.UTC)) .with(COL_QUOTE_UUID, UUID.randomUUID()); testMap.put(new CPutQuery(valueToPut)); testMap.put(new CPutQuery(valueToPut2)); final ColumnsSet set = new ColumnsSet() .with(COL_QUOTES) .with(COL_TIMESTAMP); final Collection<CFilter<?>> filters = new ArrayList<>(); filters.add(CFilters.eq(Value.bound(COL_QUOTES, quoteToPutAndToGet))); final CQuery query = CQueryBuilder .createQuery() .of(set) .withFilters(filters) .end(); final List<ValueTuple> returnValue = Lists.newArrayList(testMap.get(query)); assertEquals(1, returnValue.size()); final ValueTuple value = returnValue.get(0); assertEquals(value.get(COL_QUOTES), quoteToPutAndToGet); assertEquals(value.get(COL_TIMESTAMP), dateToPutAndToGet); } @Test public void getTrivialTypeAllowFilteringTest() { testMap = new CMapSync(THREE_COLUMN_SCHEME, cassandraFactory); final String quoteToPutAndToGet = newQuote(); final DateTime dateToPutAndToGet = DateTime.now(DateTimeZone.UTC); final ValueTuple valueToPut = ValueTuple.of(COL_QUOTES, quoteToPutAndToGet) .with(COL_TIMESTAMP, dateToPutAndToGet) .with(COL_QUOTE_UUID, UUID.randomUUID()); final ValueTuple valueToPut2 = ValueTuple.of(COL_QUOTES, newQuote()) .with(COL_TIMESTAMP, DateTime.now(DateTimeZone.UTC)) .with(COL_QUOTE_UUID, UUID.randomUUID()); testMap.put(new CPutQuery(valueToPut)); testMap.put(new CPutQuery(valueToPut2)); final CQuery query = CQueryBuilder .createQuery() .of(COL_QUOTES, COL_TIMESTAMP) .addFilters() .eq(COL_QUOTES, quoteToPutAndToGet) .noMoreFilters() .allowFiltering() .end(); final List<ValueTuple> returnValue = Lists.newArrayList(testMap.get(query)); assertEquals(1, returnValue.size()); final ValueTuple value = returnValue.get(0); assertEquals(value.get(COL_QUOTES), quoteToPutAndToGet); assertEquals(value.get(COL_TIMESTAMP), dateToPutAndToGet); } @Test public void removeTrivialTypeTest() { testMap = new CMapSync(THREE_COLUMN_SCHEME, cassandraFactory); final ValueTuple valueToPut = ValueTuple.of(COL_QUOTES, newQuote()) .with(COL_TIMESTAMP, DateTime.now(DateTimeZone.UTC)) .with(COL_QUOTE_UUID, UUID.randomUUID()); final ValueTuple valueToPut2 = ValueTuple.of(COL_QUOTES, newQuote()) .with(COL_TIMESTAMP, DateTime.now(DateTimeZone.UTC)) .with(COL_QUOTE_UUID, UUID.randomUUID()); testMap.put(new CPutQuery(valueToPut)); testMap.put(new CPutQuery(valueToPut2)); final CQuery query = CQueryBuilder .createRemoveQuery() .withFilters(CFilters.eq(Value.bound(COL_QUOTES, valueToPut.get(COL_QUOTES)))) .end(); testMap.remove(query); final List<ValueTuple> returnValue = Lists.newArrayList(testMap.all()); assertEquals(1, returnValue.size()); assertTrue(returnValue.contains(valueToPut2)); assertFalse(returnValue.contains(valueToPut)); } @Test public void multipleRemoveTrivialTypeTest() { testMap = new CMapSync(THREE_COLUMN_SCHEME, cassandraFactory); final ValueTuple valueToPut = ValueTuple.of(COL_QUOTES, newQuote()) .with(COL_TIMESTAMP, DateTime.now(DateTimeZone.UTC)) .with(COL_QUOTE_UUID, UUID.randomUUID()); final ValueTuple valueToPut2 = ValueTuple.of(COL_QUOTES, newQuote()) .with(COL_TIMESTAMP, DateTime.now(DateTimeZone.UTC)) .with(COL_QUOTE_UUID, UUID.randomUUID()); testMap.put(new CPutQuery(valueToPut)); testMap.put(new CPutQuery(valueToPut2)); final CQuery query = CQueryBuilder .createRemoveQuery() .addFilters() .eq(COL_QUOTES, valueToPut.get(COL_QUOTES)) .noMoreFilters() .end(); testMap.remove(query); final List<ValueTuple> returnValue = Lists.newArrayList(testMap.all()); assertEquals(1, returnValue.size()); assertTrue(returnValue.contains(valueToPut2)); } @Test public void multipleRemoveTrivialTypeWithNColumnSetTest() { testMap = new CMapSync(THREE_COLUMN_SCHEME, cassandraFactory); final ValueTuple valueToPut = ValueTuple.of(COL_QUOTES, newQuote()) .with(COL_TIMESTAMP, DateTime.now(DateTimeZone.UTC)) .with(COL_QUOTE_UUID, UUID.randomUUID()); final ValueTuple valueToPut2 = ValueTuple.of(COL_QUOTES, newQuote()) .with(COL_TIMESTAMP, DateTime.now(DateTimeZone.UTC)) .with(COL_QUOTE_UUID, UUID.randomUUID()); testMap.put(new CPutQuery(valueToPut)); testMap.put(new CPutQuery(valueToPut2)); final CQuery query = CQueryBuilder .createRemoveQuery() .withFilters(CFilters.eq(Value.bound(COL_QUOTES, valueToPut.get(COL_QUOTES)))) .end(); testMap.remove(query); final List<ValueTuple> returnValue = Lists.newArrayList(testMap.all()); assertEquals(1, returnValue.size()); assertTrue(returnValue.contains(valueToPut2)); assertFalse(returnValue.contains(valueToPut)); } @Test public void putWithTtlTest() throws InterruptedException { testMap = new CMapSync(THREE_COLUMN_SCHEME, cassandraFactory); final ValueTuple valueToPut = ValueTuple.of(COL_QUOTES, newQuote()) .with(COL_TIMESTAMP, DateTime.now(DateTimeZone.UTC)) .with(COL_QUOTE_UUID, UUID.randomUUID()); testMap.put(new CPutQuery(valueToPut, Optional.of(1))); sleep(2000); final List<ValueTuple> returnValue = Lists.newArrayList(testMap.all()); assertEquals(0, returnValue.size()); } @Test public void simpleCountTest() throws InterruptedException { generateTableEntries(testMap, 20); final CQuery query = CQueryBuilder .createCountQuery() .end(); assertEquals(20L, testMap.count(query)); } @Test public void filterCountTest() throws InterruptedException { generateTableEntries(testMap, 20); final CQuery query = CQueryBuilder .createCountQuery() .addFilters() .eq(COL_QUOTES, newQuote()) .noMoreFilters() .end(); assertEquals(0L, testMap.count(query)); } @Test public void orderingByClusteringAndPartitionKeysTest() { final TableScheme scheme = new CMapBuilder("RingOfPowerOrderings") .addColumn(COL_QUOTES) .addColumn(COL_TIMESTAMP) .end() .setPartition(COL_QUOTES) .setClustering(COL_TIMESTAMP) .buildScheme(); testMap = new CMapSync(scheme, cassandraFactory); // partition: { final CQuery query = CQueryBuilder .createQuery() .of(COL_QUOTES) .addFilters() .eq(COL_QUOTES, newQuote()) .noMoreFilters() .orderingBy(COL_QUOTES, Orderings.ASC) .end(); testMap.get(query); } // clustering: { final CQuery query = CQueryBuilder .createQuery() .of(COL_QUOTES) .addFilters() .eq(COL_QUOTES, newQuote()) .noMoreFilters() .orderingBy(COL_TIMESTAMP, Orderings.ASC) .end(); testMap.get(query); } } @Test public void dateTest() { final String quote = newQuote(); final ValueTuple valueToPut = ValueTuple.of(COL_QUOTES, quote) .with(COL_TIMESTAMP, DateTime.now(DateTimeZone.UTC)); testMap.put(new CPutQuery(valueToPut)); final CQuery query = CQueryBuilder .createRemoveQuery() .addFilters() .eq(COL_QUOTES, quote) .noMoreFilters() .end(); List<ValueTuple> value = Lists.newArrayList(testMap.get(query)); //TODO: WTF? } @Test public void removeTrivialTypeSeveralPrimaryKeysTest() { final TableScheme scheme = new CMapBuilder("table") .addColumn(COL_QUOTES) .addColumn(COL_TIMESTAMP) .addColumn(COL_QUOTE_UUID) .end() .setPartition(COL_QUOTES, COL_QUOTE_UUID) .withoutClustering().buildScheme(); testMap = new CMapSync(scheme, cassandraFactory); final ValueTuple valueToPut = ValueTuple.of(COL_QUOTES, newQuote()) .with(COL_TIMESTAMP, DateTime.now(DateTimeZone.UTC)) .with(COL_QUOTE_UUID, UUID.randomUUID()); final ValueTuple valueToPut2 = ValueTuple.of(COL_QUOTES, newQuote()) .with(COL_TIMESTAMP, DateTime.now(DateTimeZone.UTC)) .with(COL_QUOTE_UUID, UUID.randomUUID()); testMap.put(new CPutQuery(valueToPut)); testMap.put(new CPutQuery(valueToPut2)); final CQuery query = CQueryBuilder .createRemoveQuery() .withFilters(CFilters.eq(Value.bound(COL_QUOTES, valueToPut.get(COL_QUOTES))), CFilters.eq(Value.bound(COL_QUOTE_UUID, valueToPut.get(COL_QUOTE_UUID)))) .end(); testMap.remove(query); final List<ValueTuple> returnValue = Lists.newArrayList(testMap.all()); assertEquals(1, returnValue.size()); assertTrue(returnValue.contains(valueToPut2)); assertFalse(returnValue.contains(valueToPut)); } private static void generateTableEntries(final CMapSync testMap, final int count) throws InterruptedException { for (int i = 0; i < count; ++i) { testMap.put(new CPutQuery( ValueTuple.of(COL_QUOTES, newQuote()) .with(COL_TIMESTAMP, DateTime.now(DateTimeZone.UTC)))); sleep(count * 10); } } }
apache-2.0
bozimmerman/CoffeeMud
com/planet_ink/coffee_mud/Abilities/Prayers/Prayer_BirdsEye.java
3554
package com.planet_ink.coffee_mud.Abilities.Prayers; import com.planet_ink.coffee_mud.core.interfaces.*; import com.planet_ink.coffee_mud.core.*; import com.planet_ink.coffee_mud.core.collections.*; 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.Libraries.interfaces.TrackingLibrary; 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 2004-2022 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. */ public class Prayer_BirdsEye extends Prayer { @Override public String ID() { return "Prayer_BirdsEye"; } private final static String localizedName = CMLib.lang().L("Birds Eye"); @Override public String name() { return localizedName; } @Override public int classificationCode() { return Ability.ACODE_PRAYER|Ability.DOMAIN_COMMUNING; } @Override public long flags() { return Ability.FLAG_NEUTRAL; } @Override public int abstractQuality() { return Ability.QUALITY_INDIFFERENT; } @Override public boolean invoke(final MOB mob, final List<String> commands, final Physical givenTarget, final boolean auto, final int asLevel) { if(!super.invoke(mob,commands,givenTarget,auto,asLevel)) return false; final boolean success=proficiencyCheck(mob,0,auto); if(success) { CMMsg msg=CMClass.getMsg(mob,null,this,verbalCastCode(mob,null,auto),auto?"":L("^S<S-NAME> @x1 for a birds eye view.^?",prayWord(mob))); if(mob.location().okMessage(mob,msg)) { mob.location().send(mob,msg); final Item I=CMClass.getItem("BardMap"); if(I!=null) { final Vector<Room> set=new Vector<Room>(); TrackingLibrary.TrackingFlags flags; flags = CMLib.tracking().newFlags() .plus(TrackingLibrary.TrackingFlag.NOEMPTYGRIDS) .plus(TrackingLibrary.TrackingFlag.NOAIR); CMLib.tracking().getRadiantRooms(mob.location(),set,flags,null,2,null); final StringBuffer str=new StringBuffer(""); for(int i=0;i<set.size();i++) str.append(CMLib.map().getExtendedRoomID(set.elementAt(i))+";"); I.setReadableText(str.toString()); I.setName(""); I.basePhyStats().setDisposition(PhyStats.IS_GLOWING); msg=CMClass.getMsg(mob,I,CMMsg.MSG_READ,""); mob.addItem(I); mob.location().send(mob,msg); I.destroy(); } } } else beneficialWordsFizzle(mob,null,L("<S-NAME> @x1 for a birds eye view, but fail(s).",prayWord(mob))); return success; } }
apache-2.0
mvniekerk/titanium4j
src/com/emitrom/ti4j/mobile/client/ui/ios/AdView.java
4184
/************************************************************************ AdView.java is part of Ti4j 3.1.0 Copyright 2013 Emitrom LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. **************************************************************************/ package com.emitrom.ti4j.mobile.client.ui.ios; import com.emitrom.ti4j.mobile.client.core.handlers.ErrorHandler; import com.emitrom.ti4j.mobile.client.core.handlers.loading.LoadHandler; import com.emitrom.ti4j.mobile.client.core.handlers.ui.ChangeHandler; import com.emitrom.ti4j.mobile.client.ui.View; /** * The adview is a view for display apple iads. the view is created by the * method {@link com.emitrom.ti4j.mobile.client.ui.ios.IOS.createAdView}. */ public class AdView extends View { public static String SIZE_320x50 = SIZE_320x50(); public static String SIZE_480x32 = SIZE_480x32(); public AdView() { createPeer(); } /** * A banner view action can cover your application's user interface. * however, your application continues to run, and receives events normally. * if your application receives an event that requires the user's attention, * it can programmatically cancel the action and uncover its interface by * calling cancelaction. canceling actions frequently can cause a loss of * revenue for your application. */ public native void cancelAction() /*-{ var jso = this.@com.emitrom.ti4j.core.client.ProxyObject::getJsObj()(); return jso.cancelAction(); }-*/; public native void addChangeHandler(ChangeHandler handler)/*-{ var jso = this.@com.emitrom.ti4j.core.client.ProxyObject::getJsObj()(); jso .addEventListener( @com.emitrom.ti4j.mobile.client.core.events.ui.UIEvent::CHANGE, function(e) { var eventObject = @com.emitrom.ti4j.mobile.client.core.events.ui.UIEvent::new(Lcom/google/gwt/core/client/JavaScriptObject;)(e); handler.@com.emitrom.ti4j.mobile.client.core.handlers.ui.ChangeHandler::onChange(Lcom/emitrom/ti4j/mobile/client/core/events/ui/UIEvent;)(eventObject); }); }-*/; public native void addErrorHandler(ErrorHandler handler)/*-{ var jso = this.@com.emitrom.ti4j.core.client.ProxyObject::getJsObj()(); jso .addEventListener( @com.emitrom.ti4j.mobile.client.core.events.ErrorEvent::ERROR, function(e) { var eventObject = @com.emitrom.ti4j.mobile.client.core.events.ErrorEvent::new(Lcom/google/gwt/core/client/JavaScriptObject;)(e); handler.@com.emitrom.ti4j.mobile.client.core.handlers.ErrorHandler::onError(Lcom/emitrom/ti4j/mobile/client/core/events/ErrorEvent;)(eventObject); }); }-*/; public native void addLoadHandler(LoadHandler handler)/*-{ var jso = this.@com.emitrom.ti4j.core.client.ProxyObject::getJsObj()(); jso .addEventListener( @com.emitrom.ti4j.mobile.client.core.events.loading.LoadEvent::LOAD, function(e) { var eventObject = @com.emitrom.ti4j.mobile.client.core.events.loading.LoadEvent::new(Lcom/google/gwt/core/client/JavaScriptObject;)(e); handler.@com.emitrom.ti4j.mobile.client.core.handlers.loading.LoadHandler::onLoad(Lcom/emitrom/ti4j/mobile/client/core/events/loading/LoadEvent;)(eventObject); }); }-*/; @Override public void createPeer() { jsObj = IOS.get().createAdView(); } /** * @return Constant for 320x50 ad sizes */ private static native String SIZE_320x50() /*-{ return Titanium.UI.iOS.AdView.SIZE_320x50; }-*/; /** * @return Constant for 480x32 ad sizes */ private static native String SIZE_480x32() /*-{ return Titanium.UI.iOS.AdView.SIZE_480x32; }-*/; }
apache-2.0
IMCG/priter
src/examples/org/apache/hadoop/examples/priorityiteration/KatzActivator.java
3335
package org.apache.hadoop.examples.priorityiteration; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import java.util.StringTokenizer; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.FloatWritable; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.mapred.Activator; import org.apache.hadoop.mapred.JobConf; import org.apache.hadoop.mapred.PrIterBase; import org.apache.hadoop.mapred.OutputCollector; import org.apache.hadoop.mapred.Reporter; import org.apache.hadoop.mapred.buffer.impl.InputPKVBuffer; public class KatzActivator extends PrIterBase implements Activator<IntWritable, FloatWritable, FloatWritable> { private String subGraphsDir; private int kvs = 0; private int iter = 0; private int partitions; private float beta; //graph in local memory private HashMap<Integer, ArrayList<Integer>> linkList = new HashMap<Integer, ArrayList<Integer>>(); private synchronized void loadGraphToMem(JobConf conf, int n){ subGraphsDir = conf.get(MainDriver.SUBGRAPH_DIR); Path remote_link = new Path(subGraphsDir + "/part" + n); FileSystem hdfs = null; try { hdfs = FileSystem.get(conf); FSDataInputStream in = hdfs.open(remote_link); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String line; while((line = reader.readLine()) != null){ int index = line.indexOf("\t"); if(index != -1){ String node = line.substring(0, index); String linkstring = line.substring(index+1); ArrayList<Integer> links = new ArrayList<Integer>(); StringTokenizer st = new StringTokenizer(linkstring); while(st.hasMoreTokens()){ links.add(Integer.parseInt(st.nextToken())); } this.linkList.put(Integer.parseInt(node), links); } } reader.close(); } catch (IOException e) { e.printStackTrace(); } } @Override public void configure(JobConf job) { int taskid = Util.getTaskId(job); partitions = job.getInt("priter.graph.partitions", 1); beta = job.getFloat(MainDriver.KATZ_BETA, (float)0.05); loadGraphToMem(job, taskid); } @Override public void initStarter(InputPKVBuffer<IntWritable, FloatWritable> starter) throws IOException { starter.init(new IntWritable(0), new FloatWritable(1000000)); } @Override public void activate(IntWritable key, FloatWritable value, OutputCollector<IntWritable, FloatWritable> output, Reporter report) throws IOException { kvs++; report.setStatus(String.valueOf(kvs)); int page = key.get(); ArrayList<Integer> links = null; links = this.linkList.get(key.get()); if(links == null){ System.out.println("no links found for node " + page); for(int i=0; i<partitions; i++){ output.collect(new IntWritable(i), new FloatWritable(0)); } return; } float delta = value.get() * beta; for(int link : links){ output.collect(new IntWritable(link), new FloatWritable(delta)); } } @Override public void iterate() { System.out.println((iter++) + " passes " + kvs + " activations"); } }
apache-2.0
treason258/TreCore
app/src/main/java/com/mjiayou/trecore/test/router/RouterActivity.java
1587
package com.mjiayou.trecore.test.router; import android.os.Bundle; import android.view.View; import android.widget.TextView; import com.mjiayou.myannotation.TCBindPath; import com.mjiayou.trecore.R; import com.mjiayou.treannotation.TCRouterName; import com.mjiayou.treannotation.TCRouter; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; @TCBindPath(TCRouterName.ROUTER_ACTIVITY) public class RouterActivity extends AppCompatActivity { private TextView tvRouter; // @Override // protected int getLayoutId() { // return R.layout.activity_router; // } // // @Override // protected void afterOnCreate(Bundle savedInstanceState) { // getTitleBar().setTitle("RouterActivity"); // // tvRouter = (TextView) findViewById(R.id.tvRouter); // tvRouter.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View view) { // TCRouter.get().startActivity(mContext, "TestModuleAActivity", null); // } // }); // } @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_router); tvRouter = (TextView) findViewById(R.id.tvRouter); tvRouter.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { TCRouter.get().startActivity(RouterActivity.this, TCRouterName.TEST_MODULE_A_ACTIVITY, null); } }); } }
apache-2.0
OSEHRA/ISAAC
core/model/src/main/java/sh/isaac/model/logic/node/internal/RoleNodeSomeWithNids.java
6228
/* * 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. * * Contributions from 2013-2017 where performed either by US government * employees, or under US Veterans Health Administration contracts. * * US Veterans Health Administration contributions by government employees * are work of the U.S. Government and are not subject to copyright * protection in the United States. Portions contributed by government * employees are USGovWork (17USC §105). Not subject to copyright. * * Contribution by contractors to the US Veterans Health Administration * during this period are contractually contributed under the * Apache License, Version 2.0. * * See: https://www.usa.gov/government-works * * Contributions prior to 2013: * * Copyright (C) International Health Terminology Standards Development Organisation. * Licensed under the Apache License, Version 2.0. * */ package sh.isaac.model.logic.node.internal; //~--- JDK imports ------------------------------------------------------------ import java.util.UUID; //~--- non-JDK imports -------------------------------------------------------- import sh.isaac.api.DataTarget; import sh.isaac.api.Get; import sh.isaac.api.externalizable.ByteArrayDataBuffer; import sh.isaac.api.logic.LogicNode; import sh.isaac.api.logic.NodeSemantic; import sh.isaac.api.util.UuidT5Generator; import sh.isaac.model.logic.LogicalExpressionImpl; import sh.isaac.model.logic.node.AbstractLogicNode; import sh.isaac.model.logic.node.external.RoleNodeSomeWithUuids; //~--- classes ---------------------------------------------------------------- /** * Created by kec on 12/10/14. */ public final class RoleNodeSomeWithNids extends TypedNodeWithNids { /** * Instantiates a new role node some with uuids. * * @param externalForm the external form */ public RoleNodeSomeWithNids(RoleNodeSomeWithUuids externalForm) { super(externalForm); //can't run validation here due to problems with this constructor pattern. } /** * Instantiates a new role node some with serialized data. * * @param logicGraphVersion the logic graph version * @param dataInputStream the data input stream */ public RoleNodeSomeWithNids(LogicalExpressionImpl logicGraphVersion, ByteArrayDataBuffer dataInputStream) { super(logicGraphVersion, dataInputStream); //will skip validate here, since it is highly unlikely it was created without being validated in the first place. } /** * Instantiates a new role node some with sequences. * * @param logicGraphVersion the logic graph version * @param typeConceptId the type concept id * @param child the child */ public RoleNodeSomeWithNids(LogicalExpressionImpl logicGraphVersion, int typeConceptId, AbstractLogicNode child) { super(logicGraphVersion, typeConceptId, child); validate(); } private void validate() { NodeSemantic childSemantic = getOnlyChild().getNodeSemantic(); if (childSemantic == NodeSemantic.OR) { throw new RuntimeException("The child of a Role_Some must not be " + getOnlyChild().getNodeSemantic()); } } //~--- methods ------------------------------------------------------------- /** * To string. * * @return the string */ @Override public String toString() { return toString(""); } /** * To string. * * @param nodeIdSuffix the node id suffix * @return the string */ @Override public String toString(String nodeIdSuffix) { return "Some[" + getNodeIndex() + nodeIdSuffix + "]" + super.toString(nodeIdSuffix); } @Override public String toSimpleString() { return "Some " + super.toSimpleString(); } @Override public void addToBuilder(StringBuilder builder) { builder.append("\n SomeRole("); builder.append("Get.concept(\"").append(Get.identifierService().getUuidPrimordialStringForNid(typeConceptNid)).append("\")"); builder.append(", "); for (AbstractLogicNode child: getChildren()) { child.addToBuilder(builder); } builder.append(")\n"); } /** * Write node data. * * @param dataOutput the data output * @param dataTarget the data target */ @Override public void writeNodeData(ByteArrayDataBuffer dataOutput, DataTarget dataTarget) { switch (dataTarget) { case EXTERNAL: final RoleNodeSomeWithUuids externalForm = new RoleNodeSomeWithUuids(this); externalForm.writeNodeData(dataOutput, dataTarget); break; case INTERNAL: super.writeNodeData(dataOutput, dataTarget); break; default: throw new UnsupportedOperationException("Can't handle dataTarget: " + dataTarget); } } /** * Compare typed node fields. * * @param o the o * @return the int */ @Override protected int compareTypedNodeFields(LogicNode o) { // node semantic already determined equals. return 0; } /** * Inits the node uuid. * * @return the uuid */ @Override protected UUID initNodeUuid() { return UuidT5Generator.get(getNodeSemantic().getSemanticUuid(), Integer.toString(typeConceptNid)); } //~--- get methods --------------------------------------------------------- /** * Gets the node semantic. * * @return the node semantic */ @Override public NodeSemantic getNodeSemantic() { return NodeSemantic.ROLE_SOME; } }
apache-2.0
PheMA/phema-executer
src/main/java/org/phema/executer/hqmf/models/Identifier.java
782
package org.phema.executer.hqmf.models; /** * Created by Luke Rasmussen on 8/21/17. */ public class Identifier { private String type; private String root; private String extension; public Identifier(String type, String root, String extension) { this.type = type; this.root = root; this.extension = extension; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getRoot() { return root; } public void setRoot(String root) { this.root = root; } public String getExtension() { return extension; } public void setExtension(String extension) { this.extension = extension; } }
apache-2.0
Inari-Soft/inari-firefly
src/test/java/com/inari/firefly/physics/animation/TestIntAnimation.java
445
package com.inari.firefly.physics.animation; public class TestIntAnimation extends IntAnimation { private int value = 0; protected TestIntAnimation( int id ) { super( id ); } @Override public int getInitValue() { return 0; } @Override public int getValue( int component, int currentValue ) { return value; } @Override public void update() { value++; } }
apache-2.0
INDExOS/media-for-mobile
domain/src/test/java/org/m4m/domain/dsl/AudioDecoderFather.java
1467
/* * Copyright 2014-2016 Media for Mobile * * 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.m4m.domain.dsl; import org.m4m.domain.AudioDecoder; import org.m4m.domain.Frame; import org.m4m.domain.MediaFormat; import org.m4m.domain.MediaFormatType; public class AudioDecoderFather extends DecoderFather { public AudioDecoderFather(Father create) { super(create); with(MediaFormatType.AUDIO); with(create.audioFormat().construct()); } public AudioDecoderFather whichDecodesTo(Frame frame) { super.whichDecodesTo(frame); return this; } public AudioDecoderFather with(MediaFormat mediaFormat) { super.with(mediaFormat); return this; } public AudioDecoder construct() { AudioDecoder decoder = new AudioDecoder(mediaCodec != null ? mediaCodec : mediaCodecFather.construct()); decoder.setMediaFormat(mediaFormat); return decoder; } }
apache-2.0
GerritCodeReview/gerrit
java/com/google/gerrit/extensions/common/FileInfo.java
1941
// Copyright (C) 2014 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.gerrit.extensions.common; import java.util.Objects; public class FileInfo { public Character status; public Boolean binary; public String oldPath; public Integer linesInserted; public Integer linesDeleted; public long sizeDelta; public long size; @Override public boolean equals(Object o) { if (o instanceof FileInfo) { FileInfo fileInfo = (FileInfo) o; return Objects.equals(status, fileInfo.status) && Objects.equals(binary, fileInfo.binary) && Objects.equals(oldPath, fileInfo.oldPath) && Objects.equals(linesInserted, fileInfo.linesInserted) && Objects.equals(linesDeleted, fileInfo.linesDeleted) && sizeDelta == fileInfo.sizeDelta && size == fileInfo.size; } return false; } @Override public int hashCode() { return Objects.hash(status, binary, oldPath, linesInserted, linesDeleted, sizeDelta, size); } @Override public String toString() { return "FileInfo{" + "status=" + status + ", binary=" + binary + ", oldPath=" + oldPath + ", linesInserted=" + linesInserted + ", linesDeleted=" + linesDeleted + ", sizeDelta=" + sizeDelta + ", size=" + size + "}"; } }
apache-2.0
noties/ScriptJava
src/scriptjava/IScript.java
706
/* * Copyright 2016 Dimitry Ivanov (copy@dimitryivanov.ru) * * 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 scriptjava; public interface IScript { void execute() throws Throwable; }
apache-2.0
freeVM/freeVM
enhanced/archive/classlib/java6/modules/nio/src/main/java/java/nio/channels/Channel.java
2351
/* 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 java.nio.channels; import java.io.Closeable; import java.io.IOException; /** * A channel is a conduit to IO services covering such items as files, sockets, * hardware devices, IO ports, or some software component. * <p> * Channels are open upon creation, and can be explicitly closed. Once a channel * is closed it cannot be re-opened, and attempts to perform IO operations on * the closed channel result in a <code>ClosedChannelException * </code>. * </p> * <p> * Particular implementations or sub-interfaces of Channel dictate whether they * are thread-safe or not. * </p> * */ public interface Channel extends Closeable { /** * Answers whether this channel is open or not. * * @return true if the channel is open, otherwise answers false. */ public boolean isOpen(); /** * Closes an open channel. * * If the channel is already closed this method has no effect. If there is a * problem with closing the channel then the method throws an IOException * and the exception contains reasons for the failure. * <p> * If an attempt is made to perform an operation on a closed channel then a * <code>ClosedChannelException</code> will be thrown on that attempt. * </p> * <p> * If multiple threads attempts to simultaneously close a channel, then only * one thread will run the closure code, and others will be blocked until the * first returns. * </p> * * @throws IOException * if a problem occurs closing the channel. */ public void close() throws IOException; }
apache-2.0
phax/ph-oton
ph-oton-bootstrap3/src/main/java/com/helger/photon/bootstrap3/alert/BootstrapInfoBox.java
917
/* * Copyright (C) 2014-2022 Philip Helger (www.helger.com) * philip[at]helger[dot]com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.helger.photon.bootstrap3.alert; /** * Bootstrap info box * * @author Philip Helger */ public class BootstrapInfoBox extends AbstractBootstrapAlert <BootstrapInfoBox> { public BootstrapInfoBox () { super (EBootstrapAlertType.INFO); } }
apache-2.0
liuxv/SlidingLayout
external/sliding/src/com/liuxv/sliding/PageTransaction.java
2127
package com.liuxv.sliding; /** * 由于进入进出顺序不确定,需要判断一些 transaction 状态 * 此类用于维护 transaction * * @author liuxu87@gmail.com (Liu Xu) */ public class PageTransaction { /** * 是否允许视察动画 */ private boolean mAnimEnable; /** * 是否设定了进入动画 */ private boolean mIsEnterAnimSchedule; /** * 是否执行了进入、退出动画 */ private boolean mIsPerformedEnterAnim; private boolean mIsPerformedExitAnim; /** * 是否调用了进入、退出结束 */ private boolean mEndEnterTransaction; private boolean mEndExitTransaction; public PageTransaction() {} public boolean isAnimEnable() { return mAnimEnable; } public boolean isEnterAnimSchedule() { return mIsEnterAnimSchedule; } public boolean needDoExitAnim() { return mIsPerformedEnterAnim && (!mIsPerformedExitAnim) && mEndEnterTransaction && (!mEndExitTransaction); } public boolean needDoEnterAnim() { return (!mIsPerformedEnterAnim) && (!mIsPerformedExitAnim) && (!mEndEnterTransaction) && (!mEndExitTransaction); } public void setAnimEnable(boolean isEnable) { mAnimEnable = isEnable; } public void scheduleEnterAnimSchedule() { mIsEnterAnimSchedule = true; } public void doEnterAnim(SlidingLayout slidingLayout, float enterPosition) { mIsPerformedEnterAnim = true; slidingLayout.slientSmoothSlideTo(enterPosition); } public void doExitAnim(SlidingLayout slidingLayout, float closePosition) { mIsPerformedExitAnim = true; slidingLayout.slientSmoothSlideTo(closePosition); } public boolean isTransactionEnded() { return mEndEnterTransaction && mEndExitTransaction; } public void endEnterTransaction() { mEndEnterTransaction = true; } public void endExitTransaction() { mEndExitTransaction = true; } public void beginNewTransaction() { mIsEnterAnimSchedule = false; mIsPerformedEnterAnim = false; mIsPerformedExitAnim = false; mEndEnterTransaction = false; mEndExitTransaction = false; } }
apache-2.0
Netflix/zeno
src/main/java/com/netflix/zeno/fastblob/OrdinalMapping.java
1379
/* * * Copyright 2014 Netflix, 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.netflix.zeno.fastblob; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; public class OrdinalMapping { Map<String, StateOrdinalMapping> stateOrdinalMappings; public OrdinalMapping() { stateOrdinalMappings = new ConcurrentHashMap<String, StateOrdinalMapping>(); } public StateOrdinalMapping createStateOrdinalMapping(String type, int maxOriginalOrdinal) { StateOrdinalMapping stateOrdinalMapping = new StateOrdinalMapping(maxOriginalOrdinal); stateOrdinalMappings.put(type, stateOrdinalMapping); return stateOrdinalMapping; } public StateOrdinalMapping getStateOrdinalMapping(String type) { return stateOrdinalMappings.get(type); } }
apache-2.0
SciGaP/seagrid-rich-client
src/main/java/gamess/GlobalParameters.java
4344
/*Copyright (c) 2007, Center for Computational Sciences, University of Kentucky. All rights reserved. Developed by: Center for Computational Sciences, University of Kentucky http://www.ccs.uky.edu Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal with 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: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimers. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimers in the documentation and/or other materials provided with the distribution. 3. Neither the names of Center for Computational Sciences, University of Kentucky nor the names of its contributors may be used to endorse or promote products derived from this Software without specific prior written permission. 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 CONTRIBUTORS 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 WITH THE SOFTWARE. */ /** * @author Michael Sheetz * @author Pavithra Koka * @author Shreeram Sridharan */ package gamess; import legacy.editor.commons.Settings; import org.w3c.dom.Document; import java.util.ArrayList; public class GlobalParameters { static String inputDocumentName= Settings.getApplicationDataDir() + "/gamess/GamessMenu.xml"; static String inputDocumentName1= Settings.getApplicationDataDir() + "/gamess/GamessIncompatibilities.xml"; static String GamessMenuNew= Settings.getApplicationDataDir() + "/gamess/GamessMenuNew.xml"; static String HelpFile = Settings.getApplicationDataDir() + "/gamess/GamessHelp.html"; static public Document doc = null; static public Document userNotesAndToolTip = null; static public boolean isProvisionalMode = false; public static void switchToProvisionalMode() { isProvisionalMode = true; } public static void switchToNormalMode() { isProvisionalMode = false; } static public UndoRedoHandler undoRedoHandle = new UndoRedoHandler(); static private StringBuilder listOfGroups = new StringBuilder("|$END|$CONTRL|$SYSTEM|$BASIS|$DATA|$ZMAT|$LIBE|$SCF|$SCFMI|$DFT|" + "$MP2|$CIS|$CISVEC|$CCINP|$EOMINP|$MOPAC|$GUESS|$VEC|$MOFRZ|$STATPT|$TRUDGE|$TRURST|$FORCE|$CPHF|$MASS|$HESS|$GRAD|" + "$DIPDR|$VIB|$VIB2|$VSCF|$VIBSCF|$IRC|$DRC|$MEX|$MD|$GLOBOP|$GRADEX|$SURF|$LOCAL|$TWOEI|$TRUNCN|$ELMOM|$ELPOT|$ELDENS|" + "$ELFLDG|$POINTS|$GRID|$PDC|$MOLGRF|$STONE|$RAMAN|$ALPDR|$NMR|$MOROKM|$FFCALC|$TDHF|$TDHFX|$EFRAG|$FRAGNAME|$FRGRPL|" + "$PRTEFP|$DAMP|$DAMPGS|$PCM|$PCMGRD|$PCMCAV|$TESCAV|$NEWCAV|$IEFPCM|$PCMITR|$DISBS|$DISREP|$SVP|$SVPIRF|$COSGMS|$SCRF|" + "$ECP|$MCP|$RELWFN|$EFIELD|$INTGRL|$FMM|$TRANS|$FMO|$FMOPRP|$FMOXYZ|$OPTFMO|$FMOLMO|$FMOBND|$FMOENM|$FMOEND|$OPTRST|" + "$GDDI|$CIINP|$DET|$CIDET|$GEN|$CIGEN|$ORMAS|$GCILST|$SODET|$DRT|$CIDRT|$MCSCF|$MRMP|$DEMRPT|$MCQDPT|$CISORT|$GUGEM|" + "$GUGDIA|$GUGDM|$GUGDM2|$LAGRAN|$TRFDM2|$TRANST|"); public static boolean isGroupAvailable(String group) { if(listOfGroups.indexOf("|" + group.toUpperCase() + "|") == -1) return false; else return true; } public static ArrayList<String> plainDataGroup = new ArrayList<String>(); public static ArrayList<String> gridGroup = new ArrayList<String>(); static { // Loading plain data group plainDataGroup.add("DATA"); plainDataGroup.add("VEC"); plainDataGroup.add("VIBSCF"); plainDataGroup.add("CISVEC"); //Loading gridGroup.add("ZMAT"); gridGroup.add("LIBE"); } }
apache-2.0
seava/seava.lib.j4e
seava.j4e.web.ctrl/src/main/java/seava/j4e/web/controller/session/SessionController.java
13574
/** * DNet eBusiness Suite * Copyright: 2013 Nan21 Electronics SRL. All rights reserved. * Use is subject to license terms. */ package seava.j4e.web.controller.session; import java.io.IOException; import java.math.BigInteger; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Calendar; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import seava.j4e.api.Constants; import seava.j4e.api.enums.DateFormatAttribute; import seava.j4e.api.security.IChangePasswordService; import seava.j4e.api.security.ILoginParams; import seava.j4e.api.security.LoginParamsHolder; import seava.j4e.api.session.ISessionUser; import seava.j4e.api.session.IUser; import seava.j4e.api.session.IUserSettings; import seava.j4e.api.session.Session; import seava.j4e.web.controller.AbstractBaseController; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.web.context.HttpSessionSecurityContextRepository; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; @RequestMapping(value = Constants.CTXPATH_SESSION) public class SessionController extends AbstractBaseController { final static Logger logger = LoggerFactory .getLogger(SessionController.class); private AuthenticationManager authenticationManager; /** * Login page view */ private String loginViewName; /** * Show login page * * @return * @throws Exception */ @RequestMapping(value = "/" + Constants.SESSION_ACTION_SHOW_LOGIN) public ModelAndView showLogin(HttpServletRequest request, HttpServletResponse response) throws Exception { // if user already authenticated redirect SecurityContext ctx = (SecurityContext) request .getSession() .getAttribute( HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY); if (ctx != null && ctx.getAuthentication() != null) { Object su = ctx.getAuthentication().getPrincipal(); if (su != null && (su instanceof ISessionUser) && (!((ISessionUser) su).isSessionLocked())) { response.sendRedirect(this.getSettings().get( Constants.PROP_CTXPATH)); return null; } } Map<String, Object> model = new HashMap<String, Object>(); model.put("loginPageCss", this.getSettings().get(Constants.PROP_LOGIN_PAGE_CSS)); model.put("loginPageLogo", this.getSettings().get(Constants.PROP_LOGIN_PAGE_LOGO)); model.put("currentYear", Calendar.getInstance().get(Calendar.YEAR) + ""); model.put("productName", this.getSettings().getProductName()); model.put("productDescription", this.getSettings() .getProductDescription()); model.put("productVersion", this.getSettings().getProductVersion()); model.put("productUrl", this.getSettings().getProductUrl()); model.put("productVendor", this.getSettings().getProductVendor()); model.put("ctxpath", this.getSettings().get(Constants.PROP_CTXPATH)); return new ModelAndView(this.loginViewName, model); } /** * Process login action * * @param username * @param password * @param clientCode * @param language * @param request * @param response * @return * @throws Exception */ @RequestMapping(value = "/" + Constants.SESSION_ACTION_LOGIN, method = RequestMethod.POST) public ModelAndView login( @RequestParam(value = "user", required = true) String username, @RequestParam(value = "pswd", required = true) String password, @RequestParam(value = "client", required = true) String clientCode, @RequestParam(value = "lang", required = false) String language, HttpServletRequest request, HttpServletResponse response) throws Exception { try { if (logger.isInfoEnabled()) { logger.info("Session request: -> login "); } if (logger.isDebugEnabled()) { logger.debug( " --> request-params: user={}, client={}, pswd=*** ", new Object[] { username, clientCode }); } request.getSession().invalidate(); request.getSession(); prepareLoginParamsHolder(clientCode, language, request); String hashedPass = getMD5Password(password); Authentication authRequest = new UsernamePasswordAuthenticationToken( username, hashedPass); Authentication authResponse = this.getAuthenticationManager() .authenticate(authRequest); SecurityContextHolder.getContext().setAuthentication(authResponse); response.sendRedirect(this.getSettings() .get(Constants.PROP_CTXPATH) + Constants.URL_UI_EXTJS); return null; } catch (Exception e) { ModelAndView err = this.showLogin(request, response); String msg = "Access denied. "; if (e.getMessage() != null && !"".equals(e.getMessage())) { msg += e.getMessage(); } err.getModel().put("error", msg); return err; } } /** * Process login action from an AJAX context * * @param username * @param password * @param clientCode * @param language * @param request * @param response * @return * @throws Exception */ @ResponseBody @RequestMapping(params = Constants.REQUEST_PARAM_ACTION + "=" + Constants.SESSION_ACTION_LOGIN) public String loginExtjs( @RequestParam(value = "user", required = true) String username, @RequestParam(value = "pswd", required = true) String password, @RequestParam(value = "client", required = true) String clientCode, @RequestParam(value = "lang", required = false) String language, HttpServletRequest request, HttpServletResponse response) throws Exception { try { if (logger.isInfoEnabled()) { logger.info("Session request: -> login "); } if (logger.isDebugEnabled()) { logger.debug( " --> request-params: user={}, client={}, pswd=*** ", new Object[] { username, clientCode }); } // TODO: copy attributes ? request.getSession().invalidate(); request.getSession(); prepareLoginParamsHolder(clientCode, language, request); String hashedPass = getMD5Password(password); Authentication authRequest = new UsernamePasswordAuthenticationToken( username, hashedPass); Authentication authResponse = this.getAuthenticationManager() .authenticate(authRequest); SecurityContextHolder.getContext().setAuthentication(authResponse); ISessionUser sessionUser = (ISessionUser) SecurityContextHolder .getContext().getAuthentication().getPrincipal(); IUser user = sessionUser.getUser(); IUserSettings prefs = user.getSettings(); StringBuffer sb = new StringBuffer(); String userRolesStr = null; sb.append(",\"extjsDateFormat\":\"" + prefs.getDateFormatMask(DateFormatAttribute.EXTJS_DATE_FORMAT .name()) + "\""); sb.append(" , \"extjsTimeFormat\": \"" + prefs.getDateFormatMask(DateFormatAttribute.EXTJS_TIME_FORMAT .name()) + "\""); sb.append(" , \"extjsDateTimeFormat\": \"" + prefs.getDateFormatMask(DateFormatAttribute.EXTJS_DATETIME_FORMAT .name()) + "\""); sb.append(" , \"extjsMonthFormat\": \"" + prefs.getDateFormatMask(DateFormatAttribute.EXTJS_MONTH_FORMAT .name()) + "\""); sb.append(" , \"extjsAltFormats\": \"" + prefs.getDateFormatMask(DateFormatAttribute.EXTJS_ALT_FORMATS .name()) + "\""); sb.append(" , \"decimalSeparator\": \"" + prefs.getDecimalSeparator() + "\""); sb.append(" , \"thousandSeparator\": \"" + prefs.getThousandSeparator() + "\""); StringBuffer sbroles = new StringBuffer(); int i = 0; for (String role : user.getProfile().getRoles()) { if (i > 0) { sbroles.append(","); } sbroles.append("\"" + role + "\""); i++; } userRolesStr = sbroles.toString(); sb.append(" , \"roles\": [" + userRolesStr + "]"); request.getSession() .setAttribute( HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, SecurityContextHolder.getContext()); String clientId = user.getClient().getId(); if (clientId == null) { clientId = ""; } return "{ \"success\": true , \"data\": {\"code\":\"" + user.getCode() + "\", \"name\":\"" + user.getName() + "\",\"loginName\":\"" + user.getLoginName() + "\", \"clientId\":\"" + clientId + "\" } }"; } catch (Exception e) { return this.handleException(e, response); } } @ResponseBody @RequestMapping(value = "/" + Constants.SESSION_ACTION_LOGOUT) public String logout(HttpServletRequest request, HttpServletResponse response) throws Exception { if (logger.isInfoEnabled()) { logger.info("Session request: -> logout "); } SecurityContextHolder.getContext().setAuthentication(null); request.getSession().invalidate(); return ""; } @ResponseBody @RequestMapping(value = "/" + Constants.SESSION_ACTION_LOCK) public String lock(HttpServletRequest request, HttpServletResponse response) throws Exception { if (logger.isInfoEnabled()) { logger.info("Session request: -> lock "); } ISessionUser sessionUser = (ISessionUser) SecurityContextHolder .getContext().getAuthentication().getPrincipal(); sessionUser.lockSession(); return ""; } /** * Change current user password. * * @param oldPassword * @param newPassword * @param request * @param response * @return * @throws Exception */ @ResponseBody @RequestMapping(method = RequestMethod.POST, params = Constants.REQUEST_PARAM_ACTION + "=" + Constants.SESSION_ACTION_CHANGEPASSWORD) public String changePassword( @RequestParam(value = "opswd", required = true) String oldPassword, @RequestParam(value = "npswd", required = true) String newPassword, HttpServletRequest request, HttpServletResponse response) throws Exception { try { if (logger.isInfoEnabled()) { logger.info("Session request: -> changePassword "); } if (logger.isDebugEnabled()) { logger.debug(" --> request-params: opswd=***, npswd=*** "); } SecurityContext ctx = (SecurityContext) request .getSession() .getAttribute( HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY); if (ctx == null || ctx.getAuthentication() == null) { throw new Exception("Not authenticated"); } IUser user = ((ISessionUser) ctx.getAuthentication().getPrincipal()) .getUser(); Session.user.set(user); // ------------------------------------------------- if (user.isSystemUser()) { throw new Exception( "The password of a system-user cannot be changed from the application."); } IChangePasswordService service = this.getApplicationContext() .getBean(IChangePasswordService.class); service.doChangePassword(user.getCode(), newPassword, oldPassword, user.getClient().getId(), user.getClient().getCode()); return "{success: true}"; } catch (Exception e) { return this.handleException(e, response); } finally { this.finishRequest(); } } /** * Pack extra information about login into a ThreadLocal to be passed to the * authentication-provider service * * @param clientCode * @param language * @param request */ private void prepareLoginParamsHolder(String clientCode, String language, HttpServletRequest request) { ILoginParams lp = this.getApplicationContext().getBean( ILoginParams.class); String ip = request.getHeader("X-Forwarded-For"); if (ip != null && !"".equals(ip)) { ip = ip.substring(0, ip.indexOf(",")); } else { ip = request.getRemoteAddr(); } lp.setRemoteIp(ip); lp.setUserAgent(request.getHeader("User-Agent")); lp.setRemoteHost(request.getRemoteHost()); lp.setLanguage(language); lp.setClientCode(clientCode); LoginParamsHolder.params.set(lp); } /** * Generic exception handler */ protected String handleException(Exception e, HttpServletResponse response) throws IOException { response.setStatus(403); return e.getLocalizedMessage(); } /** * Helper function to return a MD5 encryption of the given string * * @param thePassword * @return * @throws NoSuchAlgorithmException */ protected String getMD5Password(String thePassword) throws NoSuchAlgorithmException { MessageDigest messageDigest = MessageDigest.getInstance("MD5"); messageDigest.update(thePassword.getBytes(), 0, thePassword.length()); String hashedPass = new BigInteger(1, messageDigest.digest()) .toString(16); if (hashedPass.length() < 32) { hashedPass = "0" + hashedPass; } return hashedPass; } public AuthenticationManager getAuthenticationManager() { if (this.authenticationManager == null) { this.authenticationManager = this.getApplicationContext().getBean( Constants.SPRING_AUTH_MANAGER, AuthenticationManager.class); } return authenticationManager; } public void setAuthenticationManager( AuthenticationManager authenticationManager) { this.authenticationManager = authenticationManager; } public String getLoginViewName() { return loginViewName; } public void setLoginViewName(String loginViewName) { this.loginViewName = loginViewName; } }
apache-2.0
spariev/snakeyaml
src/test/java/org/yaml/snakeyaml/scanner/SimpleKeyTest.java
913
/** * Copyright (c) 2008-2010 Andrey Somov * * 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.yaml.snakeyaml.scanner; import junit.framework.TestCase; public class SimpleKeyTest extends TestCase { public void testToString() { SimpleKey key = new SimpleKey(1, false, 5, 3, 2, null); assertTrue(key.toString().contains("SimpleKey")); } }
apache-2.0
ToureNPlaner/tourenplaner-server
src/main/java/de/tourenplaner/computecore/ComputeThread.java
3821
/* * Copyright 2012 ToureNPlaner * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.tourenplaner.computecore; import de.tourenplaner.algorithms.Algorithm; import de.tourenplaner.algorithms.ComputeException; import de.tourenplaner.computeserver.ErrorMessage; import io.netty.handler.codec.http.HttpResponseStatus; import java.util.concurrent.BlockingQueue; import java.util.logging.Level; import java.util.logging.Logger; /** * A ComputeThread computes the results of ComputeRequests it gets from the * queue of it's associated ComputeCore using Algorithms known to it's * AlgorithmManager * * @author Christoph Haag, Sascha Meusel, Niklas Schnelle, Peter Vollmer */ public class ComputeThread extends Thread { private static Logger log = Logger.getLogger("de.tourenplaner.computecore"); private final AlgorithmManager alm; private final BlockingQueue<ComputeRequest> reqQueue; /** * Constructs a new ComputeThread using the given AlgorithmManager and * RequestQueue * * @param am AlgorithmManager * @param rq BlockingQueue&lt;ComputeRequest&gt; */ public ComputeThread(AlgorithmManager am, BlockingQueue<ComputeRequest> rq) { alm = am; reqQueue = rq; this.setDaemon(true); } /** * Runs computations taking new ones from the Queue */ @Override public void run() { ComputeRequest work; Algorithm alg; while (!Thread.interrupted()) { try { work = reqQueue.take(); // check needed if availability of algorithms changes alg = alm.getAlgByURLSuffix(work.getRequestData().getAlgorithmURLSuffix()); if (alg != null) { try { alg.compute(work); log.finer("Algorithm " + work.getRequestData().getAlgorithmURLSuffix() + " successfully computed."); // IOException will be handled as EINTERNAL work.getResponder().writeComputeResult(work, HttpResponseStatus.OK); } catch (ComputeException e) { log.log(Level.WARNING, "There was a ComputeException", e); String errorMessage = work.getResponder().writeAndReturnErrorMessage(ErrorMessage.ECOMPUTE, e.getMessage()); } catch (Exception e) { log.log(Level.WARNING, "Internal server exception (caused by algorithm or result writing)", e); // Don't give too much info to client as we probably got a programming mistake work.getResponder().writeErrorMessage(ErrorMessage.EINTERNAL_UNSPECIFIED); } } else { log.warning("Unsupported algorithm " + work.getRequestData().getAlgorithmURLSuffix() + " requested"); work.getResponder().writeErrorMessage(ErrorMessage.EUNKNOWNALG); } } catch (InterruptedException e) { log.warning("ComputeThread interrupted"); return; } catch (Exception e) { log.log(Level.WARNING, "An exception occurred, keep on going", e); } } } }
apache-2.0
ox-it/cucm-http-api
src/main/java/com/cisco/axl/api/_8/UpdateDeviceProfileReq.java
37154
package com.cisco.axl.api._8; import java.util.ArrayList; import java.util.List; import javax.xml.bind.JAXBElement; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementRef; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for UpdateDeviceProfileReq complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="UpdateDeviceProfileReq"> * &lt;complexContent> * &lt;extension base="{http://www.cisco.com/AXL/API/8.0}NameAndGUIDRequest"> * &lt;sequence> * &lt;element name="newName" type="{http://www.cisco.com/AXL/API/8.0}UniqueString128" minOccurs="0"/> * &lt;element name="description" type="{http://www.cisco.com/AXL/API/8.0}String128" minOccurs="0"/> * &lt;element name="userHoldMohAudioSourceId" type="{http://www.cisco.com/AXL/API/8.0}XMOHAudioSourceId" minOccurs="0"/> * &lt;element name="vendorConfig" type="{http://www.cisco.com/AXL/API/8.0}XVendorConfig" minOccurs="0"/> * &lt;element name="mlppDomainId" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/> * &lt;element name="mlppIndicationStatus" type="{http://www.cisco.com/AXL/API/8.0}XStatus" minOccurs="0"/> * &lt;element name="preemption" type="{http://www.cisco.com/AXL/API/8.0}XPreemption" minOccurs="0"/> * &lt;element name="lines" minOccurs="0"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;choice> * &lt;element name="line" type="{http://www.cisco.com/AXL/API/8.0}XPhoneLine" maxOccurs="unbounded"/> * &lt;element name="lineIdentifier" type="{http://www.cisco.com/AXL/API/8.0}XNumplanIdentifier" maxOccurs="unbounded"/> * &lt;/choice> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;element name="phoneTemplateName" type="{http://www.cisco.com/AXL/API/8.0}XFkType" minOccurs="0"/> * &lt;element name="speeddials" minOccurs="0"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence minOccurs="0"> * &lt;element name="speeddial" type="{http://www.cisco.com/AXL/API/8.0}XSpeeddial" maxOccurs="unbounded" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;element name="busyLampFields" minOccurs="0"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence minOccurs="0"> * &lt;element name="busyLampField" type="{http://www.cisco.com/AXL/API/8.0}XBusyLampField" maxOccurs="unbounded" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;element name="blfDirectedCallParks" minOccurs="0"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence minOccurs="0"> * &lt;element name="blfDirectedCallPark" type="{http://www.cisco.com/AXL/API/8.0}XBLFDirectedCallPark" maxOccurs="unbounded" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;element name="addOnModules" minOccurs="0"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence minOccurs="0"> * &lt;element name="addOnModule" type="{http://www.cisco.com/AXL/API/8.0}XAddOnModule" maxOccurs="2" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;element name="userlocale" type="{http://www.cisco.com/AXL/API/8.0}XUserLocale" minOccurs="0"/> * &lt;element name="singleButtonBarge" type="{http://www.cisco.com/AXL/API/8.0}XBarge" minOccurs="0"/> * &lt;element name="joinAcrossLines" type="{http://www.cisco.com/AXL/API/8.0}XStatus" minOccurs="0"/> * &lt;element name="loginUserId" type="{http://www.cisco.com/AXL/API/8.0}XFkType" minOccurs="0"/> * &lt;element name="ignorePresentationIndicators" type="{http://www.cisco.com/AXL/API/8.0}boolean" minOccurs="0"/> * &lt;element name="dndOption" type="{http://www.cisco.com/AXL/API/8.0}XDNDOption" minOccurs="0"/> * &lt;element name="dndRingSetting" type="{http://www.cisco.com/AXL/API/8.0}XRingSetting" minOccurs="0"/> * &lt;element name="dndStatus" type="{http://www.cisco.com/AXL/API/8.0}boolean" minOccurs="0"/> * &lt;element name="emccCallingSearchSpace" type="{http://www.cisco.com/AXL/API/8.0}XFkType" minOccurs="0"/> * &lt;element name="alwaysUsePrimeLine" type="{http://www.cisco.com/AXL/API/8.0}XStatus" minOccurs="0"/> * &lt;element name="alwaysUsePrimeLineForVoiceMessage" type="{http://www.cisco.com/AXL/API/8.0}XStatus" minOccurs="0"/> * &lt;element name="softkeyTemplateName" type="{http://www.cisco.com/AXL/API/8.0}XFkType" minOccurs="0"/> * &lt;element name="callInfoPrivacyStatus" type="{http://www.cisco.com/AXL/API/8.0}XStatus" minOccurs="0"/> * &lt;element name="services" minOccurs="0"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence minOccurs="0"> * &lt;element name="service" type="{http://www.cisco.com/AXL/API/8.0}XSubscribedService" maxOccurs="unbounded" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "UpdateDeviceProfileReq", propOrder = { "newName", "description", "userHoldMohAudioSourceId", "vendorConfig", "mlppDomainId", "mlppIndicationStatus", "preemption", "lines", "phoneTemplateName", "speeddials", "busyLampFields", "blfDirectedCallParks", "addOnModules", "userlocale", "singleButtonBarge", "joinAcrossLines", "loginUserId", "ignorePresentationIndicators", "dndOption", "dndRingSetting", "dndStatus", "emccCallingSearchSpace", "alwaysUsePrimeLine", "alwaysUsePrimeLineForVoiceMessage", "softkeyTemplateName", "callInfoPrivacyStatus", "services" }) public class UpdateDeviceProfileReq extends NameAndGUIDRequest { protected String newName; protected String description; @XmlElementRef(name = "userHoldMohAudioSourceId", type = JAXBElement.class) protected JAXBElement<String> userHoldMohAudioSourceId; protected XVendorConfig vendorConfig; @XmlElementRef(name = "mlppDomainId", type = JAXBElement.class) protected JAXBElement<Integer> mlppDomainId; @XmlElement(defaultValue = "Off") protected String mlppIndicationStatus; @XmlElement(defaultValue = "Default") protected String preemption; protected UpdateDeviceProfileReq.Lines lines; @XmlElementRef(name = "phoneTemplateName", type = JAXBElement.class) protected JAXBElement<XFkType> phoneTemplateName; protected UpdateDeviceProfileReq.Speeddials speeddials; protected UpdateDeviceProfileReq.BusyLampFields busyLampFields; protected UpdateDeviceProfileReq.BlfDirectedCallParks blfDirectedCallParks; protected UpdateDeviceProfileReq.AddOnModules addOnModules; @XmlElementRef(name = "userlocale", type = JAXBElement.class) protected JAXBElement<String> userlocale; @XmlElement(defaultValue = "Default") protected String singleButtonBarge; @XmlElement(defaultValue = "Default") protected String joinAcrossLines; @XmlElementRef(name = "loginUserId", type = JAXBElement.class) protected JAXBElement<XFkType> loginUserId; @XmlElement(defaultValue = "false") protected String ignorePresentationIndicators; @XmlElement(defaultValue = "Ringer Off") protected String dndOption; @XmlElementRef(name = "dndRingSetting", type = JAXBElement.class) protected JAXBElement<String> dndRingSetting; protected String dndStatus; @XmlElementRef(name = "emccCallingSearchSpace", type = JAXBElement.class) protected JAXBElement<XFkType> emccCallingSearchSpace; @XmlElement(defaultValue = "Default") protected String alwaysUsePrimeLine; @XmlElement(defaultValue = "Default") protected String alwaysUsePrimeLineForVoiceMessage; @XmlElementRef(name = "softkeyTemplateName", type = JAXBElement.class) protected JAXBElement<XFkType> softkeyTemplateName; @XmlElement(defaultValue = "Default") protected String callInfoPrivacyStatus; protected UpdateDeviceProfileReq.Services services; /** * Gets the value of the newName property. * * @return * possible object is * {@link String } * */ public String getNewName() { return newName; } /** * Sets the value of the newName property. * * @param value * allowed object is * {@link String } * */ public void setNewName(String value) { this.newName = value; } /** * Gets the value of the description property. * * @return * possible object is * {@link String } * */ public String getDescription() { return description; } /** * Sets the value of the description property. * * @param value * allowed object is * {@link String } * */ public void setDescription(String value) { this.description = value; } /** * Gets the value of the userHoldMohAudioSourceId property. * * @return * possible object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public JAXBElement<String> getUserHoldMohAudioSourceId() { return userHoldMohAudioSourceId; } /** * Sets the value of the userHoldMohAudioSourceId property. * * @param value * allowed object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public void setUserHoldMohAudioSourceId(JAXBElement<String> value) { this.userHoldMohAudioSourceId = ((JAXBElement<String> ) value); } /** * Gets the value of the vendorConfig property. * * @return * possible object is * {@link XVendorConfig } * */ public XVendorConfig getVendorConfig() { return vendorConfig; } /** * Sets the value of the vendorConfig property. * * @param value * allowed object is * {@link XVendorConfig } * */ public void setVendorConfig(XVendorConfig value) { this.vendorConfig = value; } /** * Gets the value of the mlppDomainId property. * * @return * possible object is * {@link JAXBElement }{@code <}{@link Integer }{@code >} * */ public JAXBElement<Integer> getMlppDomainId() { return mlppDomainId; } /** * Sets the value of the mlppDomainId property. * * @param value * allowed object is * {@link JAXBElement }{@code <}{@link Integer }{@code >} * */ public void setMlppDomainId(JAXBElement<Integer> value) { this.mlppDomainId = ((JAXBElement<Integer> ) value); } /** * Gets the value of the mlppIndicationStatus property. * * @return * possible object is * {@link String } * */ public String getMlppIndicationStatus() { return mlppIndicationStatus; } /** * Sets the value of the mlppIndicationStatus property. * * @param value * allowed object is * {@link String } * */ public void setMlppIndicationStatus(String value) { this.mlppIndicationStatus = value; } /** * Gets the value of the preemption property. * * @return * possible object is * {@link String } * */ public String getPreemption() { return preemption; } /** * Sets the value of the preemption property. * * @param value * allowed object is * {@link String } * */ public void setPreemption(String value) { this.preemption = value; } /** * Gets the value of the lines property. * * @return * possible object is * {@link UpdateDeviceProfileReq.Lines } * */ public UpdateDeviceProfileReq.Lines getLines() { return lines; } /** * Sets the value of the lines property. * * @param value * allowed object is * {@link UpdateDeviceProfileReq.Lines } * */ public void setLines(UpdateDeviceProfileReq.Lines value) { this.lines = value; } /** * Gets the value of the phoneTemplateName property. * * @return * possible object is * {@link JAXBElement }{@code <}{@link XFkType }{@code >} * */ public JAXBElement<XFkType> getPhoneTemplateName() { return phoneTemplateName; } /** * Sets the value of the phoneTemplateName property. * * @param value * allowed object is * {@link JAXBElement }{@code <}{@link XFkType }{@code >} * */ public void setPhoneTemplateName(JAXBElement<XFkType> value) { this.phoneTemplateName = ((JAXBElement<XFkType> ) value); } /** * Gets the value of the speeddials property. * * @return * possible object is * {@link UpdateDeviceProfileReq.Speeddials } * */ public UpdateDeviceProfileReq.Speeddials getSpeeddials() { return speeddials; } /** * Sets the value of the speeddials property. * * @param value * allowed object is * {@link UpdateDeviceProfileReq.Speeddials } * */ public void setSpeeddials(UpdateDeviceProfileReq.Speeddials value) { this.speeddials = value; } /** * Gets the value of the busyLampFields property. * * @return * possible object is * {@link UpdateDeviceProfileReq.BusyLampFields } * */ public UpdateDeviceProfileReq.BusyLampFields getBusyLampFields() { return busyLampFields; } /** * Sets the value of the busyLampFields property. * * @param value * allowed object is * {@link UpdateDeviceProfileReq.BusyLampFields } * */ public void setBusyLampFields(UpdateDeviceProfileReq.BusyLampFields value) { this.busyLampFields = value; } /** * Gets the value of the blfDirectedCallParks property. * * @return * possible object is * {@link UpdateDeviceProfileReq.BlfDirectedCallParks } * */ public UpdateDeviceProfileReq.BlfDirectedCallParks getBlfDirectedCallParks() { return blfDirectedCallParks; } /** * Sets the value of the blfDirectedCallParks property. * * @param value * allowed object is * {@link UpdateDeviceProfileReq.BlfDirectedCallParks } * */ public void setBlfDirectedCallParks(UpdateDeviceProfileReq.BlfDirectedCallParks value) { this.blfDirectedCallParks = value; } /** * Gets the value of the addOnModules property. * * @return * possible object is * {@link UpdateDeviceProfileReq.AddOnModules } * */ public UpdateDeviceProfileReq.AddOnModules getAddOnModules() { return addOnModules; } /** * Sets the value of the addOnModules property. * * @param value * allowed object is * {@link UpdateDeviceProfileReq.AddOnModules } * */ public void setAddOnModules(UpdateDeviceProfileReq.AddOnModules value) { this.addOnModules = value; } /** * Gets the value of the userlocale property. * * @return * possible object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public JAXBElement<String> getUserlocale() { return userlocale; } /** * Sets the value of the userlocale property. * * @param value * allowed object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public void setUserlocale(JAXBElement<String> value) { this.userlocale = ((JAXBElement<String> ) value); } /** * Gets the value of the singleButtonBarge property. * * @return * possible object is * {@link String } * */ public String getSingleButtonBarge() { return singleButtonBarge; } /** * Sets the value of the singleButtonBarge property. * * @param value * allowed object is * {@link String } * */ public void setSingleButtonBarge(String value) { this.singleButtonBarge = value; } /** * Gets the value of the joinAcrossLines property. * * @return * possible object is * {@link String } * */ public String getJoinAcrossLines() { return joinAcrossLines; } /** * Sets the value of the joinAcrossLines property. * * @param value * allowed object is * {@link String } * */ public void setJoinAcrossLines(String value) { this.joinAcrossLines = value; } /** * Gets the value of the loginUserId property. * * @return * possible object is * {@link JAXBElement }{@code <}{@link XFkType }{@code >} * */ public JAXBElement<XFkType> getLoginUserId() { return loginUserId; } /** * Sets the value of the loginUserId property. * * @param value * allowed object is * {@link JAXBElement }{@code <}{@link XFkType }{@code >} * */ public void setLoginUserId(JAXBElement<XFkType> value) { this.loginUserId = ((JAXBElement<XFkType> ) value); } /** * Gets the value of the ignorePresentationIndicators property. * * @return * possible object is * {@link String } * */ public String getIgnorePresentationIndicators() { return ignorePresentationIndicators; } /** * Sets the value of the ignorePresentationIndicators property. * * @param value * allowed object is * {@link String } * */ public void setIgnorePresentationIndicators(String value) { this.ignorePresentationIndicators = value; } /** * Gets the value of the dndOption property. * * @return * possible object is * {@link String } * */ public String getDndOption() { return dndOption; } /** * Sets the value of the dndOption property. * * @param value * allowed object is * {@link String } * */ public void setDndOption(String value) { this.dndOption = value; } /** * Gets the value of the dndRingSetting property. * * @return * possible object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public JAXBElement<String> getDndRingSetting() { return dndRingSetting; } /** * Sets the value of the dndRingSetting property. * * @param value * allowed object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public void setDndRingSetting(JAXBElement<String> value) { this.dndRingSetting = ((JAXBElement<String> ) value); } /** * Gets the value of the dndStatus property. * * @return * possible object is * {@link String } * */ public String getDndStatus() { return dndStatus; } /** * Sets the value of the dndStatus property. * * @param value * allowed object is * {@link String } * */ public void setDndStatus(String value) { this.dndStatus = value; } /** * Gets the value of the emccCallingSearchSpace property. * * @return * possible object is * {@link JAXBElement }{@code <}{@link XFkType }{@code >} * */ public JAXBElement<XFkType> getEmccCallingSearchSpace() { return emccCallingSearchSpace; } /** * Sets the value of the emccCallingSearchSpace property. * * @param value * allowed object is * {@link JAXBElement }{@code <}{@link XFkType }{@code >} * */ public void setEmccCallingSearchSpace(JAXBElement<XFkType> value) { this.emccCallingSearchSpace = ((JAXBElement<XFkType> ) value); } /** * Gets the value of the alwaysUsePrimeLine property. * * @return * possible object is * {@link String } * */ public String getAlwaysUsePrimeLine() { return alwaysUsePrimeLine; } /** * Sets the value of the alwaysUsePrimeLine property. * * @param value * allowed object is * {@link String } * */ public void setAlwaysUsePrimeLine(String value) { this.alwaysUsePrimeLine = value; } /** * Gets the value of the alwaysUsePrimeLineForVoiceMessage property. * * @return * possible object is * {@link String } * */ public String getAlwaysUsePrimeLineForVoiceMessage() { return alwaysUsePrimeLineForVoiceMessage; } /** * Sets the value of the alwaysUsePrimeLineForVoiceMessage property. * * @param value * allowed object is * {@link String } * */ public void setAlwaysUsePrimeLineForVoiceMessage(String value) { this.alwaysUsePrimeLineForVoiceMessage = value; } /** * Gets the value of the softkeyTemplateName property. * * @return * possible object is * {@link JAXBElement }{@code <}{@link XFkType }{@code >} * */ public JAXBElement<XFkType> getSoftkeyTemplateName() { return softkeyTemplateName; } /** * Sets the value of the softkeyTemplateName property. * * @param value * allowed object is * {@link JAXBElement }{@code <}{@link XFkType }{@code >} * */ public void setSoftkeyTemplateName(JAXBElement<XFkType> value) { this.softkeyTemplateName = ((JAXBElement<XFkType> ) value); } /** * Gets the value of the callInfoPrivacyStatus property. * * @return * possible object is * {@link String } * */ public String getCallInfoPrivacyStatus() { return callInfoPrivacyStatus; } /** * Sets the value of the callInfoPrivacyStatus property. * * @param value * allowed object is * {@link String } * */ public void setCallInfoPrivacyStatus(String value) { this.callInfoPrivacyStatus = value; } /** * Gets the value of the services property. * * @return * possible object is * {@link UpdateDeviceProfileReq.Services } * */ public UpdateDeviceProfileReq.Services getServices() { return services; } /** * Sets the value of the services property. * * @param value * allowed object is * {@link UpdateDeviceProfileReq.Services } * */ public void setServices(UpdateDeviceProfileReq.Services value) { this.services = value; } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence minOccurs="0"> * &lt;element name="addOnModule" type="{http://www.cisco.com/AXL/API/8.0}XAddOnModule" maxOccurs="2" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "addOnModule" }) public static class AddOnModules { protected List<XAddOnModule> addOnModule; /** * Gets the value of the addOnModule property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the addOnModule property. * * <p> * For example, to add a new item, do as follows: * <pre> * getAddOnModule().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link XAddOnModule } * * */ public List<XAddOnModule> getAddOnModule() { if (addOnModule == null) { addOnModule = new ArrayList<XAddOnModule>(); } return this.addOnModule; } } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence minOccurs="0"> * &lt;element name="blfDirectedCallPark" type="{http://www.cisco.com/AXL/API/8.0}XBLFDirectedCallPark" maxOccurs="unbounded" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "blfDirectedCallPark" }) public static class BlfDirectedCallParks { protected List<XBLFDirectedCallPark> blfDirectedCallPark; /** * Gets the value of the blfDirectedCallPark property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the blfDirectedCallPark property. * * <p> * For example, to add a new item, do as follows: * <pre> * getBlfDirectedCallPark().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link XBLFDirectedCallPark } * * */ public List<XBLFDirectedCallPark> getBlfDirectedCallPark() { if (blfDirectedCallPark == null) { blfDirectedCallPark = new ArrayList<XBLFDirectedCallPark>(); } return this.blfDirectedCallPark; } } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence minOccurs="0"> * &lt;element name="busyLampField" type="{http://www.cisco.com/AXL/API/8.0}XBusyLampField" maxOccurs="unbounded" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "busyLampField" }) public static class BusyLampFields { protected List<XBusyLampField> busyLampField; /** * Gets the value of the busyLampField property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the busyLampField property. * * <p> * For example, to add a new item, do as follows: * <pre> * getBusyLampField().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link XBusyLampField } * * */ public List<XBusyLampField> getBusyLampField() { if (busyLampField == null) { busyLampField = new ArrayList<XBusyLampField>(); } return this.busyLampField; } } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;choice> * &lt;element name="line" type="{http://www.cisco.com/AXL/API/8.0}XPhoneLine" maxOccurs="unbounded"/> * &lt;element name="lineIdentifier" type="{http://www.cisco.com/AXL/API/8.0}XNumplanIdentifier" maxOccurs="unbounded"/> * &lt;/choice> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "line", "lineIdentifier" }) public static class Lines { protected List<XPhoneLine> line; protected List<XNumplanIdentifier> lineIdentifier; /** * Gets the value of the line property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the line property. * * <p> * For example, to add a new item, do as follows: * <pre> * getLine().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link XPhoneLine } * * */ public List<XPhoneLine> getLine() { if (line == null) { line = new ArrayList<XPhoneLine>(); } return this.line; } /** * Gets the value of the lineIdentifier property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the lineIdentifier property. * * <p> * For example, to add a new item, do as follows: * <pre> * getLineIdentifier().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link XNumplanIdentifier } * * */ public List<XNumplanIdentifier> getLineIdentifier() { if (lineIdentifier == null) { lineIdentifier = new ArrayList<XNumplanIdentifier>(); } return this.lineIdentifier; } } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence minOccurs="0"> * &lt;element name="service" type="{http://www.cisco.com/AXL/API/8.0}XSubscribedService" maxOccurs="unbounded" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "service" }) public static class Services { protected List<XSubscribedService> service; /** * Gets the value of the service property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the service property. * * <p> * For example, to add a new item, do as follows: * <pre> * getService().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link XSubscribedService } * * */ public List<XSubscribedService> getService() { if (service == null) { service = new ArrayList<XSubscribedService>(); } return this.service; } } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence minOccurs="0"> * &lt;element name="speeddial" type="{http://www.cisco.com/AXL/API/8.0}XSpeeddial" maxOccurs="unbounded" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "speeddial" }) public static class Speeddials { protected List<XSpeeddial> speeddial; /** * Gets the value of the speeddial property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the speeddial property. * * <p> * For example, to add a new item, do as follows: * <pre> * getSpeeddial().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link XSpeeddial } * * */ public List<XSpeeddial> getSpeeddial() { if (speeddial == null) { speeddial = new ArrayList<XSpeeddial>(); } return this.speeddial; } } }
apache-2.0
sudosurootdev/SeriesGuide
SeriesGuide/src/main/java/com/battlelancer/seriesguide/appwidget/ListWidgetProvider.java
8600
/* * Copyright 2014 Uwe Trottmann * * 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.battlelancer.seriesguide.appwidget; import com.battlelancer.seriesguide.settings.WidgetSettings; import com.battlelancer.seriesguide.ui.EpisodesActivity; import com.battlelancer.seriesguide.ui.ShowsActivity; import com.uwetrottmann.androidutils.AndroidUtils; import com.battlelancer.seriesguide.R; import android.annotation.TargetApi; import android.app.AlarmManager; import android.app.PendingIntent; import android.appwidget.AppWidgetManager; import android.appwidget.AppWidgetProvider; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.SystemClock; import android.support.v4.app.TaskStackBuilder; import android.text.format.DateUtils; import android.widget.RemoteViews; @TargetApi(11) public class ListWidgetProvider extends AppWidgetProvider { public static final String UPDATE = "com.battlelancer.seriesguide.appwidget.UPDATE"; public static final long REPETITION_INTERVAL = 5 * DateUtils.MINUTE_IN_MILLIS; private static final int DIP_THRESHOLD_COMPACT_LAYOUT = 80; @Override public void onDisabled(Context context) { super.onDisabled(context); // remove the update alarm if the last widget is gone Intent update = new Intent(UPDATE); PendingIntent pi = PendingIntent.getBroadcast(context, 195, update, 0); AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); am.cancel(pi); } @Override public void onReceive(Context context, Intent intent) { super.onReceive(context, intent); // check if we received our update alarm if (UPDATE.equals(intent.getAction())) { // trigger refresh of list widgets AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context); int[] appWidgetIds = appWidgetManager.getAppWidgetIds(new ComponentName(context, ListWidgetProvider.class)); appWidgetManager.notifyAppWidgetViewDataChanged(appWidgetIds, R.id.list_view); } } @Override public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { super.onUpdate(context, appWidgetManager, appWidgetIds); // update all added list widgets for (int appWidgetId : appWidgetIds) { onAppWidgetOptionsChanged(context, appWidgetManager, appWidgetId, null); } // set an alarm to update widgets every x mins if the device is awake Intent update = new Intent(UPDATE); PendingIntent pi = PendingIntent.getBroadcast(context, 195, update, 0); AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); am.setRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + REPETITION_INTERVAL, REPETITION_INTERVAL, pi); } @Override public void onAppWidgetOptionsChanged(Context context, AppWidgetManager appWidgetManager, int appWidgetId, Bundle newOptions) { RemoteViews rv = buildRemoteViews(context, appWidgetManager, appWidgetId); appWidgetManager.updateAppWidget(appWidgetId, rv); } @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) public static RemoteViews buildRemoteViews(Context context, AppWidgetManager appWidgetManager, int appWidgetId) { // determine layout based on given size final boolean isCompactLayout = isCompactLayout(appWidgetManager, appWidgetId); // determine content type from widget settings final int typeIndex = WidgetSettings.getWidgetListType(context, appWidgetId); // Here we setup the intent which points to the StackViewService // which will provide the views for this collection. Intent intent = new Intent(context, ListWidgetService.class); intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId); // When intents are compared, the extras are ignored, so we need to // embed the extras into the data so that the extras will not be // ignored. intent.setData(Uri.parse(intent.toUri(Intent.URI_INTENT_SCHEME))); RemoteViews rv = new RemoteViews(context.getPackageName(), isCompactLayout ? R.layout.appwidget_v11_compact : R.layout.appwidget_v11); if (AndroidUtils.isICSOrHigher()) { rv.setRemoteAdapter(R.id.list_view, intent); } else { rv.setRemoteAdapter(appWidgetId, R.id.list_view, intent); } // The empty view is displayed when the collection has no items. It // should be a sibling of the collection view. rv.setEmptyView(R.id.list_view, R.id.empty_view); // set the background color int bgColor = WidgetSettings.getWidgetBackgroundColor(context, appWidgetId); rv.setInt(R.id.container, "setBackgroundColor", bgColor); // determine the tab touching the widget title should open int tabIndex; if (typeIndex == WidgetSettings.Type.UPCOMING) { tabIndex = ShowsActivity.InitBundle.INDEX_TAB_UPCOMING; } else if (typeIndex == WidgetSettings.Type.RECENT) { tabIndex = ShowsActivity.InitBundle.INDEX_TAB_RECENT; } else { tabIndex = ShowsActivity.InitBundle.INDEX_TAB_SHOWS; } // only regular layout has text title if (!isCompactLayout) { // change title based on config if (typeIndex == WidgetSettings.Type.RECENT) { rv.setTextViewText(R.id.widgetTitle, context.getString(R.string.recent)); } else if (typeIndex == WidgetSettings.Type.FAVORITES) { rv.setTextViewText(R.id.widgetTitle, context.getString(R.string.action_shows_filter_favorites)); } else { rv.setTextViewText(R.id.widgetTitle, context.getString(R.string.upcoming)); } } // app launch button final Intent appLaunchIntent = new Intent(context, ShowsActivity.class) .putExtra(ShowsActivity.InitBundle.SELECTED_TAB, tabIndex); PendingIntent pendingIntent = TaskStackBuilder.create(context) .addNextIntent(appLaunchIntent) .getPendingIntent(appWidgetId, PendingIntent.FLAG_UPDATE_CURRENT); rv.setOnClickPendingIntent(R.id.widget_title, pendingIntent); // item intent template, launches episode detail view TaskStackBuilder builder = TaskStackBuilder.create(context); builder.addNextIntent(appLaunchIntent); builder.addNextIntent(new Intent(context, EpisodesActivity.class)); rv.setPendingIntentTemplate(R.id.list_view, builder.getPendingIntent(1, PendingIntent.FLAG_UPDATE_CURRENT)); // settings button Intent settingsIntent = new Intent(context, ListWidgetConfigure.class) .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) .putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId); rv.setOnClickPendingIntent(R.id.widget_settings, PendingIntent.getActivity(context, appWidgetId, settingsIntent, PendingIntent.FLAG_UPDATE_CURRENT)); return rv; } /** * Based on the widget size determines whether to use a compact layout. Defaults to false on ICS * and below. */ @TargetApi(Build.VERSION_CODES.JELLY_BEAN) private static boolean isCompactLayout(AppWidgetManager appWidgetManager, int appWidgetId) { if (AndroidUtils.isJellyBeanOrHigher()) { Bundle options = appWidgetManager.getAppWidgetOptions(appWidgetId); int minHeight = options.getInt(AppWidgetManager.OPTION_APPWIDGET_MIN_HEIGHT); return minHeight < DIP_THRESHOLD_COMPACT_LAYOUT; } return false; } }
apache-2.0
cmacnaug/meshkeeper
meshkeeper-api/src/main/java/org/fusesource/meshkeeper/MeshArtifactFilter.java
132
package org.fusesource.meshkeeper; public interface MeshArtifactFilter { public boolean include(MeshArtifact artifact); }
apache-2.0
debop/hibernate-redis
hibernate-examples/src/test/java/org/hibernate/examples/mapping/associations/onetomany/map/OneToManyCarOption.java
1072
package org.hibernate.examples.mapping.associations.onetomany.map; import lombok.Getter; import lombok.Setter; import org.hibernate.examples.model.AbstractValueObject; import org.hibernate.examples.utils.HashTool; import org.hibernate.examples.utils.ToStringHelper; import javax.persistence.Embeddable; /** * org.hibernate.examples.mapping.associations.onetomany.map.OneToManyCarOption * * @author 배성혁 sunghyouk.bae@gmail.com * @since 2013. 11. 29. 오후 1:25 */ @Embeddable @Getter @Setter public class OneToManyCarOption extends AbstractValueObject { public OneToManyCarOption() { } public OneToManyCarOption(String name, Integer value) { this.name = name; this.value = value; } private String name; private Integer value; @Override public int hashCode() { return HashTool.compute(name); } @Override public ToStringHelper buildStringHelper() { return super.buildStringHelper() .add("name", name) .add("value", value); } private static final long serialVersionUID = -4017716295243845509L; }
apache-2.0
andrhamm/Singularity
SingularityService/src/main/java/com/hubspot/singularity/SingularityAbort.java
4836
package com.hubspot.singularity; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; import javax.inject.Named; import javax.inject.Singleton; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.state.ConnectionState; import org.apache.curator.framework.state.ConnectionStateListener; import org.eclipse.jetty.server.Server; import org.slf4j.ILoggerFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Optional; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.net.HostAndPort; import com.google.inject.Inject; import com.hubspot.mesos.JavaUtils; import com.hubspot.singularity.config.SMTPConfiguration; import com.hubspot.singularity.config.SingularityConfiguration; import com.hubspot.singularity.sentry.SingularityExceptionNotifier; import com.hubspot.singularity.smtp.SingularitySmtpSender; import ch.qos.logback.classic.LoggerContext; @Singleton public class SingularityAbort implements ConnectionStateListener { private static final Logger LOG = LoggerFactory.getLogger(SingularityAbort.class); private final Optional<SMTPConfiguration> maybeSmtpConfiguration; private final SingularitySmtpSender smtpSender; private final HostAndPort hostAndPort; private final SingularityExceptionNotifier exceptionNotifier; private final ServerProvider serverProvider; private final AtomicBoolean aborting = new AtomicBoolean(); @Inject public SingularityAbort(SingularitySmtpSender smtpSender, ServerProvider serverProvider, SingularityConfiguration configuration, SingularityExceptionNotifier exceptionNotifier, @Named(SingularityMainModule.HTTP_HOST_AND_PORT) HostAndPort hostAndPort) { this.maybeSmtpConfiguration = configuration.getSmtpConfigurationOptional(); this.serverProvider = serverProvider; this.smtpSender = smtpSender; this.exceptionNotifier = exceptionNotifier; this.hostAndPort = hostAndPort; } @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { if (newState == ConnectionState.LOST) { LOG.error("Aborting due to new connection state received from ZooKeeper: {}", newState); abort(AbortReason.LOST_ZK_CONNECTION, Optional.<Throwable>absent()); } } public enum AbortReason { LOST_ZK_CONNECTION, LOST_LEADERSHIP, UNRECOVERABLE_ERROR, TEST_ABORT, MESOS_ERROR; } public void abort(AbortReason abortReason, Optional<Throwable> throwable) { if (!aborting.getAndSet(true)) { try { sendAbortNotification(abortReason, throwable); flushLogs(); } finally { exit(); } } } private void exit() { Optional<Server> server = serverProvider.get(); if (server.isPresent()) { try { server.get().stop(); } catch (Exception e) { LOG.warn("While aborting server", e); } finally { System.exit(1); } } else { LOG.warn("SingularityAbort called before server has fully initialized!"); System.exit(1); // Use the hammer. } } private void sendAbortNotification(AbortReason abortReason, Optional<Throwable> throwable) { final String message = String.format("Singularity on %s is aborting due to %s", hostAndPort.getHostText(), abortReason); LOG.error(message); sendAbortMail(message, throwable); exceptionNotifier.notify(message, ImmutableMap.of("abortReason", abortReason.name())); } private void sendAbortMail(final String message, final Optional<Throwable> throwable) { if (!maybeSmtpConfiguration.isPresent()) { LOG.warn("Couldn't send abort mail because no SMTP configuration is present"); return; } final List<SingularityEmailDestination> emailDestination = maybeSmtpConfiguration.get().getEmailConfiguration().get(SingularityEmailType.SINGULARITY_ABORTING); if (emailDestination.isEmpty() || !emailDestination.contains(SingularityEmailDestination.ADMINS)) { LOG.info("Not configured to send abort mail"); return; } final String body = throwable.isPresent() ? throwable.get().toString() : "(no stack trace)"; smtpSender.queueMail(maybeSmtpConfiguration.get().getAdmins(), ImmutableList.<String> of(), message, body); } private void flushLogs() { final long millisToWait = 100; LOG.info("Attempting to flush logs and wait {} ...", JavaUtils.durationFromMillis(millisToWait)); ILoggerFactory loggerFactory = LoggerFactory.getILoggerFactory(); if (loggerFactory instanceof LoggerContext) { LoggerContext context = (LoggerContext) loggerFactory; context.stop(); } try { Thread.sleep(millisToWait); } catch (Exception e) { LOG.info("While sleeping for log flush", e); } } }
apache-2.0
sk-y/big-xlsx-reporter
src/main/java/bigreport/ReportMaker.java
10480
package bigreport; import bigreport.exception.CompositeIOException; import bigreport.exception.FileDeleteException; import bigreport.velocity.VelocityResolver; import bigreport.velocity.VelocityResult; import bigreport.xls.WorkBookParser; import bigreport.xls.merge.MergeInfo; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.apache.poi.openxml4j.opc.OPCPackage; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.apache.velocity.runtime.directive.Directive; import java.io.*; import java.util.Date; import java.util.Enumeration; import java.util.List; import java.util.Map; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import java.util.zip.ZipOutputStream; import static bigreport.util.StreamUtil.*; public class ReportMaker { private VelocityResolver resolver; private static final String DEFAULT_CHAR_SET = "UTF-8"; private String ecnoding; public ReportMaker(Map beans) { this(new VelocityResolver(beans)); } public ReportMaker(VelocityResolver resolver) { this(resolver, DEFAULT_CHAR_SET); } public ReportMaker(VelocityResolver resolver, String charset) { this.resolver = resolver; if (charset != null) { this.ecnoding = charset; } else { this.ecnoding = DEFAULT_CHAR_SET; } } public void createReport(InputStream templateInputStream, OutputStream resultOutputStream) throws IOException { File templateCopy = File.createTempFile("rm-report-" + new Date().getTime(), null); OutputStream templateCopyOutputStream = null; CompositeIOException compositeIOException=null; try { templateCopyOutputStream = new FileOutputStream(templateCopy); IOUtils.copy(templateInputStream, templateCopyOutputStream); doCreateReport(resultOutputStream, templateCopy); } catch (Exception e){ compositeIOException=new CompositeIOException(e); throw compositeIOException; } finally { IOUtils.closeQuietly(templateCopyOutputStream); forceDelete(templateCopy, compositeIOException); } } public void createReport(String templatePath, String destFilePath) throws IOException { File destFile = new File(destFilePath); FileOutputStream destOutputStream = null; File templateCopy = null; CompositeIOException compositeIOException=null; try { destOutputStream = new FileOutputStream(destFile); File templateFile = new File(templatePath); templateCopy = File.createTempFile(destFile.getName(), null); FileUtils.copyFile(templateFile, templateCopy); doCreateReport(destOutputStream, templateCopy); } catch (Exception e){ compositeIOException=new CompositeIOException(e); throw compositeIOException; } finally { IOUtils.closeQuietly(destOutputStream); forceDelete(templateCopy, compositeIOException); } } private void doCreateReport(OutputStream destOutputStream, File templateCopy) throws IOException { ZipOutputStream zipDestFileOutputStream = null; ZipFile zippedTemplateCopy = null; try { zipDestFileOutputStream = new ZipOutputStream(destOutputStream); Map<String, TemplateDescription> sheetTemplates = getTemplatePerSheet(templateCopy); zippedTemplateCopy = new ZipFile(templateCopy); if (sheetTemplates.isEmpty()) { return; } writeWorkBook(zipDestFileOutputStream, zippedTemplateCopy, sheetTemplates); } finally { closeZipFile(zippedTemplateCopy); finishZipOutputStream(zipDestFileOutputStream); } } private void writeWorkBook(ZipOutputStream zipDestFileOutputStream, ZipFile zippedTemplateCopy, Map<String, TemplateDescription> sheetTemplates) throws IOException { Enumeration<? extends ZipEntry> zipEntries = zippedTemplateCopy.entries(); while (zipEntries.hasMoreElements()) { ZipEntry zipEntry = zipEntries.nextElement(); zipDestFileOutputStream.putNextEntry(new ZipEntry(zipEntry.getName())); InputStream tempZipInputStream = null; try { tempZipInputStream = zippedTemplateCopy.getInputStream(zipEntry); TemplateDescription description = sheetTemplates.get(zipEntry.getName()); if (description != null && !description.isEmpty()) { VelocityResult result = resolveVelocityTemplate(zipEntry.getName(), sheetTemplates.get(zipEntry.getName())); String xlsxTemplateString = IOUtils.toString(tempZipInputStream, ecnoding); writeSheet(zipDestFileOutputStream, result, xlsxTemplateString, sheetTemplates.get(zipEntry.getName())); result.deleteAllTempFiles(); } else { IOUtils.copy(tempZipInputStream, zipDestFileOutputStream); if (description != null && description.getMergeInfo() != null) { description.getMergeInfo().reset(); } } zipDestFileOutputStream.flush(); zipDestFileOutputStream.closeEntry(); } finally { if (tempZipInputStream != null) { tempZipInputStream.close(); } } } } private VelocityResult resolveVelocityTemplate(String name, TemplateDescription templateDescription) throws IOException { Writer fw = null; File tempDataFile = null; MergeInfo mergeInfo = templateDescription.getMergeInfo(); try { tempDataFile = File.createTempFile(name.substring(name.lastIndexOf('/')).replace(' ', '_'), null); FileOutputStream outputStream = new FileOutputStream(tempDataFile); fw = new OutputStreamWriter(outputStream, DEFAULT_CHAR_SET); resolver.resolve(templateDescription, fw, mergeInfo.getMergedTempFile()); } finally { if (fw != null) { fw.close(); } } return new VelocityResult(tempDataFile, mergeInfo); } private void writeSheet(OutputStream output, VelocityResult velocityResult, String xlsxTemplateString, TemplateDescription templateDescription) throws IOException { writeBeforeData(templateDescription.getCellFrom().getRow() + 1, xlsxTemplateString, output); writeFromFileToOutputStream(velocityResult.getDataXmlFile(), output); writeBetweenDataAndMergedSection(velocityResult, xlsxTemplateString, output); writeMergedCellsSection(velocityResult, output); writeRestData(velocityResult, xlsxTemplateString, output); } private Map<String, TemplateDescription> getTemplatePerSheet(File templateCopy) throws IOException { XSSFWorkbook wb = null; FileInputStream templateCopyInputStream = null; try { templateCopyInputStream = new FileInputStream(templateCopy.getCanonicalPath()); wb = new XSSFWorkbook(templateCopyInputStream); WorkBookParser parser = new WorkBookParser(wb); return parser.parseWorkBook(); } finally { if (wb != null) { closePackage(wb.getPackage()); } IOUtils.closeQuietly(templateCopyInputStream); } } private void closePackage(OPCPackage aPackage) { try { aPackage.close(); } catch (IOException e) { //do nothing } } private void writeRestData(VelocityResult velocityResult, String xlsxTemplateString, OutputStream output) throws IOException { int startIndex; if (velocityResult.getMergeInfo().getCount() == 0) { int startMergedCells = xlsxTemplateString.indexOf(Markers.START_MERGED_CELLS); int endMergedCells = xlsxTemplateString.indexOf(Markers.END_MERGED_CELLS) + Markers.END_MERGED_CELLS.length(); if (startMergedCells >= 0 && endMergedCells >= 0) { xlsxTemplateString = new StringBuffer(xlsxTemplateString).replace(startMergedCells, endMergedCells, "").toString(); } startIndex = xlsxTemplateString.indexOf(Markers.END_DATA); } else { startIndex = xlsxTemplateString.indexOf(Markers.END_MERGED_CELLS); } if (startIndex >= 0) { IOUtils.write(xlsxTemplateString.substring(startIndex), output, DEFAULT_CHAR_SET); } } private void writeMergedCellsSection(VelocityResult velocityResult, OutputStream output) throws IOException { FileInputStream is = null; if (velocityResult.getMergeInfo().getCount() == 0) { return; } try { String mergeHeader = Markers.START_MERGED_CELLS + "count=\"" + velocityResult.getMergeInfo().getCount() + "\">"; IOUtils.write(mergeHeader, output, DEFAULT_CHAR_SET); is = new FileInputStream(velocityResult.getMergeInfo().getMergedTempFile()); IOUtils.copy(is, output); } finally { if (is != null) { is.close(); } } } private void writeBetweenDataAndMergedSection(VelocityResult velocityResult, String xlsxTemplateString, OutputStream output) throws IOException { if (velocityResult.getMergeInfo().getCount() > 0) { int endOfDataIndex = xlsxTemplateString.indexOf(Markers.END_DATA); int startMergedCellsGroup = xlsxTemplateString.indexOf(Markers.START_MERGED_CELLS); String beforeMergedCells = ""; if (startMergedCellsGroup >= 0) { beforeMergedCells = xlsxTemplateString.substring(endOfDataIndex, startMergedCellsGroup); } IOUtils.write(beforeMergedCells, output, DEFAULT_CHAR_SET); } } private void writeBeforeData(int rowStart, String xlsxTemplateString, OutputStream output) throws IOException { String beforeTemplate = xlsxTemplateString.substring(0, xlsxTemplateString.indexOf("<row r=\"" + rowStart + "\"")); IOUtils.write(beforeTemplate, output, DEFAULT_CHAR_SET); } }
apache-2.0
consulo/consulo-groovy
groovy-impl/src/main/java/org/jetbrains/plugins/groovy/lang/resolve/ast/LoggingContributor.java
2594
/* * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.plugins.groovy.lang.resolve.ast; import com.google.common.collect.ImmutableMap; import com.intellij.psi.PsiModifier; import javax.annotation.Nonnull; import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.GrModifierList; import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.annotation.GrAnnotation; import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrField; import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition; import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GrLightField; import org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil; import java.util.Collection; /** * @author peter */ public class LoggingContributor extends AstTransformContributor { private static final ImmutableMap<String, String> ourLoggers = ImmutableMap.<String, String>builder(). put("groovy.util.logging.Log", "java.util.logging.Logger"). put("groovy.util.logging.Commons", "org.apache.commons.logging.Log"). put("groovy.util.logging.Log4j", "org.apache.log4j.Logger"). put("groovy.util.logging.Slf4j", "org.slf4j.Logger"). build(); @Override public void collectFields(@Nonnull GrTypeDefinition psiClass, @Nonnull Collection<GrField> collector) { GrModifierList modifierList = psiClass.getModifierList(); if (modifierList == null) return; for (GrAnnotation annotation : modifierList.getAnnotations()) { String qname = annotation.getQualifiedName(); String logger = ourLoggers.get(qname); if (logger != null) { String fieldName = PsiUtil.getAnnoAttributeValue(annotation, "value", "log"); GrLightField field = new GrLightField(psiClass, fieldName, logger); field.setNavigationElement(annotation); field.getModifierList().setModifiers(PsiModifier.PRIVATE, PsiModifier.FINAL, PsiModifier.STATIC); field.setOriginInfo("created by @" + annotation.getShortName()); collector.add(field); } } } }
apache-2.0
blerer/cassandra
src/java/org/apache/cassandra/net/FrameEncoderUnprotected.java
2451
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.cassandra.net; import java.nio.ByteBuffer; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandler; import org.apache.cassandra.utils.memory.BufferPool; import static org.apache.cassandra.net.FrameEncoderCrc.HEADER_LENGTH; import static org.apache.cassandra.net.FrameEncoderCrc.writeHeader; /** * A frame encoder that writes frames, just without any modification or payload protection. * This is non-standard, and useful for systems that have a trusted transport layer that want * to avoid incurring the (very low) cost of computing a CRC. * * Please see {@link FrameDecoderUnprotected} for description of the framing produced by this encoder. */ @ChannelHandler.Sharable class FrameEncoderUnprotected extends FrameEncoder { static final FrameEncoderUnprotected instance = new FrameEncoderUnprotected(); static final PayloadAllocator allocator = (isSelfContained, capacity) -> new Payload(isSelfContained, capacity, HEADER_LENGTH, 0); PayloadAllocator allocator() { return allocator; } ByteBuf encode(boolean isSelfContained, ByteBuffer frame) { try { int frameLength = frame.remaining(); int dataLength = frameLength - HEADER_LENGTH; if (dataLength >= 1 << 17) throw new IllegalArgumentException("Maximum uncompressed payload size is 128KiB"); writeHeader(frame, isSelfContained, dataLength); return GlobalBufferPoolAllocator.wrap(frame); } catch (Throwable t) { bufferPool.put(frame); throw t; } } }
apache-2.0
aNNiMON/HotaruFX
app/src/main/java/com/annimon/hotarufx/lib/InterpolatorValue.java
890
package com.annimon.hotarufx.lib; import com.annimon.hotarufx.exceptions.TypeException; import javafx.animation.Interpolator; public class InterpolatorValue implements Value { private final Interpolator interpolator; public InterpolatorValue(Interpolator interpolator) { this.interpolator = interpolator; } public Interpolator getInterpolator() { return interpolator; } @Override public int type() { return Types.INTERPOLATOR; } @Override public Object raw() { return interpolator; } @Override public Number asNumber() { throw new TypeException("Cannot cast interpolator to number"); } @Override public String asString() { throw new TypeException("Cannot cast interpolator to string"); } @Override public int compareTo(Value o) { return 0; } }
apache-2.0
easyandroid-cc/EasyVpn
app/src/main/java/cc/easyandroid/easyvpn/ui/EasyAppBarLayout.java
2936
package cc.easyandroid.easyvpn.ui; import android.content.Context; import android.support.design.widget.AppBarLayout; import android.support.v4.view.ViewCompat; import android.support.v4.view.WindowInsetsCompat; import android.util.AttributeSet; import android.view.View; public class EasyAppBarLayout extends AppBarLayout { public EasyAppBarLayout(Context context) { super(context); init(context); } public EasyAppBarLayout(Context context, AttributeSet attrs) { super(context, attrs); init(context); } private void init(Context context) { ViewCompat.setOnApplyWindowInsetsListener(this, new android.support.v4.view.OnApplyWindowInsetsListener() { @Override public WindowInsetsCompat onApplyWindowInsets(View v, WindowInsetsCompat insets) { return setWindowInsets(insets); } }); } private WindowInsetsCompat setWindowInsets(WindowInsetsCompat insets) { if (mLastInsets != insets) { mLastInsets = insets; requestLayout(); } return insets.consumeSystemWindowInsets(); } WindowInsetsCompat mLastInsets; private int getTopInset() { //EasyAppBarLayout 不是第一个view时候setOnApplyWindowInsetsListener 不会调用 return mLastInsets != null ? mLastInsets.getSystemWindowInsetTop() : getStatusBarHeight(getContext()); } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); // Update our child view offset helpers for (int i = 0, z = getChildCount(); i < z; i++) { final View child = getChildAt(i); if (!ViewCompat.getFitsSystemWindows(child)) { final int insetTop = getTopInset(); if (child.getTop() < insetTop) { // If the child isn't set to fit system windows but is drawing within the inset // offset it down ViewCompat.offsetTopAndBottom(child, insetTop); } } } } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); setMeasuredDimension(getMeasuredWidth(), getMeasuredHeight() + getTopInset()); } public static int getStatusBarHeight(Context context) { if (android.os.Build.VERSION.SDK_INT >= 21) { int result = 0; int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android"); if (resourceId > 0) { result = context.getResources().getDimensionPixelSize(resourceId); } return result; } else { return 0; } } }
apache-2.0
MathieuConstant/lgtools
lgtools-2.0/src/fr/upem/lgtools/parser/Configurations.java
619
/** * */ package fr.upem.lgtools.parser; import fr.upem.lgtools.text.Sentence; /** * @author mconstant * */ public class Configurations { public static <T extends Analysis> Configuration<T> createDefaultConfiguration(Configuration<T> c){ return new SimpleConfiguration<T>((SimpleConfiguration<T>)c); } public static Configuration<DepTree> createDefaultConfiguration(Sentence s,int bufferCount, int stackCount, DepTree goldTree){ return new SimpleConfiguration<DepTree>(s, new DepTree(s.getUnits().size() + 1),goldTree, bufferCount, stackCount); //return new SimpleConfiguration<T>(); } }
apache-2.0
aprescott/diffa
participant-support/src/main/java/net/lshift/diffa/participant/scanning/SealedBucketException.java
937
/** * Copyright (C) 2010-2011 LShift Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.lshift.diffa.participant.scanning; /** * Exception indicating that getDigest has already been called on a DigestBuilder, so it can no longer have * items added. */ class SealedBucketException extends RuntimeException { public SealedBucketException(String vsn, String name) { super(vsn + " -> " + name); } }
apache-2.0
olehmberg/winter
winter-framework/src/main/java/de/uni_mannheim/informatik/dws/winter/utils/mining/FrequentItemSetMiner.java
3956
/** * * Copyright (C) 2015 Data and Web Science Group, University of Mannheim, Germany (code@dwslab.de) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package de.uni_mannheim.informatik.dws.winter.utils.mining; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import de.uni_mannheim.informatik.dws.winter.utils.Distribution; import de.uni_mannheim.informatik.dws.winter.utils.MapUtils; import de.uni_mannheim.informatik.dws.winter.utils.query.Q; import de.uni_mannheim.informatik.dws.winter.webtables.Table; /** * @author Oliver Lehmberg (oli@dwslab.de) * */ public class FrequentItemSetMiner<TItem> { public Map<Set<TItem>, Integer> calculateFrequentItemSetsOfColumnPositions(Collection<Table> tables, Set<Collection<TItem>> transactions) { Map<Set<TItem>, Integer> itemSets = new HashMap<>(); // index transactions by item Map<TItem, Set<Collection<TItem>>> transactionIndex = new HashMap<>(); // create all 1-item sets for(Collection<TItem> transaction : transactions) { Distribution<TItem> itemDistribution = Distribution.fromCollection(transaction); for(TItem item : itemDistribution.getElements()) { // create the item set Set<TItem> itemSet = Q.toSet(item); MapUtils.add(itemSets, itemSet, itemDistribution.getFrequency(item)); Set<Collection<TItem>> t = MapUtils.getFast(transactionIndex, item, (i) -> new HashSet<>()); t.add(transaction); } } // create all i+1 item sets boolean hasChanges = false; // easy access to item sets generated in the last round Set<Set<TItem>> OneItemSets = new HashSet<>(itemSets.keySet()); Set<Set<TItem>> lastItemSets = itemSets.keySet(); Set<Set<TItem>> currentItemSets = new HashSet<>(); // loop until no new item sets are discovered do { // iterate over all item sets created in the last round for(Set<TItem> itemset1 : lastItemSets) { // and combine them with the 1-item sets to create new item sets for(Set<TItem> itemset2 : OneItemSets) { if(!itemset1.equals(itemset2) && !itemset1.containsAll(itemset2)) { Set<TItem> itemset = new HashSet<>(); itemset.addAll(itemset1); itemset.addAll(itemset2); currentItemSets.add(itemset); } } } // calculate frequency of new item sets Iterator<Set<TItem>> it = currentItemSets.iterator(); while(it.hasNext()) { Set<TItem> itemSet = it.next(); Set<Collection<TItem>> commonTransactions = null; for(TItem item : itemSet) { Set<Collection<TItem>> transactionsWithItem = transactionIndex.get(item); if(commonTransactions==null) { commonTransactions = transactionsWithItem; } else { commonTransactions = Q.intersection(commonTransactions, transactionsWithItem); } if(commonTransactions.size()==0) { break; } } if(commonTransactions.size()==0) { it.remove(); } else { itemSets.put(itemSet, commonTransactions.size()); } } hasChanges = currentItemSets.size()>0; lastItemSets = currentItemSets; currentItemSets = new HashSet<>(); } while(hasChanges); return itemSets; } }
apache-2.0
aws/aws-sdk-java
aws-java-sdk-codecommit/src/main/java/com/amazonaws/services/codecommit/model/GetBlobRequest.java
5181
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.codecommit.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.AmazonWebServiceRequest; /** * <p> * Represents the input of a get blob operation. * </p> * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/codecommit-2015-04-13/GetBlob" target="_top">AWS API * Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class GetBlobRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable { /** * <p> * The name of the repository that contains the blob. * </p> */ private String repositoryName; /** * <p> * The ID of the blob, which is its SHA-1 pointer. * </p> */ private String blobId; /** * <p> * The name of the repository that contains the blob. * </p> * * @param repositoryName * The name of the repository that contains the blob. */ public void setRepositoryName(String repositoryName) { this.repositoryName = repositoryName; } /** * <p> * The name of the repository that contains the blob. * </p> * * @return The name of the repository that contains the blob. */ public String getRepositoryName() { return this.repositoryName; } /** * <p> * The name of the repository that contains the blob. * </p> * * @param repositoryName * The name of the repository that contains the blob. * @return Returns a reference to this object so that method calls can be chained together. */ public GetBlobRequest withRepositoryName(String repositoryName) { setRepositoryName(repositoryName); return this; } /** * <p> * The ID of the blob, which is its SHA-1 pointer. * </p> * * @param blobId * The ID of the blob, which is its SHA-1 pointer. */ public void setBlobId(String blobId) { this.blobId = blobId; } /** * <p> * The ID of the blob, which is its SHA-1 pointer. * </p> * * @return The ID of the blob, which is its SHA-1 pointer. */ public String getBlobId() { return this.blobId; } /** * <p> * The ID of the blob, which is its SHA-1 pointer. * </p> * * @param blobId * The ID of the blob, which is its SHA-1 pointer. * @return Returns a reference to this object so that method calls can be chained together. */ public GetBlobRequest withBlobId(String blobId) { setBlobId(blobId); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getRepositoryName() != null) sb.append("RepositoryName: ").append(getRepositoryName()).append(","); if (getBlobId() != null) sb.append("BlobId: ").append(getBlobId()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof GetBlobRequest == false) return false; GetBlobRequest other = (GetBlobRequest) obj; if (other.getRepositoryName() == null ^ this.getRepositoryName() == null) return false; if (other.getRepositoryName() != null && other.getRepositoryName().equals(this.getRepositoryName()) == false) return false; if (other.getBlobId() == null ^ this.getBlobId() == null) return false; if (other.getBlobId() != null && other.getBlobId().equals(this.getBlobId()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getRepositoryName() == null) ? 0 : getRepositoryName().hashCode()); hashCode = prime * hashCode + ((getBlobId() == null) ? 0 : getBlobId().hashCode()); return hashCode; } @Override public GetBlobRequest clone() { return (GetBlobRequest) super.clone(); } }
apache-2.0
avery1701/thor
src/test/java/com/advancedpwr/samples/PersonFactory.java
522
package com.advancedpwr.samples; public class PersonFactory { public Person createExamplePerson() { Person grandpa = createGrandPa(); Person dad = new Person(); dad.setName( "dad" ); dad.setDad( grandpa ); Person mom = new Person(); mom.setName( "mom" ); Person son = new Person(); son.setName( "son" ); son.setDad( dad ); son.setMom( mom ); return son; } protected Person createGrandPa() { Person grandpa = new Person(); grandpa.setName( "grandpa" ); return grandpa; } }
apache-2.0
lsmall/flowable-engine
modules/flowable-spring-boot/flowable-spring-boot-samples/flowable-spring-boot-sample-app/src/main/java/flowable/AppSampleApplication.java
329
package flowable; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** * */ @SpringBootApplication public class AppSampleApplication { public static void main(String args[]) { SpringApplication.run(AppSampleApplication.class, args); } }
apache-2.0
kevinsi4508/cloud-bigtable-client
bigtable-dataflow-parent/bigtable-beam-import/src/main/java/com/google/cloud/bigtable/beam/TemplateUtils.java
5714
/* * Copyright 2018 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. */ package com.google.cloud.bigtable.beam; import com.google.bigtable.repackaged.com.google.bigtable.v2.ReadRowsRequest; import com.google.cloud.bigtable.beam.sequencefiles.ExportJob.ExportOptions; import com.google.cloud.bigtable.beam.sequencefiles.ImportJob.ImportOptions; import com.google.cloud.bigtable.hbase.adapters.Adapters; import com.google.cloud.bigtable.hbase.adapters.read.DefaultReadHooks; import com.google.cloud.bigtable.hbase.adapters.read.ReadHooks; import java.io.Serializable; import java.nio.charset.CharacterCodingException; import org.apache.beam.sdk.options.ValueProvider; import org.apache.hadoop.hbase.client.Scan; import org.apache.hadoop.hbase.filter.ParseFilter; import com.google.cloud.bigtable.hbase.BigtableOptionsFactory; /** * !!! DO NOT TOUCH THIS CLASS !!! * * <p>Utility needed to help setting runtime parameters in Bigtable configurations. This is needed * because the methods that take runtime parameters are package private and not intended for direct * public consumption for now. */ public class TemplateUtils { /** Builds CloudBigtableTableConfiguration from input runtime parameters for import job. */ public static CloudBigtableTableConfiguration BuildImportConfig(ImportOptions opts) { CloudBigtableTableConfiguration.Builder builder = new CloudBigtableTableConfiguration.Builder() .withProjectId(opts.getBigtableProject()) .withInstanceId(opts.getBigtableInstanceId()) .withTableId(opts.getBigtableTableId()); if (opts.getBigtableAppProfileId() != null) { builder.withAppProfileId(opts.getBigtableAppProfileId()); } ValueProvider enableThrottling = ValueProvider.NestedValueProvider.of( opts.getMutationThrottleLatencyMs(), (Integer throttleMs) -> String.valueOf(throttleMs > 0)); builder.withConfiguration(BigtableOptionsFactory.BIGTABLE_BUFFERED_MUTATOR_ENABLE_THROTTLING, enableThrottling); builder.withConfiguration(BigtableOptionsFactory.BIGTABLE_BUFFERED_MUTATOR_THROTTLING_THRESHOLD_MILLIS, ValueProvider.NestedValueProvider.of(opts.getMutationThrottleLatencyMs(), String::valueOf)); return builder.build(); } /** Provides a request that is constructed with some attributes. */ private static class RequestValueProvider implements ValueProvider<ReadRowsRequest>, Serializable { private final ValueProvider<String> start; private final ValueProvider<String> stop; private final ValueProvider<Integer> maxVersion; private final ValueProvider<String> filter; private ReadRowsRequest cachedRequest; RequestValueProvider( ValueProvider<String> start, ValueProvider<String> stop, ValueProvider<Integer> maxVersion, ValueProvider<String> filter) { this.start = start; this.stop = stop; this.maxVersion = maxVersion; this.filter = filter; } @Override public ReadRowsRequest get() { if (cachedRequest == null) { Scan scan = new Scan(); if (start.get() != null && !start.get().isEmpty()) { scan.setStartRow(start.get().getBytes()); } if (stop.get() != null && !stop.get().isEmpty()) { scan.setStopRow(stop.get().getBytes()); } if (maxVersion.get() != null) { scan.setMaxVersions(maxVersion.get()); } if (filter.get() != null && !filter.get().isEmpty()) { try { scan.setFilter(new ParseFilter().parseFilterString(filter.get())); } catch (CharacterCodingException e) { throw new RuntimeException(e); } } ReadHooks readHooks = new DefaultReadHooks(); ReadRowsRequest.Builder builder = Adapters.SCAN_ADAPTER.adapt(scan, readHooks); cachedRequest = readHooks.applyPreSendHook(builder.build()); } return cachedRequest; } @Override public boolean isAccessible() { return start.isAccessible() && stop.isAccessible() && maxVersion.isAccessible() && filter.isAccessible(); } @Override public String toString() { if (isAccessible()) { return String.valueOf(get()); } return CloudBigtableConfiguration.VALUE_UNAVAILABLE; } } /** Builds CloudBigtableScanConfiguration from input runtime parameters for export job. */ public static CloudBigtableScanConfiguration BuildExportConfig(ExportOptions opts) { ValueProvider<ReadRowsRequest> request = new RequestValueProvider( opts.getBigtableStartRow(), opts.getBigtableStopRow(), opts.getBigtableMaxVersions(), opts.getBigtableFilter()); CloudBigtableScanConfiguration.Builder configBuilder = new CloudBigtableScanConfiguration.Builder() .withProjectId(opts.getBigtableProject()) .withInstanceId(opts.getBigtableInstanceId()) .withTableId(opts.getBigtableTableId()) .withAppProfileId(opts.getBigtableAppProfileId()) .withRequest(request); return configBuilder.build(); } }
apache-2.0
lcamilo15/hapi-fhir
hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/annotation/OperationParam.java
1739
package ca.uhn.fhir.rest.annotation; /* * #%L * HAPI FHIR - Core Library * %% * Copyright (C) 2014 - 2015 University Health Network * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.hl7.fhir.instance.model.api.IBase; /** */ @Retention(RetentionPolicy.RUNTIME) @Target(value=ElementType.PARAMETER) public @interface OperationParam { /** * Value for {@link OperationParam#max()} indicating no maximum */ final int MAX_UNLIMITED = -1; /** * The name of the parameter */ String name(); /** * The type of the parameter. This will only have effect on <code>@OperationParam</code> * annotations specified as values for {@link Operation#returnParameters()} */ Class<? extends IBase> type() default IBase.class; /** * The minimum number of repetitions allowed for this child */ int min() default 0; /** * The maximum number of repetitions allowed for this child. Should be * set to {@link #MAX_UNLIMITED} if there is no limit to the number of * repetitions. */ int max() default MAX_UNLIMITED; }
apache-2.0
diorcety/system-manager
async/async-bundle/src/main/java/com/zenika/systemmanager/async/service/ChatEntry.java
1129
/* * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. * */ package com.zenika.systemmanager.async.service; public class ChatEntry { public String pseudo; public String message; public ChatEntry() { } public ChatEntry(String pseudo, String message) { this.pseudo = pseudo; this.message = message; } }
apache-2.0
naotsugu/example-jersey-grizzly
src/main/java/example/Main.java
2399
package example; import com.avaje.ebean.Ebean; import com.avaje.ebean.EbeanServer; import org.avaje.agentloader.AgentLoader; import org.glassfish.grizzly.http.server.CLStaticHttpHandler; import org.glassfish.grizzly.http.server.HttpServer; import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory; import org.glassfish.jersey.server.ResourceConfig; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.ws.rs.Priorities; import javax.ws.rs.core.CacheControl; import javax.ws.rs.core.UriBuilder; import java.awt.*; import java.io.IOException; import java.net.URI; public class Main { private static Logger log = LoggerFactory.getLogger(Main.class); static final URI BASE_URI = UriBuilder.fromUri("http://localhost/").port(8090).build(); public static void main(String[] args) throws IOException { setupEbean(); final HttpServer server = GrizzlyHttpServerFactory.createHttpServer( BASE_URI, ResourceConfig.forApplicationClass(RsResourceConfig.class), false); // static assets server.getServerConfiguration().addHttpHandler( new CLStaticHttpHandler(Main.class.getClassLoader(), "/assets/"), "/static"); server.start(); Runtime.getRuntime().addShutdownHook(new Thread(server::shutdownNow)); openBrowser(); log.info("Start grizzly. Press any key to exit."); System.in.read(); System.exit(0); } private static EbeanServer setupEbean() { boolean success = AgentLoader.loadAgentFromClasspath( "avaje-ebeanorm-agent", "debug=1;packages=example.domain.model.**"); if (!success) log.error("ebean agent not found - not dynamically loaded"); return Ebean.getServer("h2"); } private static void openBrowser() { try { if (Desktop.isDesktopSupported()) Desktop.getDesktop().browse(Main.BASE_URI); } catch (IOException ignore) { log.error("failed to launch browser.", ignore); } } public static class RsResourceConfig extends ResourceConfig { public RsResourceConfig() { packages("example.web.resource"); packages("example.web.filter"); register(CacheControl.class, Priorities.HEADER_DECORATOR); } } }
apache-2.0
camachohoracio/Armadillo.Core
Communication/src/main/java/Armadillo/Communication/zmq/zmq/V1Decoder.java
4395
package Armadillo.Communication.zmq.zmq; import java.nio.ByteBuffer; public class V1Decoder extends DecoderBase { private static final int one_byte_size_ready = 0; private static final int eight_byte_size_ready = 1; private static final int flags_ready = 2; private static final int message_ready = 3; private final byte[] tmpbuf; private Msg in_progress; private IMsgSink msg_sink; private final long maxmsgsize; private int msg_flags; public V1Decoder (int bufsize_, long maxmsgsize_, IMsgSink session) { super (bufsize_); maxmsgsize = maxmsgsize_; msg_sink = session; tmpbuf = new byte[8]; // At the beginning, read one byte and go to one_byte_size_ready state. next_step (tmpbuf, 1, flags_ready); } // Set the receiver of decoded messages. @Override public void set_msg_sink (IMsgSink msg_sink_) { msg_sink = msg_sink_; } @Override protected boolean next() { switch(state()) { case one_byte_size_ready: return one_byte_size_ready (); case eight_byte_size_ready: return eight_byte_size_ready (); case flags_ready: return flags_ready (); case message_ready: return message_ready (); default: return false; } } private boolean one_byte_size_ready () { int size = tmpbuf [0]; if (size < 0) size = (0xff) & size; // Message size must not exceed the maximum allowed size. if (maxmsgsize >= 0) if (size > maxmsgsize) { decoding_error (); return false; } // in_progress is initialised at this point so in theory we should // close it before calling zmq_msg_init_size, however, it's a 0-byte // message and thus we can treat it as uninitialised... in_progress = new Msg (size); in_progress.set_flags (msg_flags); next_step (in_progress.data (), in_progress.size (), message_ready); return true; } private boolean eight_byte_size_ready() { // The payload size is encoded as 64-bit unsigned integer. // The most significant byte comes first. final long msg_size = ByteBuffer.wrap(tmpbuf).getLong(); // Message size must not exceed the maximum allowed size. if (maxmsgsize >= 0) if (msg_size > maxmsgsize) { decoding_error (); return false; } // Message size must fit within range of size_t data type. if (msg_size > Integer.MAX_VALUE) { decoding_error (); return false; } // in_progress is initialised at this point so in theory we should // close it before calling init_size, however, it's a 0-byte // message and thus we can treat it as uninitialised. in_progress = new Msg ((int) msg_size); in_progress.set_flags (msg_flags); next_step (in_progress.data (), in_progress.size (), message_ready); return true; } private boolean flags_ready() { // Store the flags from the wire into the message structure. msg_flags = 0; int first = tmpbuf[0]; if ((first & V1Protocol.MORE_FLAG) > 0) msg_flags |= Msg.more; // The payload length is either one or eight bytes, // depending on whether the 'large' bit is set. if ((first & V1Protocol.LARGE_FLAG) > 0) next_step (tmpbuf, 8, eight_byte_size_ready); else next_step (tmpbuf, 1, one_byte_size_ready); return true; } private boolean message_ready() { // Message is completely read. Push it further and start reading // new message. (in_progress is a 0-byte message after this point.) if (msg_sink == null) return false; int rc = msg_sink.push_msg(in_progress); if (rc != 0) { if (rc != ZError.EAGAIN) decoding_error (); return false; } next_step (tmpbuf, 1, flags_ready); return true; } }
apache-2.0
inkstand-io/scribble
scribble-jcr/src/test/java/io/inkstand/scribble/jcr/rules/RemoteContentRepositoryTest.java
5151
/* * Copyright 2015-2016 DevCon5 GmbH, info@devcon5.ch * * 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.inkstand.scribble.jcr.rules; import static org.junit.Assert.assertEquals; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.StringWriter; import java.net.URL; import java.nio.charset.Charset; import org.apache.commons.io.IOUtils; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.runners.MockitoJUnitRunner; /** * Created by Gerald on 19.05.2015. */ @RunWith(MockitoJUnitRunner.class) public class RemoteContentRepositoryTest { @Rule public TemporaryFolder folder = new TemporaryFolder(); /** * The class under test */ @InjectMocks private RemoteContentRepository subject; @Test(expected = AssertionError.class) public void testBefore_invalidContainerQualifier() throws Throwable { //prepare System.setProperty("arquillian.launch", "& '1'='1'"); URL arquillianContainerConfiguration = new URL("file:///notexisting"); subject.onArquillianHost(arquillianContainerConfiguration); //act subject.before(); } @Test public void testBefore_validContainerQualifier() throws Throwable { //prepare System.setProperty("arquillian.launch", "testContainer"); URL arquillianContainerConfiguration = getClass().getResource("RemoteContentRepositoryTest_arquillian.xml"); subject.onArquillianHost(arquillianContainerConfiguration); subject.setupManually(); //act subject.before(); //assert assertEquals("test.example.com", subject.getRemoteHost()); } /** * This tests implements an exploit to the XML External Entity Attack {@see http://www.ws-attacks.org/index.php/XML_Entity_Reference_Attack}. * The attack targets a file in the filesystem containing a secret, i.e. a password, which is not untypical for * build servers containing passwords for artifact repositories. The attacking file defines an entity that resolves * to the file containing the secret. The entity (&amp;xxx;) is used in the xml file and can be read using xpath. * The RemoteContentRepository rule uses an arquillian.xml file to resolve the hostname of the target server using * an xpath expression. A test may use a specially prepared xml file and (optionally) an xpath injection to resolve * the contents of a system file. Of course this is more a hypothetical attack in a test framework as the attacker * may freely access the file directly with the same privileges as the user that started the JVM. * * @throws Throwable */ @Test(expected = AssertionError.class) public void test_ExternalitEntityAttack_notVulnerable() throws Throwable { //prepare //the attacked file containing the secret final File attackedFile = folder.newFile("attackedFile.txt"); try (FileOutputStream fos = new FileOutputStream(attackedFile)) { IOUtils.write("secretContent", fos); } //as attacker file we use a template and replacing a %s placeholder with the url of the attacked file //in a real-world attack we would use a valuable target such as /etc/passwd final File attackerFile = folder.newFile("attackerFile.xml"); //load the template file from the classpath try (InputStream is = getClass().getResourceAsStream("RemoteContentRepositoryTest_attacker.xml"); FileOutputStream fos = new FileOutputStream(attackerFile)) { final String attackerContent = prepareAttackerContent(is, attackedFile); IOUtils.write(attackerContent, fos); } System.setProperty("arquillian.launch", "testContainer"); subject.onArquillianHost(attackerFile.toURI().toURL()); subject.setupManually(); //act subject.before(); //assert //the content from the attacked file is put into the attacking xml where it resolves to the hostname assertEquals("secretContent", subject.getRemoteHost()); } private String prepareAttackerContent(final InputStream templateInputStream, final File attackedFile) throws IOException { final StringWriter writer = new StringWriter(); IOUtils.copy(templateInputStream, writer, Charset.defaultCharset()); return String.format(writer.toString(), attackedFile.toURI().toURL()); } }
apache-2.0
submain/intellij-haxe
gen/com/intellij/plugins/haxe/lang/psi/HaxeInherit.java
906
/* * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // This is a generated file. Not intended for manual editing. package com.intellij.plugins.haxe.lang.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; public interface HaxeInherit extends HaxePsiCompositeElement { @Nullable HaxeType getType(); }
apache-2.0
alinekborges/AndroidDestin
app/src/main/java/com/semanadeeletronica/destincompleto/GitHubActivity.java
1582
package com.semanadeeletronica.destincompleto; import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import com.semanadeeletronica.destincompleto.util.Navigation; public class GitHubActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_git_hub); } @Override public void onBackPressed() { super.onBackPressed(); Navigation.animate(this, Navigation.Animation.BACK); } public void gitHubOnClick(View v) { String url = "https://github.com/alinekborges/AndroidDestin"; Intent i = new Intent(Intent.ACTION_VIEW); i.setData(Uri.parse(url)); startActivity(i); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.git_hub, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
apache-2.0
JichengSong/hbase
src/main/java/org/apache/hadoop/hbase/KeyValue.java
78013
/** * Copyright 2009 The Apache Software Foundation * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hbase; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.nio.ByteBuffer; import java.util.Comparator; import java.util.HashMap; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.hbase.io.HeapSize; import org.apache.hadoop.hbase.io.hfile.HFile; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.hbase.util.ClassSize; import org.apache.hadoop.io.RawComparator; import org.apache.hadoop.io.Writable; import com.google.common.primitives.Longs; /** * An HBase Key/Value. This is the fundamental HBase Type. * * <p>If being used client-side, the primary methods to access individual fields * are {@link #getRow()}, {@link #getFamily()}, {@link #getQualifier()}, * {@link #getTimestamp()}, and {@link #getValue()}. These methods allocate new * byte arrays and return copies. Avoid their use server-side. * * <p>Instances of this class are immutable. They do not implement Comparable * but Comparators are provided. Comparators change with context, * whether user table or a catalog table comparison. Its critical you use the * appropriate comparator. There are Comparators for KeyValue instances and * then for just the Key portion of a KeyValue used mostly by {@link HFile}. * * <p>KeyValue wraps a byte array and takes offsets and lengths into passed * array at where to start interpreting the content as KeyValue. The KeyValue * format inside a byte array is: * <code>&lt;keylength> &lt;valuelength> &lt;key> &lt;value></code> * Key is further decomposed as: * <code>&lt;rowlength> &lt;row> &lt;columnfamilylength> &lt;columnfamily> &lt;columnqualifier> &lt;timestamp> &lt;keytype></code> * The <code>rowlength</code> maximum is <code>Short.MAX_SIZE</code>, * column family length maximum is * <code>Byte.MAX_SIZE</code>, and column qualifier + key length must * be < <code>Integer.MAX_SIZE</code>. * The column does not contain the family/qualifier delimiter, {@link #COLUMN_FAMILY_DELIMITER} */ public class KeyValue implements Writable, HeapSize, Cloneable { static final Log LOG = LogFactory.getLog(KeyValue.class); // TODO: Group Key-only comparators and operations into a Key class, just // for neatness sake, if can figure what to call it. /** * Colon character in UTF-8 */ public static final char COLUMN_FAMILY_DELIMITER = ':'; public static final byte[] COLUMN_FAMILY_DELIM_ARRAY = new byte[]{COLUMN_FAMILY_DELIMITER}; /** * Comparator for plain key/values; i.e. non-catalog table key/values. */ public static KVComparator COMPARATOR = new KVComparator(); /** * Comparator for plain key; i.e. non-catalog table key. Works on Key portion * of KeyValue only. */ public static KeyComparator KEY_COMPARATOR = new KeyComparator(); /** * A {@link KVComparator} for <code>.META.</code> catalog table * {@link KeyValue}s. */ public static KVComparator META_COMPARATOR = new MetaComparator(); /** * A {@link KVComparator} for <code>.META.</code> catalog table * {@link KeyValue} keys. */ public static KeyComparator META_KEY_COMPARATOR = new MetaKeyComparator(); /** * A {@link KVComparator} for <code>-ROOT-</code> catalog table * {@link KeyValue}s. */ public static KVComparator ROOT_COMPARATOR = new RootComparator(); /** * A {@link KVComparator} for <code>-ROOT-</code> catalog table * {@link KeyValue} keys. */ public static KeyComparator ROOT_KEY_COMPARATOR = new RootKeyComparator(); /** * Get the appropriate row comparator for the specified table. * * Hopefully we can get rid of this, I added this here because it's replacing * something in HSK. We should move completely off of that. * * @param tableName The table name. * @return The comparator. */ public static KeyComparator getRowComparator(byte [] tableName) { if(Bytes.equals(HTableDescriptor.ROOT_TABLEDESC.getName(),tableName)) { return ROOT_COMPARATOR.getRawComparator(); } if(Bytes.equals(HTableDescriptor.META_TABLEDESC.getName(), tableName)) { return META_COMPARATOR.getRawComparator(); } return COMPARATOR.getRawComparator(); } /** Size of the key length field in bytes*/ public static final int KEY_LENGTH_SIZE = Bytes.SIZEOF_INT; /** Size of the key type field in bytes */ public static final int TYPE_SIZE = Bytes.SIZEOF_BYTE; /** Size of the row length field in bytes */ public static final int ROW_LENGTH_SIZE = Bytes.SIZEOF_SHORT; /** Size of the family length field in bytes */ public static final int FAMILY_LENGTH_SIZE = Bytes.SIZEOF_BYTE; /** Size of the timestamp field in bytes */ public static final int TIMESTAMP_SIZE = Bytes.SIZEOF_LONG; // Size of the timestamp and type byte on end of a key -- a long + a byte. public static final int TIMESTAMP_TYPE_SIZE = TIMESTAMP_SIZE + TYPE_SIZE; // Size of the length shorts and bytes in key. public static final int KEY_INFRASTRUCTURE_SIZE = ROW_LENGTH_SIZE + FAMILY_LENGTH_SIZE + TIMESTAMP_TYPE_SIZE; // How far into the key the row starts at. First thing to read is the short // that says how long the row is. public static final int ROW_OFFSET = Bytes.SIZEOF_INT /*keylength*/ + Bytes.SIZEOF_INT /*valuelength*/; // Size of the length ints in a KeyValue datastructure. public static final int KEYVALUE_INFRASTRUCTURE_SIZE = ROW_OFFSET; /** * Key type. * Has space for other key types to be added later. Cannot rely on * enum ordinals . They change if item is removed or moved. Do our own codes. */ public static enum Type { Minimum((byte)0), Put((byte)4), Delete((byte)8), DeleteColumn((byte)12), DeleteFamily((byte)14), // Maximum is used when searching; you look from maximum on down. Maximum((byte)255); private final byte code; Type(final byte c) { this.code = c; } public byte getCode() { return this.code; } /** * Cannot rely on enum ordinals . They change if item is removed or moved. * Do our own codes. * @param b * @return Type associated with passed code. */ public static Type codeToType(final byte b) { for (Type t : Type.values()) { if (t.getCode() == b) { return t; } } throw new RuntimeException("Unknown code " + b); } } /** * Lowest possible key. * Makes a Key with highest possible Timestamp, empty row and column. No * key can be equal or lower than this one in memstore or in store file. */ public static final KeyValue LOWESTKEY = new KeyValue(HConstants.EMPTY_BYTE_ARRAY, HConstants.LATEST_TIMESTAMP); private byte [] bytes = null; private int offset = 0; private int length = 0; /** * @return True if a delete type, a {@link KeyValue.Type#Delete} or * a {KeyValue.Type#DeleteFamily} or a {@link KeyValue.Type#DeleteColumn} * KeyValue type. */ public static boolean isDelete(byte t) { return Type.Delete.getCode() <= t && t <= Type.DeleteFamily.getCode(); } /** Here be dragons **/ // used to achieve atomic operations in the memstore. public long getMemstoreTS() { return memstoreTS; } /**更改MVVC版本号,这个方法名该为setMvvcVersion更直观*/ public void setMemstoreTS(long memstoreTS) { this.memstoreTS = memstoreTS; } // default value is 0, aka DNC private long memstoreTS = 0; /** Dragon time over, return to normal business */ /** Writable Constructor -- DO NOT USE */ public KeyValue() {} /** * Creates a KeyValue from the start of the specified byte array. * Presumes <code>bytes</code> content is formatted as a KeyValue blob. * @param bytes byte array */ public KeyValue(final byte [] bytes) { this(bytes, 0); } /** * Creates a KeyValue from the specified byte array and offset. * Presumes <code>bytes</code> content starting at <code>offset</code> is * formatted as a KeyValue blob. * @param bytes byte array * @param offset offset to start of KeyValue */ public KeyValue(final byte [] bytes, final int offset) { this(bytes, offset, getLength(bytes, offset)); } /** * Creates a KeyValue from the specified byte array, starting at offset, and * for length <code>length</code>. * @param bytes byte array * @param offset offset to start of the KeyValue * @param length length of the KeyValue */ public KeyValue(final byte [] bytes, final int offset, final int length) { this.bytes = bytes; this.offset = offset; this.length = length; } /** Constructors that build a new backing byte array from fields */ /** * Constructs KeyValue structure filled with null value. * Sets type to {@link KeyValue.Type#Maximum} * @param row - row key (arbitrary byte array) * @param timestamp */ public KeyValue(final byte [] row, final long timestamp) { this(row, timestamp, Type.Maximum); } /** * Constructs KeyValue structure filled with null value. * @param row - row key (arbitrary byte array) * @param timestamp */ public KeyValue(final byte [] row, final long timestamp, Type type) { this(row, null, null, timestamp, type, null); } /** * Constructs KeyValue structure filled with null value. * Sets type to {@link KeyValue.Type#Maximum} * @param row - row key (arbitrary byte array) * @param family family name * @param qualifier column qualifier */ public KeyValue(final byte [] row, final byte [] family, final byte [] qualifier) { this(row, family, qualifier, HConstants.LATEST_TIMESTAMP, Type.Maximum); } /** * Constructs KeyValue structure filled with null value. * @param row - row key (arbitrary byte array) * @param family family name * @param qualifier column qualifier */ public KeyValue(final byte [] row, final byte [] family, final byte [] qualifier, final byte [] value) { this(row, family, qualifier, HConstants.LATEST_TIMESTAMP, Type.Put, value); } /** * Constructs KeyValue structure filled with specified values. * @param row row key * @param family family name * @param qualifier column qualifier * @param timestamp version timestamp * @param type key type * @throws IllegalArgumentException */ public KeyValue(final byte[] row, final byte[] family, final byte[] qualifier, final long timestamp, Type type) { this(row, family, qualifier, timestamp, type, null); } /** * Constructs KeyValue structure filled with specified values. * @param row row key * @param family family name * @param qualifier column qualifier * @param timestamp version timestamp * @param value column value * @throws IllegalArgumentException */ public KeyValue(final byte[] row, final byte[] family, final byte[] qualifier, final long timestamp, final byte[] value) { this(row, family, qualifier, timestamp, Type.Put, value); } /** * Constructs KeyValue structure filled with specified values. * @param row row key * @param family family name * @param qualifier column qualifier * @param timestamp version timestamp * @param type key type * @param value column value * @throws IllegalArgumentException */ public KeyValue(final byte[] row, final byte[] family, final byte[] qualifier, final long timestamp, Type type, final byte[] value) { this(row, family, qualifier, 0, qualifier==null ? 0 : qualifier.length, timestamp, type, value, 0, value==null ? 0 : value.length); } /** * Constructs KeyValue structure filled with specified values. * @param row row key * @param family family name * @param qualifier column qualifier * @param qoffset qualifier offset * @param qlength qualifier length * @param timestamp version timestamp * @param type key type * @param value column value * @param voffset value offset * @param vlength value length * @throws IllegalArgumentException */ public KeyValue(byte [] row, byte [] family, byte [] qualifier, int qoffset, int qlength, long timestamp, Type type, byte [] value, int voffset, int vlength) { this(row, 0, row==null ? 0 : row.length, family, 0, family==null ? 0 : family.length, qualifier, qoffset, qlength, timestamp, type, value, voffset, vlength); } /** * Constructs KeyValue structure filled with specified values. * <p> * Column is split into two fields, family and qualifier. * @param row row key * @param roffset row offset * @param rlength row length * @param family family name * @param foffset family offset * @param flength family length * @param qualifier column qualifier * @param qoffset qualifier offset * @param qlength qualifier length * @param timestamp version timestamp * @param type key type * @param value column value * @param voffset value offset * @param vlength value length * @throws IllegalArgumentException */ public KeyValue(final byte [] row, final int roffset, final int rlength, final byte [] family, final int foffset, final int flength, final byte [] qualifier, final int qoffset, final int qlength, final long timestamp, final Type type, final byte [] value, final int voffset, final int vlength) { this.bytes = createByteArray(row, roffset, rlength, family, foffset, flength, qualifier, qoffset, qlength, timestamp, type, value, voffset, vlength); this.length = bytes.length; this.offset = 0; } /** * Constructs an empty KeyValue structure, with specified sizes. * This can be used to partially fill up KeyValues. * <p> * Column is split into two fields, family and qualifier. * @param rlength row length * @param flength family length * @param qlength qualifier length * @param timestamp version timestamp * @param type key type * @param vlength value length * @throws IllegalArgumentException */ public KeyValue(final int rlength, final int flength, final int qlength, final long timestamp, final Type type, final int vlength) { this.bytes = createEmptyByteArray(rlength, flength, qlength, timestamp, type, vlength); this.length = bytes.length; this.offset = 0; } /** * Create an empty byte[] representing a KeyValue * All lengths are preset and can be filled in later. * @param rlength * @param flength * @param qlength * @param timestamp * @param type * @param vlength * @return The newly created byte array. */ static byte[] createEmptyByteArray(final int rlength, int flength, int qlength, final long timestamp, final Type type, int vlength) { if (rlength > Short.MAX_VALUE) { throw new IllegalArgumentException("Row > " + Short.MAX_VALUE); } if (flength > Byte.MAX_VALUE) { throw new IllegalArgumentException("Family > " + Byte.MAX_VALUE); } // Qualifier length if (qlength > Integer.MAX_VALUE - rlength - flength) { throw new IllegalArgumentException("Qualifier > " + Integer.MAX_VALUE); } // Key length long longkeylength = KEY_INFRASTRUCTURE_SIZE + rlength + flength + qlength; if (longkeylength > Integer.MAX_VALUE) { throw new IllegalArgumentException("keylength " + longkeylength + " > " + Integer.MAX_VALUE); } int keylength = (int)longkeylength; // Value length if (vlength > HConstants.MAXIMUM_VALUE_LENGTH) { // FindBugs INT_VACUOUS_COMPARISON throw new IllegalArgumentException("Valuer > " + HConstants.MAXIMUM_VALUE_LENGTH); } // Allocate right-sized byte array. byte [] bytes = new byte[KEYVALUE_INFRASTRUCTURE_SIZE + keylength + vlength]; // Write the correct size markers int pos = 0; pos = Bytes.putInt(bytes, pos, keylength); pos = Bytes.putInt(bytes, pos, vlength); pos = Bytes.putShort(bytes, pos, (short)(rlength & 0x0000ffff)); pos += rlength; pos = Bytes.putByte(bytes, pos, (byte)(flength & 0x0000ff)); pos += flength + qlength; pos = Bytes.putLong(bytes, pos, timestamp); pos = Bytes.putByte(bytes, pos, type.getCode()); return bytes; } /** * Write KeyValue format into a byte array. * * @param row row key * @param roffset row offset * @param rlength row length * @param family family name * @param foffset family offset * @param flength family length * @param qualifier column qualifier * @param qoffset qualifier offset * @param qlength qualifier length * @param timestamp version timestamp * @param type key type * @param value column value * @param voffset value offset * @param vlength value length * @return The newly created byte array. */ static byte [] createByteArray(final byte [] row, final int roffset, final int rlength, final byte [] family, final int foffset, int flength, final byte [] qualifier, final int qoffset, int qlength, final long timestamp, final Type type, final byte [] value, final int voffset, int vlength) { if (rlength > Short.MAX_VALUE) { throw new IllegalArgumentException("Row > " + Short.MAX_VALUE); } if (row == null) { throw new IllegalArgumentException("Row is null"); } // Family length flength = family == null ? 0 : flength; if (flength > Byte.MAX_VALUE) { throw new IllegalArgumentException("Family > " + Byte.MAX_VALUE); } // Qualifier length qlength = qualifier == null ? 0 : qlength; if (qlength > Integer.MAX_VALUE - rlength - flength) { throw new IllegalArgumentException("Qualifier > " + Integer.MAX_VALUE); } // Key length long longkeylength = KEY_INFRASTRUCTURE_SIZE + rlength + flength + qlength; if (longkeylength > Integer.MAX_VALUE) { throw new IllegalArgumentException("keylength " + longkeylength + " > " + Integer.MAX_VALUE); } int keylength = (int)longkeylength; // Value length vlength = value == null? 0 : vlength; if (vlength > HConstants.MAXIMUM_VALUE_LENGTH) { // FindBugs INT_VACUOUS_COMPARISON throw new IllegalArgumentException("Valuer > " + HConstants.MAXIMUM_VALUE_LENGTH); } // Allocate right-sized byte array. byte [] bytes = new byte[KEYVALUE_INFRASTRUCTURE_SIZE + keylength + vlength]; // Write key, value and key row length. int pos = 0; pos = Bytes.putInt(bytes, pos, keylength); pos = Bytes.putInt(bytes, pos, vlength); pos = Bytes.putShort(bytes, pos, (short)(rlength & 0x0000ffff)); pos = Bytes.putBytes(bytes, pos, row, roffset, rlength); pos = Bytes.putByte(bytes, pos, (byte)(flength & 0x0000ff)); if(flength != 0) { pos = Bytes.putBytes(bytes, pos, family, foffset, flength); } if(qlength != 0) { pos = Bytes.putBytes(bytes, pos, qualifier, qoffset, qlength); } pos = Bytes.putLong(bytes, pos, timestamp); pos = Bytes.putByte(bytes, pos, type.getCode()); if (value != null && value.length > 0) { pos = Bytes.putBytes(bytes, pos, value, voffset, vlength); } return bytes; } /** * Write KeyValue format into a byte array. * <p> * Takes column in the form <code>family:qualifier</code> * @param row - row key (arbitrary byte array) * @param roffset * @param rlength * @param column * @param coffset * @param clength * @param timestamp * @param type * @param value * @param voffset * @param vlength * @return The newly created byte array. */ static byte [] createByteArray(final byte [] row, final int roffset, final int rlength, final byte [] column, final int coffset, int clength, final long timestamp, final Type type, final byte [] value, final int voffset, int vlength) { // If column is non-null, figure where the delimiter is at. int delimiteroffset = 0; if (column != null && column.length > 0) { delimiteroffset = getFamilyDelimiterIndex(column, coffset, clength); if (delimiteroffset > Byte.MAX_VALUE) { throw new IllegalArgumentException("Family > " + Byte.MAX_VALUE); } } else { return createByteArray(row,roffset,rlength,null,0,0,null,0,0,timestamp, type,value,voffset,vlength); } int flength = delimiteroffset-coffset; int qlength = clength - flength - 1; return createByteArray(row, roffset, rlength, column, coffset, flength, column, delimiteroffset+1, qlength, timestamp, type, value, voffset, vlength); } // Needed doing 'contains' on List. Only compares the key portion, not the // value. @Override public boolean equals(Object other) { if (!(other instanceof KeyValue)) { return false; } KeyValue kv = (KeyValue)other; // Comparing bytes should be fine doing equals test. Shouldn't have to // worry about special .META. comparators doing straight equals. return Bytes.equals(getBuffer(), getKeyOffset(), getKeyLength(), kv.getBuffer(), kv.getKeyOffset(), kv.getKeyLength()); } @Override public int hashCode() { byte[] b = getBuffer(); int start = getOffset(), end = getOffset() + getLength(); int h = b[start++]; for (int i = start; i < end; i++) { h = (h * 13) ^ b[i]; } return h; } //--------------------------------------------------------------------------- // // KeyValue cloning // //--------------------------------------------------------------------------- /** * Clones a KeyValue. This creates a copy, re-allocating the buffer. * @return Fully copied clone of this KeyValue */ public KeyValue clone() { byte [] b = new byte[this.length]; System.arraycopy(this.bytes, this.offset, b, 0, this.length); KeyValue ret = new KeyValue(b, 0, b.length); // Important to clone the memstoreTS as well - otherwise memstore's // update-in-place methods (eg increment) will end up creating // new entries ret.setMemstoreTS(memstoreTS); return ret; } /** * Creates a deep copy of this KeyValue, re-allocating the buffer. * Same function as {@link #clone()}. Added for clarity vs shallowCopy() * @return Deep copy of this KeyValue */ public KeyValue deepCopy() { return clone(); } /** * Creates a shallow copy of this KeyValue, reusing the data byte buffer. * http://en.wikipedia.org/wiki/Object_copy * @return Shallow copy of this KeyValue */ public KeyValue shallowCopy() { KeyValue shallowCopy = new KeyValue(this.bytes, this.offset, this.length); shallowCopy.setMemstoreTS(this.memstoreTS); return shallowCopy; } //--------------------------------------------------------------------------- // // String representation // //--------------------------------------------------------------------------- public String toString() { if (this.bytes == null || this.bytes.length == 0) { return "empty"; } return keyToString(this.bytes, this.offset + ROW_OFFSET, getKeyLength()) + "/vlen=" + getValueLength() + "/ts=" + memstoreTS; } /** * @param k Key portion of a KeyValue. * @return Key as a String. */ public static String keyToString(final byte [] k) { if (k == null) { return ""; } return keyToString(k, 0, k.length); } /** * Use for logging. * @param b Key portion of a KeyValue. * @param o Offset to start of key * @param l Length of key. * @return Key as a String. */ /** * Produces a string map for this key/value pair. Useful for programmatic use * and manipulation of the data stored in an HLogKey, for example, printing * as JSON. Values are left out due to their tendency to be large. If needed, * they can be added manually. * * @return the Map<String,?> containing data from this key */ public Map<String, Object> toStringMap() { Map<String, Object> stringMap = new HashMap<String, Object>(); stringMap.put("row", Bytes.toStringBinary(getRow())); stringMap.put("family", Bytes.toStringBinary(getFamily())); stringMap.put("qualifier", Bytes.toStringBinary(getQualifier())); stringMap.put("timestamp", getTimestamp()); stringMap.put("vlen", getValueLength()); return stringMap; } public static String keyToString(final byte [] b, final int o, final int l) { if (b == null) return ""; int rowlength = Bytes.toShort(b, o); String row = Bytes.toStringBinary(b, o + Bytes.SIZEOF_SHORT, rowlength); int columnoffset = o + Bytes.SIZEOF_SHORT + 1 + rowlength; int familylength = b[columnoffset - 1]; int columnlength = l - ((columnoffset - o) + TIMESTAMP_TYPE_SIZE); String family = familylength == 0? "": Bytes.toStringBinary(b, columnoffset, familylength); String qualifier = columnlength == 0? "": Bytes.toStringBinary(b, columnoffset + familylength, columnlength - familylength); long timestamp = Bytes.toLong(b, o + (l - TIMESTAMP_TYPE_SIZE)); String timestampStr = humanReadableTimestamp(timestamp); byte type = b[o + l - 1]; return row + "/" + family + (family != null && family.length() > 0? ":" :"") + qualifier + "/" + timestampStr + "/" + Type.codeToType(type); } public static String humanReadableTimestamp(final long timestamp) { if (timestamp == HConstants.LATEST_TIMESTAMP) { return "LATEST_TIMESTAMP"; } if (timestamp == HConstants.OLDEST_TIMESTAMP) { return "OLDEST_TIMESTAMP"; } return String.valueOf(timestamp); } //--------------------------------------------------------------------------- // // Public Member Accessors // //--------------------------------------------------------------------------- /** * @return The byte array backing this KeyValue. */ public byte [] getBuffer() { return this.bytes; } /** * @return Offset into {@link #getBuffer()} at which this KeyValue starts. */ public int getOffset() { return this.offset; } /** * @return Length of bytes this KeyValue occupies in {@link #getBuffer()}. */ public int getLength() { return length; } //--------------------------------------------------------------------------- // // Length and Offset Calculators // //--------------------------------------------------------------------------- /** * Determines the total length of the KeyValue stored in the specified * byte array and offset. Includes all headers. * @param bytes byte array * @param offset offset to start of the KeyValue * @return length of entire KeyValue, in bytes */ private static int getLength(byte [] bytes, int offset) { return ROW_OFFSET + Bytes.toInt(bytes, offset) + Bytes.toInt(bytes, offset + Bytes.SIZEOF_INT); } /** * @return Key offset in backing buffer.. */ public int getKeyOffset() { return this.offset + ROW_OFFSET; } public String getKeyString() { return Bytes.toStringBinary(getBuffer(), getKeyOffset(), getKeyLength()); } /** * @return Length of key portion. */ public int getKeyLength() { return Bytes.toInt(this.bytes, this.offset); } /** * @return Value offset */ public int getValueOffset() { return getKeyOffset() + getKeyLength(); } /** * @return Value length */ public int getValueLength() { return Bytes.toInt(this.bytes, this.offset + Bytes.SIZEOF_INT); } /** * @return Row offset */ public int getRowOffset() { return getKeyOffset() + Bytes.SIZEOF_SHORT; } /** * @return Row length */ public short getRowLength() { return Bytes.toShort(this.bytes, getKeyOffset()); } /** * @return Family offset */ public int getFamilyOffset() { return getFamilyOffset(getRowLength()); } /** * @return Family offset */ public int getFamilyOffset(int rlength) { return this.offset + ROW_OFFSET + Bytes.SIZEOF_SHORT + rlength + Bytes.SIZEOF_BYTE; } /** * @return Family length */ public byte getFamilyLength() { return getFamilyLength(getFamilyOffset()); } /** * @return Family length */ public byte getFamilyLength(int foffset) { return this.bytes[foffset-1]; } /** * @return Qualifier offset */ public int getQualifierOffset() { return getQualifierOffset(getFamilyOffset()); } /** * @return Qualifier offset */ public int getQualifierOffset(int foffset) { return foffset + getFamilyLength(foffset); } /** * @return Qualifier length */ public int getQualifierLength() { return getQualifierLength(getRowLength(),getFamilyLength()); } /** * @return Qualifier length */ public int getQualifierLength(int rlength, int flength) { return getKeyLength() - (KEY_INFRASTRUCTURE_SIZE + rlength + flength); } /** * @return Column (family + qualifier) length */ public int getTotalColumnLength() { int rlength = getRowLength(); int foffset = getFamilyOffset(rlength); return getTotalColumnLength(rlength,foffset); } /** * @return Column (family + qualifier) length */ public int getTotalColumnLength(int rlength, int foffset) { int flength = getFamilyLength(foffset); int qlength = getQualifierLength(rlength,flength); return flength + qlength; } /** * @return Timestamp offset */ public int getTimestampOffset() { return getTimestampOffset(getKeyLength()); } /** * @param keylength Pass if you have it to save on a int creation. * @return Timestamp offset */ public int getTimestampOffset(final int keylength) { return getKeyOffset() + keylength - TIMESTAMP_TYPE_SIZE; } /** * @return True if this KeyValue has a LATEST_TIMESTAMP timestamp. */ public boolean isLatestTimestamp() { return Bytes.equals(getBuffer(), getTimestampOffset(), Bytes.SIZEOF_LONG, HConstants.LATEST_TIMESTAMP_BYTES, 0, Bytes.SIZEOF_LONG); } /** * @return True if this is a "fake" KV created for internal seeking purposes, * which should not be seen by user code */ public boolean isInternal() { byte type = getType(); return type == Type.Minimum.code || type == Type.Maximum.code; } /** * @param now Time to set into <code>this</code> IFF timestamp == * {@link HConstants#LATEST_TIMESTAMP} (else, its a noop). * @return True is we modified this. */ public boolean updateLatestStamp(final byte [] now) { if (this.isLatestTimestamp()) { int tsOffset = getTimestampOffset(); System.arraycopy(now, 0, this.bytes, tsOffset, Bytes.SIZEOF_LONG); // clear cache or else getTimestamp() possibly returns an old value return true; } return false; } //--------------------------------------------------------------------------- // // Methods that return copies of fields // //--------------------------------------------------------------------------- /** * Do not use unless you have to. Used internally for compacting and testing. * * Use {@link #getRow()}, {@link #getFamily()}, {@link #getQualifier()}, and * {@link #getValue()} if accessing a KeyValue client-side. * @return Copy of the key portion only. */ public byte [] getKey() { int keylength = getKeyLength(); byte [] key = new byte[keylength]; System.arraycopy(getBuffer(), getKeyOffset(), key, 0, keylength); return key; } /** * Returns value in a new byte array. * Primarily for use client-side. If server-side, use * {@link #getBuffer()} with appropriate offsets and lengths instead to * save on allocations. * @return Value in a new byte array. */ public byte [] getValue() { int o = getValueOffset(); int l = getValueLength(); byte [] result = new byte[l]; System.arraycopy(getBuffer(), o, result, 0, l); return result; } /** * Primarily for use client-side. Returns the row of this KeyValue in a new * byte array.<p> * * If server-side, use {@link #getBuffer()} with appropriate offsets and * lengths instead. * @return Row in a new byte array. */ public byte [] getRow() { int o = getRowOffset(); short l = getRowLength(); byte result[] = new byte[l]; System.arraycopy(getBuffer(), o, result, 0, l); return result; } /** * * @return Timestamp */ public long getTimestamp() { return getTimestamp(getKeyLength()); } /** * @param keylength Pass if you have it to save on a int creation. * @return Timestamp */ long getTimestamp(final int keylength) { int tsOffset = getTimestampOffset(keylength); return Bytes.toLong(this.bytes, tsOffset); } /** * @return Type of this KeyValue. */ public byte getType() { return getType(getKeyLength()); } /** * @param keylength Pass if you have it to save on a int creation. * @return Type of this KeyValue. */ byte getType(final int keylength) { return this.bytes[this.offset + keylength - 1 + ROW_OFFSET]; } /** * @return True if a delete type, a {@link KeyValue.Type#Delete} or * a {KeyValue.Type#DeleteFamily} or a {@link KeyValue.Type#DeleteColumn} * KeyValue type. */ public boolean isDelete() { return KeyValue.isDelete(getType()); } /** * @return True if this KV is a {@link KeyValue.Type#Delete} type. */ public boolean isDeleteType() { // TODO: Fix this method name vis-a-vis isDelete! return getType() == Type.Delete.getCode(); } /** * @return True if this KV is a delete family type. */ public boolean isDeleteFamily() { return getType() == Type.DeleteFamily.getCode(); } /** * * @return True if this KV is a delete family or column type. */ public boolean isDeleteColumnOrFamily() { int t = getType(); return t == Type.DeleteColumn.getCode() || t == Type.DeleteFamily.getCode(); } /** * Primarily for use client-side. Returns the family of this KeyValue in a * new byte array.<p> * * If server-side, use {@link #getBuffer()} with appropriate offsets and * lengths instead. * @return Returns family. Makes a copy. */ public byte [] getFamily() { int o = getFamilyOffset(); int l = getFamilyLength(o); byte [] result = new byte[l]; System.arraycopy(this.bytes, o, result, 0, l); return result; } /** * Primarily for use client-side. Returns the column qualifier of this * KeyValue in a new byte array.<p> * * If server-side, use {@link #getBuffer()} with appropriate offsets and * lengths instead. * Use {@link #getBuffer()} with appropriate offsets and lengths instead. * @return Returns qualifier. Makes a copy. */ public byte [] getQualifier() { int o = getQualifierOffset(); int l = getQualifierLength(); byte [] result = new byte[l]; System.arraycopy(this.bytes, o, result, 0, l); return result; } //--------------------------------------------------------------------------- // // KeyValue splitter // //--------------------------------------------------------------------------- /** * Utility class that splits a KeyValue buffer into separate byte arrays. * <p> * Should get rid of this if we can, but is very useful for debugging. */ public static class SplitKeyValue { private byte [][] split; SplitKeyValue() { this.split = new byte[6][]; } public void setRow(byte [] value) { this.split[0] = value; } public void setFamily(byte [] value) { this.split[1] = value; } public void setQualifier(byte [] value) { this.split[2] = value; } public void setTimestamp(byte [] value) { this.split[3] = value; } public void setType(byte [] value) { this.split[4] = value; } public void setValue(byte [] value) { this.split[5] = value; } public byte [] getRow() { return this.split[0]; } public byte [] getFamily() { return this.split[1]; } public byte [] getQualifier() { return this.split[2]; } public byte [] getTimestamp() { return this.split[3]; } public byte [] getType() { return this.split[4]; } public byte [] getValue() { return this.split[5]; } } public SplitKeyValue split() { SplitKeyValue split = new SplitKeyValue(); int splitOffset = this.offset; int keyLen = Bytes.toInt(bytes, splitOffset); splitOffset += Bytes.SIZEOF_INT; int valLen = Bytes.toInt(bytes, splitOffset); splitOffset += Bytes.SIZEOF_INT; short rowLen = Bytes.toShort(bytes, splitOffset); splitOffset += Bytes.SIZEOF_SHORT; byte [] row = new byte[rowLen]; System.arraycopy(bytes, splitOffset, row, 0, rowLen); splitOffset += rowLen; split.setRow(row); byte famLen = bytes[splitOffset]; splitOffset += Bytes.SIZEOF_BYTE; byte [] family = new byte[famLen]; System.arraycopy(bytes, splitOffset, family, 0, famLen); splitOffset += famLen; split.setFamily(family); int colLen = keyLen - (rowLen + famLen + Bytes.SIZEOF_SHORT + Bytes.SIZEOF_BYTE + Bytes.SIZEOF_LONG + Bytes.SIZEOF_BYTE); byte [] qualifier = new byte[colLen]; System.arraycopy(bytes, splitOffset, qualifier, 0, colLen); splitOffset += colLen; split.setQualifier(qualifier); byte [] timestamp = new byte[Bytes.SIZEOF_LONG]; System.arraycopy(bytes, splitOffset, timestamp, 0, Bytes.SIZEOF_LONG); splitOffset += Bytes.SIZEOF_LONG; split.setTimestamp(timestamp); byte [] type = new byte[1]; type[0] = bytes[splitOffset]; splitOffset += Bytes.SIZEOF_BYTE; split.setType(type); byte [] value = new byte[valLen]; System.arraycopy(bytes, splitOffset, value, 0, valLen); split.setValue(value); return split; } //--------------------------------------------------------------------------- // // Compare specified fields against those contained in this KeyValue // //--------------------------------------------------------------------------- /** * @param family * @return True if matching families. */ public boolean matchingFamily(final byte [] family) { return matchingFamily(family, 0, family.length); } public boolean matchingFamily(final byte[] family, int offset, int length) { if (this.length == 0 || this.bytes.length == 0) { return false; } return Bytes.equals(family, offset, length, this.bytes, getFamilyOffset(), getFamilyLength()); } public boolean matchingFamily(final KeyValue other) { return matchingFamily(other.getBuffer(), other.getFamilyOffset(), other.getFamilyLength()); } /** * @param qualifier * @return True if matching qualifiers. */ public boolean matchingQualifier(final byte [] qualifier) { return matchingQualifier(qualifier, 0, qualifier.length); } public boolean matchingQualifier(final byte [] qualifier, int offset, int length) { return Bytes.equals(qualifier, offset, length, this.bytes, getQualifierOffset(), getQualifierLength()); } public boolean matchingQualifier(final KeyValue other) { return matchingQualifier(other.getBuffer(), other.getQualifierOffset(), other.getQualifierLength()); } public boolean matchingRow(final byte [] row) { return matchingRow(row, 0, row.length); } public boolean matchingRow(final byte[] row, int offset, int length) { return Bytes.equals(row, offset, length, this.bytes, getRowOffset(), getRowLength()); } public boolean matchingRow(KeyValue other) { return matchingRow(other.getBuffer(), other.getRowOffset(), other.getRowLength()); } /** * @param column Column minus its delimiter * @return True if column matches. */ public boolean matchingColumnNoDelimiter(final byte [] column) { int rl = getRowLength(); int o = getFamilyOffset(rl); int fl = getFamilyLength(o); int l = fl + getQualifierLength(rl,fl); return Bytes.equals(column, 0, column.length, this.bytes, o, l); } /** * * @param family column family * @param qualifier column qualifier * @return True if column matches */ public boolean matchingColumn(final byte[] family, final byte[] qualifier) { int rl = getRowLength(); int o = getFamilyOffset(rl); int fl = getFamilyLength(o); int ql = getQualifierLength(rl,fl); if (!Bytes.equals(family, 0, family.length, this.bytes, o, fl)) { return false; } if (qualifier == null || qualifier.length == 0) { if (ql == 0) { return true; } return false; } return Bytes.equals(qualifier, 0, qualifier.length, this.bytes, o + fl, ql); } /** * @param left * @param loffset * @param llength * @param lfamilylength Offset of family delimiter in left column. * @param right * @param roffset * @param rlength * @param rfamilylength Offset of family delimiter in right column. * @return The result of the comparison. */ static int compareColumns(final byte [] left, final int loffset, final int llength, final int lfamilylength, final byte [] right, final int roffset, final int rlength, final int rfamilylength) { // Compare family portion first. int diff = Bytes.compareTo(left, loffset, lfamilylength, right, roffset, rfamilylength); if (diff != 0) { return diff; } // Compare qualifier portion return Bytes.compareTo(left, loffset + lfamilylength, llength - lfamilylength, right, roffset + rfamilylength, rlength - rfamilylength); } /** * @return True if non-null row and column. */ public boolean nonNullRowAndColumn() { return getRowLength() > 0 && !isEmptyColumn(); } /** * @return True if column is empty. */ public boolean isEmptyColumn() { return getQualifierLength() == 0; } /** * Creates a new KeyValue that only contains the key portion (the value is * set to be null). * @param lenAsVal replace value with the actual value length (false=empty) */ public KeyValue createKeyOnly(boolean lenAsVal) { // KV format: <keylen:4><valuelen:4><key:keylen><value:valuelen> // Rebuild as: <keylen:4><0:4><key:keylen> int dataLen = lenAsVal? Bytes.SIZEOF_INT : 0; byte [] newBuffer = new byte[getKeyLength() + ROW_OFFSET + dataLen]; System.arraycopy(this.bytes, this.offset, newBuffer, 0, Math.min(newBuffer.length,this.length)); Bytes.putInt(newBuffer, Bytes.SIZEOF_INT, dataLen); if (lenAsVal) { Bytes.putInt(newBuffer, newBuffer.length - dataLen, this.getValueLength()); } return new KeyValue(newBuffer); } /** * Splits a column in family:qualifier form into separate byte arrays. * <p> * Not recommend to be used as this is old-style API. * @param c The column. * @return The parsed column. */ public static byte [][] parseColumn(byte [] c) { final int index = getDelimiter(c, 0, c.length, COLUMN_FAMILY_DELIMITER); if (index == -1) { // If no delimiter, return array of size 1 return new byte [][] { c }; } else if(index == c.length - 1) { // Only a family, return array size 1 byte [] family = new byte[c.length-1]; System.arraycopy(c, 0, family, 0, family.length); return new byte [][] { family }; } // Family and column, return array size 2 final byte [][] result = new byte [2][]; result[0] = new byte [index]; System.arraycopy(c, 0, result[0], 0, index); final int len = c.length - (index + 1); result[1] = new byte[len]; System.arraycopy(c, index + 1 /*Skip delimiter*/, result[1], 0, len); return result; } /** * Makes a column in family:qualifier form from separate byte arrays. * <p> * Not recommended for usage as this is old-style API. * @param family * @param qualifier * @return family:qualifier */ public static byte [] makeColumn(byte [] family, byte [] qualifier) { return Bytes.add(family, COLUMN_FAMILY_DELIM_ARRAY, qualifier); } /** * @param b * @return Index of the family-qualifier colon delimiter character in passed * buffer. */ public static int getFamilyDelimiterIndex(final byte [] b, final int offset, final int length) { return getRequiredDelimiter(b, offset, length, COLUMN_FAMILY_DELIMITER); } private static int getRequiredDelimiter(final byte [] b, final int offset, final int length, final int delimiter) { int index = getDelimiter(b, offset, length, delimiter); if (index < 0) { throw new IllegalArgumentException("No " + (char)delimiter + " in <" + Bytes.toString(b) + ">" + ", length=" + length + ", offset=" + offset); } return index; } /** * This function is only used in Meta key comparisons so its error message * is specific for meta key errors. */ static int getRequiredDelimiterInReverse(final byte [] b, final int offset, final int length, final int delimiter) { int index = getDelimiterInReverse(b, offset, length, delimiter); if (index < 0) { throw new IllegalArgumentException(".META. key must have two '" + (char)delimiter + "' " + "delimiters and have the following format: '<table>,<key>,<etc>'"); } return index; } /** * @param b * @param delimiter * @return Index of delimiter having started from start of <code>b</code> * moving rightward. */ public static int getDelimiter(final byte [] b, int offset, final int length, final int delimiter) { if (b == null) { throw new IllegalArgumentException("Passed buffer is null"); } int result = -1; for (int i = offset; i < length + offset; i++) { if (b[i] == delimiter) { result = i; break; } } return result; } /** * Find index of passed delimiter walking from end of buffer backwards. * @param b * @param delimiter * @return Index of delimiter */ public static int getDelimiterInReverse(final byte [] b, final int offset, final int length, final int delimiter) { if (b == null) { throw new IllegalArgumentException("Passed buffer is null"); } int result = -1; for (int i = (offset + length) - 1; i >= offset; i--) { if (b[i] == delimiter) { result = i; break; } } return result; } /** * A {@link KVComparator} for <code>-ROOT-</code> catalog table * {@link KeyValue}s. */ public static class RootComparator extends MetaComparator { private final KeyComparator rawcomparator = new RootKeyComparator(); public KeyComparator getRawComparator() { return this.rawcomparator; } @Override protected Object clone() throws CloneNotSupportedException { return new RootComparator(); } } /** * A {@link KVComparator} for <code>.META.</code> catalog table * {@link KeyValue}s. */ public static class MetaComparator extends KVComparator { private final KeyComparator rawcomparator = new MetaKeyComparator(); public KeyComparator getRawComparator() { return this.rawcomparator; } @Override protected Object clone() throws CloneNotSupportedException { return new MetaComparator(); } } /** * Compare KeyValues. When we compare KeyValues, we only compare the Key * portion. This means two KeyValues with same Key but different Values are * considered the same as far as this Comparator is concerned. * Hosts a {@link KeyComparator}. */ public static class KVComparator implements java.util.Comparator<KeyValue> { private final KeyComparator rawcomparator = new KeyComparator(); /** * @return RawComparator that can compare the Key portion of a KeyValue. * Used in hfile where indices are the Key portion of a KeyValue. */ public KeyComparator getRawComparator() { return this.rawcomparator; } public int compare(final KeyValue left, final KeyValue right) { int ret = getRawComparator().compare(left.getBuffer(), left.getOffset() + ROW_OFFSET, left.getKeyLength(), right.getBuffer(), right.getOffset() + ROW_OFFSET, right.getKeyLength()); if (ret != 0) return ret; // Negate this comparison so later edits show up first return -Longs.compare(left.getMemstoreTS(), right.getMemstoreTS()); } public int compareTimestamps(final KeyValue left, final KeyValue right) { return compareTimestamps(left, left.getKeyLength(), right, right.getKeyLength()); } int compareTimestamps(final KeyValue left, final int lkeylength, final KeyValue right, final int rkeylength) { // Compare timestamps long ltimestamp = left.getTimestamp(lkeylength); long rtimestamp = right.getTimestamp(rkeylength); return getRawComparator().compareTimestamps(ltimestamp, rtimestamp); } /** * @param left * @param right * @return Result comparing rows. */ public int compareRows(final KeyValue left, final KeyValue right) { return compareRows(left, left.getRowLength(), right, right.getRowLength()); } /** * @param left * @param lrowlength Length of left row. * @param right * @param rrowlength Length of right row. * @return Result comparing rows. */ public int compareRows(final KeyValue left, final short lrowlength, final KeyValue right, final short rrowlength) { return getRawComparator().compareRows(left.getBuffer(), left.getRowOffset(), lrowlength, right.getBuffer(), right.getRowOffset(), rrowlength); } /** * @param left * @param row - row key (arbitrary byte array) * @return RawComparator */ public int compareRows(final KeyValue left, final byte [] row) { return getRawComparator().compareRows(left.getBuffer(), left.getRowOffset(), left.getRowLength(), row, 0, row.length); } public int compareRows(byte [] left, int loffset, int llength, byte [] right, int roffset, int rlength) { return getRawComparator().compareRows(left, loffset, llength, right, roffset, rlength); } public int compareColumns(final KeyValue left, final byte [] right, final int roffset, final int rlength, final int rfamilyoffset) { int offset = left.getFamilyOffset(); int length = left.getFamilyLength() + left.getQualifierLength(); return getRawComparator().compareColumns(left.getBuffer(), offset, length, left.getFamilyLength(offset), right, roffset, rlength, rfamilyoffset); } int compareColumns(final KeyValue left, final short lrowlength, final KeyValue right, final short rrowlength) { int lfoffset = left.getFamilyOffset(lrowlength); int rfoffset = right.getFamilyOffset(rrowlength); int lclength = left.getTotalColumnLength(lrowlength,lfoffset); int rclength = right.getTotalColumnLength(rrowlength, rfoffset); int lfamilylength = left.getFamilyLength(lfoffset); int rfamilylength = right.getFamilyLength(rfoffset); return getRawComparator().compareColumns(left.getBuffer(), lfoffset, lclength, lfamilylength, right.getBuffer(), rfoffset, rclength, rfamilylength); } /** * Compares the row and column of two keyvalues for equality * @param left * @param right * @return True if same row and column. */ public boolean matchingRowColumn(final KeyValue left, final KeyValue right) { short lrowlength = left.getRowLength(); short rrowlength = right.getRowLength(); // TsOffset = end of column data. just comparing Row+CF length of each return ((left.getTimestampOffset() - left.getOffset()) == (right.getTimestampOffset() - right.getOffset())) && matchingRows(left, lrowlength, right, rrowlength) && compareColumns(left, lrowlength, right, rrowlength) == 0; } /** * @param left * @param right * @return True if rows match. */ public boolean matchingRows(final KeyValue left, final byte [] right) { return Bytes.equals(left.getBuffer(), left.getRowOffset(), left.getRowLength(), right, 0, right.length); } /** * Compares the row of two keyvalues for equality * @param left * @param right * @return True if rows match. */ public boolean matchingRows(final KeyValue left, final KeyValue right) { short lrowlength = left.getRowLength(); short rrowlength = right.getRowLength(); return matchingRows(left, lrowlength, right, rrowlength); } /** * @param left * @param lrowlength * @param right * @param rrowlength * @return True if rows match. */ public boolean matchingRows(final KeyValue left, final short lrowlength, final KeyValue right, final short rrowlength) { return lrowlength == rrowlength && Bytes.equals(left.getBuffer(), left.getRowOffset(), lrowlength, right.getBuffer(), right.getRowOffset(), rrowlength); } public boolean matchingRows(final byte [] left, final int loffset, final int llength, final byte [] right, final int roffset, final int rlength) { return Bytes.equals(left, loffset, llength, right, roffset, rlength); } /** * Compares the row and timestamp of two keys * Was called matchesWithoutColumn in HStoreKey. * @param right Key to compare against. * @return True if same row and timestamp is greater than the timestamp in * <code>right</code> */ public boolean matchingRowsGreaterTimestamp(final KeyValue left, final KeyValue right) { short lrowlength = left.getRowLength(); short rrowlength = right.getRowLength(); if (!matchingRows(left, lrowlength, right, rrowlength)) { return false; } return left.getTimestamp() >= right.getTimestamp(); } @Override protected Object clone() throws CloneNotSupportedException { return new KVComparator(); } /** * @return Comparator that ignores timestamps; useful counting versions. */ public KVComparator getComparatorIgnoringTimestamps() { KVComparator c = null; try { c = (KVComparator)this.clone(); c.getRawComparator().ignoreTimestamp = true; } catch (CloneNotSupportedException e) { LOG.error("Not supported", e); } return c; } /** * @return Comparator that ignores key type; useful checking deletes */ public KVComparator getComparatorIgnoringType() { KVComparator c = null; try { c = (KVComparator)this.clone(); c.getRawComparator().ignoreType = true; } catch (CloneNotSupportedException e) { LOG.error("Not supported", e); } return c; } } /** * Creates a KeyValue that is last on the specified row id. That is, * every other possible KeyValue for the given row would compareTo() * less than the result of this call. * @param row row key * @return Last possible KeyValue on passed <code>row</code> */ public static KeyValue createLastOnRow(final byte[] row) { return new KeyValue(row, null, null, HConstants.LATEST_TIMESTAMP, Type.Minimum); } /** * Create a KeyValue that is smaller than all other possible KeyValues * for the given row. That is any (valid) KeyValue on 'row' would sort * _after_ the result. * * @param row - row key (arbitrary byte array) * @return First possible KeyValue on passed <code>row</code> */ public static KeyValue createFirstOnRow(final byte [] row) { return createFirstOnRow(row, HConstants.LATEST_TIMESTAMP); } /** * Create a KeyValue that is smaller than all other possible KeyValues * for the given row. That is any (valid) KeyValue on 'row' would sort * _after_ the result. * * @param row - row key (arbitrary byte array) * @return First possible KeyValue on passed <code>row</code> */ public static KeyValue createFirstOnRow(final byte [] row, int roffset, short rlength) { return new KeyValue(row, roffset, rlength, null, 0, 0, null, 0, 0, HConstants.LATEST_TIMESTAMP, Type.Maximum, null, 0, 0); } /** * Creates a KeyValue that is smaller than all other KeyValues that * are older than the passed timestamp. * @param row - row key (arbitrary byte array) * @param ts - timestamp * @return First possible key on passed <code>row</code> and timestamp. */ public static KeyValue createFirstOnRow(final byte [] row, final long ts) { return new KeyValue(row, null, null, ts, Type.Maximum); } /** * Create a KeyValue for the specified row, family and qualifier that would be * smaller than all other possible KeyValues that have the same row,family,qualifier. * Used for seeking. * @param row - row key (arbitrary byte array) * @param family - family name * @param qualifier - column qualifier * @return First possible key on passed <code>row</code>, and column. */ public static KeyValue createFirstOnRow(final byte [] row, final byte [] family, final byte [] qualifier) { return new KeyValue(row, family, qualifier, HConstants.LATEST_TIMESTAMP, Type.Maximum); } /** * Create a Delete Family KeyValue for the specified row and family that would * be smaller than all other possible Delete Family KeyValues that have the * same row and family. * Used for seeking. * @param row - row key (arbitrary byte array) * @param family - family name * @return First Delete Family possible key on passed <code>row</code>. */ public static KeyValue createFirstDeleteFamilyOnRow(final byte [] row, final byte [] family) { return new KeyValue(row, family, null, HConstants.LATEST_TIMESTAMP, Type.DeleteFamily); } /** * @param row - row key (arbitrary byte array) * @param f - family name * @param q - column qualifier * @param ts - timestamp * @return First possible key on passed <code>row</code>, column and timestamp */ public static KeyValue createFirstOnRow(final byte [] row, final byte [] f, final byte [] q, final long ts) { return new KeyValue(row, f, q, ts, Type.Maximum); } /** * Create a KeyValue for the specified row, family and qualifier that would be * smaller than all other possible KeyValues that have the same row, * family, qualifier. * Used for seeking. * @param row row key * @param roffset row offset * @param rlength row length * @param family family name * @param foffset family offset * @param flength family length * @param qualifier column qualifier * @param qoffset qualifier offset * @param qlength qualifier length * @return First possible key on passed Row, Family, Qualifier. */ public static KeyValue createFirstOnRow(final byte [] row, final int roffset, final int rlength, final byte [] family, final int foffset, final int flength, final byte [] qualifier, final int qoffset, final int qlength) { return new KeyValue(row, roffset, rlength, family, foffset, flength, qualifier, qoffset, qlength, HConstants.LATEST_TIMESTAMP, Type.Maximum, null, 0, 0); } /** * Create a KeyValue for the specified row, family and qualifier that would be * larger than or equal to all other possible KeyValues that have the same * row, family, qualifier. * Used for reseeking. * @param row row key * @param roffset row offset * @param rlength row length * @param family family name * @param foffset family offset * @param flength family length * @param qualifier column qualifier * @param qoffset qualifier offset * @param qlength qualifier length * @return Last possible key on passed row, family, qualifier. */ public static KeyValue createLastOnRow(final byte [] row, final int roffset, final int rlength, final byte [] family, final int foffset, final int flength, final byte [] qualifier, final int qoffset, final int qlength) { return new KeyValue(row, roffset, rlength, family, foffset, flength, qualifier, qoffset, qlength, HConstants.OLDEST_TIMESTAMP, Type.Minimum, null, 0, 0); } /** * Similar to {@link #createLastOnRow(byte[], int, int, byte[], int, int, * byte[], int, int)} but creates the last key on the row/column of this KV * (the value part of the returned KV is always empty). Used in creating * "fake keys" for the multi-column Bloom filter optimization to skip the * row/column we already know is not in the file. * @return the last key on the row/column of the given key-value pair */ public KeyValue createLastOnRowCol() { return new KeyValue( bytes, getRowOffset(), getRowLength(), bytes, getFamilyOffset(), getFamilyLength(), bytes, getQualifierOffset(), getQualifierLength(), HConstants.OLDEST_TIMESTAMP, Type.Minimum, null, 0, 0); } /** * Creates the first KV with the row/family/qualifier of this KV and the * given timestamp. Uses the "maximum" KV type that guarantees that the new * KV is the lowest possible for this combination of row, family, qualifier, * and timestamp. This KV's own timestamp is ignored. While this function * copies the value from this KV, it is normally used on key-only KVs. */ public KeyValue createFirstOnRowColTS(long ts) { return new KeyValue( bytes, getRowOffset(), getRowLength(), bytes, getFamilyOffset(), getFamilyLength(), bytes, getQualifierOffset(), getQualifierLength(), ts, Type.Maximum, bytes, getValueOffset(), getValueLength()); } /** * @param b * @return A KeyValue made of a byte array that holds the key-only part. * Needed to convert hfile index members to KeyValues. */ public static KeyValue createKeyValueFromKey(final byte [] b) { return createKeyValueFromKey(b, 0, b.length); } /** * @param bb * @return A KeyValue made of a byte buffer that holds the key-only part. * Needed to convert hfile index members to KeyValues. */ public static KeyValue createKeyValueFromKey(final ByteBuffer bb) { return createKeyValueFromKey(bb.array(), bb.arrayOffset(), bb.limit()); } /** * @param b * @param o * @param l * @return A KeyValue made of a byte array that holds the key-only part. * Needed to convert hfile index members to KeyValues. */ public static KeyValue createKeyValueFromKey(final byte [] b, final int o, final int l) { byte [] newb = new byte[l + ROW_OFFSET]; System.arraycopy(b, o, newb, ROW_OFFSET, l); Bytes.putInt(newb, 0, l); Bytes.putInt(newb, Bytes.SIZEOF_INT, 0); return new KeyValue(newb); } /** * Compare key portion of a {@link KeyValue} for keys in <code>-ROOT-<code> * table. */ public static class RootKeyComparator extends MetaKeyComparator { public int compareRows(byte [] left, int loffset, int llength, byte [] right, int roffset, int rlength) { // Rows look like this: .META.,ROW_FROM_META,RID // LOG.info("ROOT " + Bytes.toString(left, loffset, llength) + // "---" + Bytes.toString(right, roffset, rlength)); final int metalength = 7; // '.META.' length int lmetaOffsetPlusDelimiter = loffset + metalength; int leftFarDelimiter = getDelimiterInReverse(left, lmetaOffsetPlusDelimiter, llength - metalength, HRegionInfo.DELIMITER); int rmetaOffsetPlusDelimiter = roffset + metalength; int rightFarDelimiter = getDelimiterInReverse(right, rmetaOffsetPlusDelimiter, rlength - metalength, HRegionInfo.DELIMITER); if (leftFarDelimiter < 0 && rightFarDelimiter >= 0) { // Nothing between .META. and regionid. Its first key. return -1; } else if (rightFarDelimiter < 0 && leftFarDelimiter >= 0) { return 1; } else if (leftFarDelimiter < 0 && rightFarDelimiter < 0) { return 0; } int result = super.compareRows(left, lmetaOffsetPlusDelimiter, leftFarDelimiter - lmetaOffsetPlusDelimiter, right, rmetaOffsetPlusDelimiter, rightFarDelimiter - rmetaOffsetPlusDelimiter); if (result != 0) { return result; } // Compare last part of row, the rowid. leftFarDelimiter++; rightFarDelimiter++; result = compareRowid(left, leftFarDelimiter, llength - (leftFarDelimiter - loffset), right, rightFarDelimiter, rlength - (rightFarDelimiter - roffset)); return result; } } /** * Comparator that compares row component only of a KeyValue. */ public static class RowComparator implements Comparator<KeyValue> { final KVComparator comparator; public RowComparator(final KVComparator c) { this.comparator = c; } public int compare(KeyValue left, KeyValue right) { return comparator.compareRows(left, right); } } /** * Compare key portion of a {@link KeyValue} for keys in <code>.META.</code> * table. */ public static class MetaKeyComparator extends KeyComparator { public int compareRows(byte [] left, int loffset, int llength, byte [] right, int roffset, int rlength) { // LOG.info("META " + Bytes.toString(left, loffset, llength) + // "---" + Bytes.toString(right, roffset, rlength)); int leftDelimiter = getDelimiter(left, loffset, llength, HRegionInfo.DELIMITER); int rightDelimiter = getDelimiter(right, roffset, rlength, HRegionInfo.DELIMITER); if (leftDelimiter < 0 && rightDelimiter >= 0) { // Nothing between .META. and regionid. Its first key. return -1; } else if (rightDelimiter < 0 && leftDelimiter >= 0) { return 1; } else if (leftDelimiter < 0 && rightDelimiter < 0) { return 0; } // Compare up to the delimiter int result = Bytes.compareTo(left, loffset, leftDelimiter - loffset, right, roffset, rightDelimiter - roffset); if (result != 0) { return result; } // Compare middle bit of the row. // Move past delimiter leftDelimiter++; rightDelimiter++; int leftFarDelimiter = getRequiredDelimiterInReverse(left, leftDelimiter, llength - (leftDelimiter - loffset), HRegionInfo.DELIMITER); int rightFarDelimiter = getRequiredDelimiterInReverse(right, rightDelimiter, rlength - (rightDelimiter - roffset), HRegionInfo.DELIMITER); // Now compare middlesection of row. result = super.compareRows(left, leftDelimiter, leftFarDelimiter - leftDelimiter, right, rightDelimiter, rightFarDelimiter - rightDelimiter); if (result != 0) { return result; } // Compare last part of row, the rowid. leftFarDelimiter++; rightFarDelimiter++; result = compareRowid(left, leftFarDelimiter, llength - (leftFarDelimiter - loffset), right, rightFarDelimiter, rlength - (rightFarDelimiter - roffset)); return result; } protected int compareRowid(byte[] left, int loffset, int llength, byte[] right, int roffset, int rlength) { return Bytes.compareTo(left, loffset, llength, right, roffset, rlength); } } /** * Avoids redundant comparisons for better performance. */ public static interface SamePrefixComparator<T> { /** * Compare two keys assuming that the first n bytes are the same. * @param commonPrefix How many bytes are the same. */ public int compareIgnoringPrefix(int commonPrefix, T left, int loffset, int llength, T right, int roffset, int rlength); } /** * Compare key portion of a {@link KeyValue}. */ public static class KeyComparator implements RawComparator<byte []>, SamePrefixComparator<byte[]> { volatile boolean ignoreTimestamp = false; volatile boolean ignoreType = false; public int compare(byte[] left, int loffset, int llength, byte[] right, int roffset, int rlength) { // Compare row short lrowlength = Bytes.toShort(left, loffset); short rrowlength = Bytes.toShort(right, roffset); int compare = compareRows(left, loffset + Bytes.SIZEOF_SHORT, lrowlength, right, roffset + Bytes.SIZEOF_SHORT, rrowlength); if (compare != 0) { return compare; } // Compare the rest of the two KVs without making any assumptions about // the common prefix. This function will not compare rows anyway, so we // don't need to tell it that the common prefix includes the row. return compareWithoutRow(0, left, loffset, llength, right, roffset, rlength, rrowlength); } /** * Compare the two key-values, ignoring the prefix of the given length * that is known to be the same between the two. * @param commonPrefix the prefix length to ignore */ @Override public int compareIgnoringPrefix(int commonPrefix, byte[] left, int loffset, int llength, byte[] right, int roffset, int rlength) { // Compare row short lrowlength = Bytes.toShort(left, loffset); short rrowlength; int comparisonResult = 0; if (commonPrefix < ROW_LENGTH_SIZE) { // almost nothing in common rrowlength = Bytes.toShort(right, roffset); comparisonResult = compareRows(left, loffset + ROW_LENGTH_SIZE, lrowlength, right, roffset + ROW_LENGTH_SIZE, rrowlength); } else { // the row length is the same rrowlength = lrowlength; if (commonPrefix < ROW_LENGTH_SIZE + rrowlength) { // The rows are not the same. Exclude the common prefix and compare // the rest of the two rows. int common = commonPrefix - ROW_LENGTH_SIZE; comparisonResult = compareRows( left, loffset + common + ROW_LENGTH_SIZE, lrowlength - common, right, roffset + common + ROW_LENGTH_SIZE, rrowlength - common); } } if (comparisonResult != 0) { return comparisonResult; } assert lrowlength == rrowlength; return compareWithoutRow(commonPrefix, left, loffset, llength, right, roffset, rlength, lrowlength); } /** * Compare columnFamily, qualifier, timestamp, and key type (everything * except the row). This method is used both in the normal comparator and * the "same-prefix" comparator. Note that we are assuming that row portions * of both KVs have already been parsed and found identical, and we don't * validate that assumption here. * @param commonPrefix * the length of the common prefix of the two key-values being * compared, including row length and row */ private int compareWithoutRow(int commonPrefix, byte[] left, int loffset, int llength, byte[] right, int roffset, int rlength, short rowlength) { /*** * KeyValue Format and commonLength: * |_keyLen_|_valLen_|_rowLen_|_rowKey_|_famiLen_|_fami_|_Quali_|.... * ------------------|-------commonLength--------|-------------- */ int commonLength = ROW_LENGTH_SIZE + FAMILY_LENGTH_SIZE + rowlength; // commonLength + TIMESTAMP_TYPE_SIZE int commonLengthWithTSAndType = TIMESTAMP_TYPE_SIZE + commonLength; // ColumnFamily + Qualifier length. int lcolumnlength = llength - commonLengthWithTSAndType; int rcolumnlength = rlength - commonLengthWithTSAndType; byte ltype = left[loffset + (llength - 1)]; byte rtype = right[roffset + (rlength - 1)]; // If the column is not specified, the "minimum" key type appears the // latest in the sorted order, regardless of the timestamp. This is used // for specifying the last key/value in a given row, because there is no // "lexicographically last column" (it would be infinitely long). The // "maximum" key type does not need this behavior. if (lcolumnlength == 0 && ltype == Type.Minimum.getCode()) { // left is "bigger", i.e. it appears later in the sorted order return 1; } if (rcolumnlength == 0 && rtype == Type.Minimum.getCode()) { return -1; } int lfamilyoffset = commonLength + loffset; int rfamilyoffset = commonLength + roffset; // Column family length. int lfamilylength = left[lfamilyoffset - 1]; int rfamilylength = right[rfamilyoffset - 1]; // If left family size is not equal to right family size, we need not // compare the qualifiers. boolean sameFamilySize = (lfamilylength == rfamilylength); int common = 0; if (commonPrefix > 0) { common = Math.max(0, commonPrefix - commonLength); if (!sameFamilySize) { // Common should not be larger than Math.min(lfamilylength, // rfamilylength). common = Math.min(common, Math.min(lfamilylength, rfamilylength)); } else { common = Math.min(common, Math.min(lcolumnlength, rcolumnlength)); } } if (!sameFamilySize) { // comparing column family is enough. return Bytes.compareTo(left, lfamilyoffset + common, lfamilylength - common, right, rfamilyoffset + common, rfamilylength - common); } // Compare family & qualifier together. final int comparison = Bytes.compareTo(left, lfamilyoffset + common, lcolumnlength - common, right, rfamilyoffset + common, rcolumnlength - common); if (comparison != 0) { return comparison; } return compareTimestampAndType(left, loffset, llength, right, roffset, rlength, ltype, rtype); } private int compareTimestampAndType(byte[] left, int loffset, int llength, byte[] right, int roffset, int rlength, byte ltype, byte rtype) { int compare; if (!this.ignoreTimestamp) { // Get timestamps. long ltimestamp = Bytes.toLong(left, loffset + (llength - TIMESTAMP_TYPE_SIZE)); long rtimestamp = Bytes.toLong(right, roffset + (rlength - TIMESTAMP_TYPE_SIZE)); compare = compareTimestamps(ltimestamp, rtimestamp); if (compare != 0) { return compare; } } if (!this.ignoreType) { // Compare types. Let the delete types sort ahead of puts; i.e. types // of higher numbers sort before those of lesser numbers. Maximum (255) // appears ahead of everything, and minimum (0) appears after // everything. return (0xff & rtype) - (0xff & ltype); } return 0; } public int compare(byte[] left, byte[] right) { return compare(left, 0, left.length, right, 0, right.length); } public int compareRows(byte [] left, int loffset, int llength, byte [] right, int roffset, int rlength) { return Bytes.compareTo(left, loffset, llength, right, roffset, rlength); } protected int compareColumns( byte [] left, int loffset, int llength, final int lfamilylength, byte [] right, int roffset, int rlength, final int rfamilylength) { return KeyValue.compareColumns(left, loffset, llength, lfamilylength, right, roffset, rlength, rfamilylength); } int compareTimestamps(final long ltimestamp, final long rtimestamp) { // The below older timestamps sorting ahead of newer timestamps looks // wrong but it is intentional. This way, newer timestamps are first // found when we iterate over a memstore and newer versions are the // first we trip over when reading from a store file. if (ltimestamp < rtimestamp) { return 1; } else if (ltimestamp > rtimestamp) { return -1; } return 0; } } // HeapSize public long heapSize() { return ClassSize.align(ClassSize.OBJECT + ClassSize.REFERENCE + ClassSize.align(ClassSize.ARRAY) + ClassSize.align(length) + (2 * Bytes.SIZEOF_INT) + Bytes.SIZEOF_LONG); } // this overload assumes that the length bytes have already been read, // and it expects the length of the KeyValue to be explicitly passed // to it. public void readFields(int length, final DataInput in) throws IOException { if (length <= 0) { throw new IOException("Failed read " + length + " bytes, stream corrupt?"); } this.length = length; this.offset = 0; this.bytes = new byte[this.length]; in.readFully(this.bytes, 0, this.length); } // Writable public void readFields(final DataInput in) throws IOException { int length = in.readInt(); readFields(length, in); } public void write(final DataOutput out) throws IOException { out.writeInt(this.length); out.write(this.bytes, this.offset, this.length); } }
apache-2.0
dubenju/javay
src/java/javay/fsm/Event.java
44
package javay.fsm; public class Event { }
apache-2.0
fugeritaetas/morozko-lib
java14-morozko/org.morozko.java.core/src/org/morozko/java/core/util/result/ResultInfo.java
1379
package org.morozko.java.core.util.result; import java.io.Serializable; public class ResultInfo implements Serializable { /** * */ private static final long serialVersionUID = 7535056453333738172L; private String resultCode; private String resultMessage; private Exception resultError; private Object info; public String getResultCode() { return resultCode; } public void setResultCode(String resultCode) { this.resultCode = resultCode; } public ResultInfo() { } public ResultInfo(String resultCode, String resultMessage, Exception resultError, Object info) { super(); this.resultCode = resultCode; this.resultMessage = resultMessage; this.resultError = resultError; this.info = info; } public ResultInfo(String resultCode, String resultMessage) { super(); this.resultCode = resultCode; this.resultMessage = resultMessage; } public String getResultMessage() { return resultMessage; } public void setResultMessage(String resultMessage) { this.resultMessage = resultMessage; } public Exception getResultError() { return resultError; } public void setResultError(Exception resultError) { this.resultError = resultError; } public Object getInfo() { return info; } public void setInfo(Object info) { this.info = info; } }
apache-2.0
hannesdejager/invokej
src/main/java/com/cloudinvoke/invokej/constructs/Factory.java
188
package com.cloudinvoke.invokej.constructs; /** * @author Hannes de Jager * @since 22 May 2013 * * @param <RESULT> */ public interface Factory<RESULT> { RESULT createInstance(); }
apache-2.0
jentfoo/aws-sdk-java
aws-java-sdk-cognitosync/src/main/java/com/amazonaws/services/cognitosync/model/transform/RegisterDeviceResultJsonUnmarshaller.java
2820
/* * Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.cognitosync.model.transform; import java.math.*; import javax.annotation.Generated; import com.amazonaws.services.cognitosync.model.*; import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import com.fasterxml.jackson.core.JsonToken; import static com.fasterxml.jackson.core.JsonToken.*; /** * RegisterDeviceResult JSON Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class RegisterDeviceResultJsonUnmarshaller implements Unmarshaller<RegisterDeviceResult, JsonUnmarshallerContext> { public RegisterDeviceResult unmarshall(JsonUnmarshallerContext context) throws Exception { RegisterDeviceResult registerDeviceResult = new RegisterDeviceResult(); int originalDepth = context.getCurrentDepth(); String currentParentElement = context.getCurrentParentElement(); int targetDepth = originalDepth + 1; JsonToken token = context.getCurrentToken(); if (token == null) token = context.nextToken(); if (token == VALUE_NULL) { return registerDeviceResult; } while (true) { if (token == null) break; if (token == FIELD_NAME || token == START_OBJECT) { if (context.testExpression("DeviceId", targetDepth)) { context.nextToken(); registerDeviceResult.setDeviceId(context.getUnmarshaller(String.class).unmarshall(context)); } } else if (token == END_ARRAY || token == END_OBJECT) { if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) { if (context.getCurrentDepth() <= originalDepth) break; } } token = context.nextToken(); } return registerDeviceResult; } private static RegisterDeviceResultJsonUnmarshaller instance; public static RegisterDeviceResultJsonUnmarshaller getInstance() { if (instance == null) instance = new RegisterDeviceResultJsonUnmarshaller(); return instance; } }
apache-2.0
Aeronica/mxTune
src/main/java/net/aeronica/mods/mxtune/gui/mml/FileData.java
1563
/* * Aeronica's mxTune MOD * Copyright 2019, Paul Boese a.k.a. Aeronica * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.aeronica.mods.mxtune.gui.mml; import net.aeronica.mods.mxtune.caches.FileHelper; import java.nio.file.Path; public class FileData implements Comparable<FileData> { final Path path; final String name; public FileData(Path path) { this.path = path; this.name = FileHelper.removeExtension(path.getFileName().toString()); } @Override public int compareTo(FileData o) { return this.name.compareTo(o.name); } @Override public boolean equals(Object obj) { return obj instanceof FileData && this.path != null && this.name != null && this.path.equals(((FileData)obj).path) && this.name.equals(((FileData) obj).name); } @Override public int hashCode() { return path != null && name != null ? this.path.hashCode() * this.name.hashCode() : super.hashCode(); } }
apache-2.0
flipper83/size-calculator
library/src/main/java/com/flipper83/sizecalculator/SizeCalculator.java
2510
package com.flipper83.sizecalculator; import android.os.Process; import android.util.Log; import android.view.View; import java.lang.ref.Reference; import java.lang.ref.ReferenceQueue; import java.util.WeakHashMap; /** * This class process all size requests * * @author flipper83 */ public class SizeCalculator { final ReferenceQueue<View> referenceQueue; private final WeakHashMap<View, SizeProcess> attachedRequests; private final ReferenceCheckerThread referenceChecker; SizeCalculator(ReferenceQueue<View> referenceQueue) { this.referenceQueue = referenceQueue; this.attachedRequests = new WeakHashMap<View, SizeProcess>(); this.referenceChecker = new ReferenceCheckerThread(referenceQueue); this.referenceChecker.start(); } public static SizeCalculator create() { ReferenceQueue<View> tempPeferenceQueue = new ReferenceQueue<View>(); return new SizeCalculator(tempPeferenceQueue); } public void calculateSize(View view, SizeReadyListener listener) { if (view == null) { throw new IllegalArgumentException("The view cannot be null."); } SizeProcess process = new SizeProcess(view, this); cancelAttachedView(view); //add the size request attachedRequests.put(view,process); process.obtainSize(listener); } void cancelAttachedView(View view) { SizeProcess process = attachedRequests.remove(view); if (process != null) { process.cancel(); } } private class ReferenceCheckerThread extends Thread { ReferenceQueue<View> referenceQueue; ReferenceCheckerThread(ReferenceQueue<View> referenceQueue) { this.referenceQueue = referenceQueue; setDaemon(true); setName("SizeCalculator/RefChecker"); } @Override public void run() { Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); while (true) { try { Reference<? extends View> toRemove = referenceQueue.remove(); if (toRemove.get() != null) { cancelAttachedView(toRemove.get()); } } catch (InterruptedException e) { //TODO SEARCH A WAY TO NOTIFY THIS ERRORS break; } } } void shutdown() { interrupt(); } } }
apache-2.0
descoped/descoped-web
undertow-container/src/main/java/io/descoped/container/undertow/exception/ServerException.java
1348
package io.descoped.container.undertow.exception; /** * Created by oranheim on 02/02/2017. */ import io.descoped.container.undertow.core.UndertowContainer; import io.undertow.server.HttpServerExchange; import io.undertow.util.StatusCodes; /** * ServerException used by exception handler */ public class ServerException extends Exception { public static final ServerException NOT_FOUND = new ServerException(StatusCodes.NOT_FOUND); public static final ServerException BAD_REQUEST = new ServerException(StatusCodes.BAD_REQUEST); public static final ServerException METHOD_NOT_ALLOWED = new ServerException(StatusCodes.METHOD_NOT_ALLOWED); private final int code; public ServerException(int code) { super(StatusCodes.getReason(code)); this.code = code; } public ServerException(int code, String message) { super(StatusCodes.getReason(code) + ":" + message); this.code = code; } public void serveError(HttpServerExchange exchange) { exchange.setResponseCode(code); StringBuilder out = new StringBuilder(); errorText(out); UndertowContainer.log.error("serveError: {}", out.toString()); exchange.getResponseSender().send(out.toString()); } public void errorText(StringBuilder out) { out.append(getMessage()); } }
apache-2.0
makersoft/makereap
modules/extension/src/main/java/org/makersoft/web/mvc/mapping/impl/CreateMapping.java
785
/* * @(#)CreateMapping.java 2013-1-28 下午23:33:33 * * Copyright (c) 2011-2013 Makersoft.org all rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * */ package org.makersoft.web.mvc.mapping.impl; import org.makersoft.web.mvc.mapping.AbstractMapping; import org.springframework.web.bind.annotation.RequestMethod; /** * */ public class CreateMapping extends AbstractMapping { private String[] values = new String[] { }; private RequestMethod[] requestMethods = { RequestMethod.POST }; public CreateMapping() { super(METHOD_CREATE_NAME); } @Override public String[] getValues() { return values; } @Override public RequestMethod[] getRequestMethods() { return requestMethods; } }
apache-2.0
foundation-runtime/logging
logging-log4j/src/main/java/com/cisco/oss/foundation/logging/FoundationLogger.java
38498
/* * Copyright 2015 Cisco Systems, 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.cisco.oss.foundation.logging; import com.cisco.oss.foundation.flowcontext.FlowContextFactory; import com.cisco.oss.foundation.logging.structured.AbstractFoundationLoggingMarker; import org.apache.commons.lang3.StringUtils; import org.apache.log4j.*; import org.apache.log4j.helpers.Loader; import org.apache.log4j.helpers.OptionConverter; import org.apache.log4j.nt.NTEventLogAppender; import org.apache.log4j.spi.LoggerRepository; import org.apache.log4j.spi.LoggingEvent; import org.apache.log4j.spi.RepositorySelector; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.input.SAXBuilder; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.joda.time.format.DateTimeFormatter; import org.joda.time.format.DateTimeFormatterBuilder; import org.slf4j.Marker; import org.slf4j.helpers.FormattingTuple; import org.slf4j.helpers.MessageFormatter; import org.slf4j.spi.LocationAwareLogger; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.text.MessageFormat; import java.util.*; import java.util.logging.ConsoleHandler; import java.util.logging.FileHandler; import java.util.logging.Handler; import java.util.logging.LogRecord; /** * This Logger implementation is used for applying the Foundation Logging standards on * top of log4j. The logger is initialized by the the FoundationLogHierarcy Object. It * is not meant to be used in code by developers. In runtime they will use this * Logger if they specify the following line in thier log4j.properties file: * log4j.loggerFactory=com.cisco.oss.foundation.logging.FoundationLogFactory * * @author Yair Ogen */ class FoundationLogger extends Logger implements LocationAwareLogger { // NOPMD /** * the property key for reloading the log4j properties file. */ private static final String Foundation_FILE_RELOAD_DELAY = "FoundationfileReloadDelay"; /** * default delay value for reloading the log4j properties file. */ private static final int FILE_RELOAD_DELAY = 10000; static Properties log4jConfigProps = null; // NOPMD private static final String DEFAULT_CONFIGURATION_FILE = "log4j.properties"; // NOPMD private static final String DEFAULT_CONFIGURATION_KEY = "log4j.configuration"; // NOPMD private static final String FQCN = FoundationLogger.class.getName(); private static final String PATTERN_KEY = "messagePattern"; public static Map<String, Map<String, Layout>> markerAppendersMap = new HashMap<String, Map<String, Layout>>(); /** * Boolean indicating whether or not NTEventLogAppender is supported. */ private static boolean ntEventLogSupported = true; FoundationLogger(final String name) { super(name); } /** * Initialize that Foundation Logging library. */ static void init() {// NOPMD determineIfNTEventLogIsSupported(); URL resource = null; final String configurationOptionStr = OptionConverter.getSystemProperty(DEFAULT_CONFIGURATION_KEY, null); if (configurationOptionStr != null) { try { resource = new URL(configurationOptionStr); } catch (MalformedURLException ex) { // so, resource is not a URL: // attempt to get the resource from the class path resource = Loader.getResource(configurationOptionStr); } } if (resource == null) { resource = Loader.getResource(DEFAULT_CONFIGURATION_FILE); // NOPMD } if (resource == null) { System.err.println("[FoundationLogger] Can not find resource: " + DEFAULT_CONFIGURATION_FILE); // NOPMD throw new FoundationIOException("Can not find resource: " + DEFAULT_CONFIGURATION_FILE); // NOPMD } // update the log manager to use the Foundation repository. final RepositorySelector foundationRepositorySelector = new FoundationRepositorySelector(FoundationLogFactory.foundationLogHierarchy); LogManager.setRepositorySelector(foundationRepositorySelector, null); // set logger to info so we always want to see these logs even if root // is set to ERROR. final Logger logger = getLogger(FoundationLogger.class); final String logPropFile = resource.getPath(); log4jConfigProps = getLogProperties(resource); // select and configure again so the loggers are created with the right // level after the repository selector was updated. OptionConverter.selectAndConfigure(resource, null, FoundationLogFactory.foundationLogHierarchy); // start watching for property changes setUpPropFileReloading(logger, logPropFile, log4jConfigProps); // add syslog appender or windows event viewer appender // setupOSSystemLog(logger, log4jConfigProps); // parseMarkerPatterns(log4jConfigProps); // parseMarkerPurePattern(log4jConfigProps); // udpateMarkerStructuredLogOverrideMap(logger); AbstractFoundationLoggingMarker.init(); updateSniffingLoggersLevel(logger); setupJULSupport(resource); } private static void setupJULSupport(URL resource) { boolean julSupportEnabled = Boolean.valueOf(log4jConfigProps.getProperty(FoundationLoggerConstants.Foundation_JUL_SUPPORT_ENABLED.toString(), "false")); if (julSupportEnabled) { String appenderRef = log4jConfigProps.getProperty(FoundationLoggerConstants.Foundation_JUL_APPENDER_REF.toString()); if (StringUtils.isBlank(appenderRef)) { Enumeration allAppenders = Logger.getRootLogger().getAllAppenders(); while (allAppenders.hasMoreElements()) { Appender appender = (Appender) allAppenders.nextElement(); if (appender instanceof FileAppender) { appenderRef = appender.getName(); getLogger(FoundationLogger.class).info("*** Using '" + appenderRef + "' as the Java util logging appender ref ***"); System.err.println("*** Using '" + appenderRef + "' as the Java util logging appender ref ***"); break; } } } if (StringUtils.isBlank(appenderRef)) { throw new IllegalArgumentException("Java util support was enabled but couldn't find a matching appender under the '" + FoundationLoggerConstants.Foundation_JUL_APPENDER_REF.toString() + "' key."); } Handler handler = null; Appender appender = Logger.getRootLogger().getAppender(appenderRef); if(appender == null){ Enumeration allAppenders = Logger.getRootLogger().getAllAppenders(); while (allAppenders.hasMoreElements()){ Appender tempAppender = (Appender)allAppenders.nextElement(); if(tempAppender instanceof AsyncAppender){ AsyncAppender asyncAppender = (AsyncAppender)tempAppender; Enumeration asyncAppenderAllAppenders = asyncAppender.getAllAppenders(); while (asyncAppenderAllAppenders.hasMoreElements()){ Appender asyncTempAppender = (Appender)asyncAppenderAllAppenders.nextElement(); if(appenderRef.equals(asyncTempAppender.getName())){ appender = asyncTempAppender; break; } } if(appender != null){ break; } } } } if(appender instanceof FileAppender){ try { handler = new FileHandler(((FileAppender)appender).getFile()); } catch (IOException e) { throw new IllegalArgumentException("IOException encountered when trying to setup jul logging: " + e, e); } }else if(appender instanceof ConsoleAppender){ handler = new ConsoleHandler(); }else{ getLogger(FoundationLogger.class).error("got a reference to an unsupported appender: " + appenderRef); } if (handler != null) { // System.setProperty("java.util.logging.config.file",resource.getPath()); java.util.logging.LogManager.getLogManager().reset(); try { java.util.logging.LogManager.getLogManager().readConfiguration(resource.openStream()); } catch (IOException e) { throw new IllegalArgumentException("IOException encountered when trying to read log4j properties file: " + e, e); } handler.setLevel(java.util.logging.Level.FINEST); handler.setFormatter(new FoundationLogFormatter()); java.util.logging.Logger rootLogger = java.util.logging.Logger.getLogger(""); rootLogger.addHandler(handler); rootLogger.setLevel(java.util.logging.Level.SEVERE); Properties julLoggerSubset = getPropertiesSubset("jul.logger"); if(!julLoggerSubset.isEmpty()){ Set<Object> keySet = julLoggerSubset.keySet(); for (Object key : keySet) { java.util.logging.Logger logger = java.util.logging.Logger.getLogger((String)key); logger.setLevel(java.util.logging.Level.parse((String)julLoggerSubset.get(key))); } } } } } private static Properties getPropertiesSubset(String prefix) { Properties subset = new Properties(); Enumeration<Object> keys = log4jConfigProps.keys(); boolean validSubset = false; while (keys.hasMoreElements()) { Object key = keys.nextElement(); if (key instanceof String && ((String) key).startsWith(prefix)) { if (!validSubset) { validSubset = true; } /* * Check to make sure that subset.subset(prefix) doesn't * blow up when there is only a single property * with the key prefix. This is not a useful * subset but it is a valid subset. */ String newKey = null; if (((String) key).length() == prefix.length()) { newKey = prefix; } else { newKey = ((String) key).substring(prefix.length() + 1); } /* * use addPropertyDirect() - this will plug the data as * is into the Map, but will also do the right thing * re key accounting */ subset.setProperty(newKey, (String) log4jConfigProps.get(key)); } } if (validSubset) { return subset; } else { return new Properties(); } } // private static void parseMarkerPatterns(Properties properties) { // // Set<String> markerMappingKeySet = new HashSet<String>(); // // Set<String> entrySet = properties.stringPropertyNames(); // for (String key : entrySet) { // if (key.startsWith("logevent")) { // markerMappingKeySet.add(key); // } // } // // for (String key : markerMappingKeySet) { // // String[] split = key.split("\\."); // if (split.length != 4) { // throw new IllegalArgumentException("the key " + key + " does not contain a four part mapping."); // } // // String markerName = split[1]; // String appenderName = split[2]; // String pattern = properties.getProperty(key); // // if (markerAppendersMap.get(markerName) == null) { // markerAppendersMap.put(markerName, new HashMap<String, Layout>()); // } // // Map<String, Layout> markerAppenderMap = markerAppendersMap.get(markerName); // Layout patternLayout = new FoundationLoggingPatternLayout(pattern); // markerAppenderMap.put(appenderName, patternLayout); // // } // // } /** * The sniffing Loggers are some special Loggers, whose level will be set to TRACE forcedly. * @param logger */ private static void updateSniffingLoggersLevel(Logger logger) { InputStream settingIS = FoundationLogger.class .getResourceAsStream("/sniffingLogger.xml"); if (settingIS == null) { logger.debug("file sniffingLogger.xml not found in classpath"); } else { try { SAXBuilder builder = new SAXBuilder(); Document document = builder.build(settingIS); settingIS.close(); Element rootElement = document.getRootElement(); List<Element> sniffingloggers = rootElement .getChildren("sniffingLogger"); for (Element sniffinglogger : sniffingloggers) { String loggerName = sniffinglogger.getAttributeValue("id"); Logger.getLogger(loggerName).setLevel(Level.TRACE); } } catch (Exception e) { logger.error( "cannot load the sniffing logger configuration file. error is: " + e, e); throw new IllegalArgumentException( "Problem parsing sniffingLogger.xml", e); } } } private static void determineIfNTEventLogIsSupported() { boolean supported = true; try { new NTEventLogAppender(); } catch (Throwable t) {// NOPMD supported = false; } ntEventLogSupported = supported; } // private static void setupOSSystemLog(final Logger logger, final Properties log4jConfigProps) { // // final Layout layout = new FoundationLoggingPatternLayout(FondationLoggerConstants.DEFAULT_CONV_PATTERN.toString()); // final Logger rootLogger = LogManager.getRootLogger(); // // final OperatingSystem operatingSystem = OperatingSystem.getOperatingSystem(); // AppenderSkeleton systemLogAppender = null; // // Level defaultThreshold = Level.WARN; // if (log4jConfigProps != null && log4jConfigProps.getProperty("FoundationdefaultSystemLoggerThreshold") != null) { // defaultThreshold = Level.toLevel(log4jConfigProps.getProperty("FoundationdefaultSystemLoggerThreshold")); // } // // if (operatingSystem.equals(OperatingSystem.Windows) && ntEventLogSupported) { // // systemLogAppender = new NTEventLogAppender("Foundation Logging", layout); // systemLogAppender.setName("nteventlog"); // systemLogAppender.setThreshold(defaultThreshold); // systemLogAppender.activateOptions(); // // rootLogger.addAppender(systemLogAppender); // // } else if (operatingSystem.equals(OperatingSystem.HPUX) || operatingSystem.equals(OperatingSystem.Linux)) { // // systemLogAppender = new SyslogAppender(layout, "localhost", SyslogAppender.LOG_USER); // systemLogAppender.setName("systemlog"); // systemLogAppender.setThreshold(defaultThreshold); // systemLogAppender.activateOptions(); // // rootLogger.addAppender(systemLogAppender); // } // if (systemLogAppender == null) { // logger.error("System log appender was not initialized! Probably \"NTEventLogAppender.dll\" is not in the computer path."); // } // // } private static void setUpPropFileReloading(final Logger logger, final String logPropFile, final Properties properties) { int fileReloadDelay = FILE_RELOAD_DELAY; if (properties.containsKey(Foundation_FILE_RELOAD_DELAY)) { final String fileReloadDelayStr = properties.getProperty(Foundation_FILE_RELOAD_DELAY); try { fileReloadDelay = Integer.parseInt(fileReloadDelayStr); } catch (NumberFormatException e) { logger.error("Can not format to integer the property: " + Foundation_FILE_RELOAD_DELAY + ". using default of: " + FILE_RELOAD_DELAY); } } PropertyConfigurator.configureAndWatch(logPropFile, fileReloadDelay); } private static Properties getLogProperties(final URL logPropFileResource) { final Properties properties = new Properties(); InputStream propertiesInStream = null; final String log4jFilePath = logPropFileResource.getPath(); try { propertiesInStream = logPropFileResource.openStream(); properties.load(propertiesInStream); } catch (FileNotFoundException e) { System.err.println("[FoundationLogger] Can not find the file: " + log4jFilePath); // NOPMD throw new FoundationIOException("Can not find the file: " + log4jFilePath, e); } catch (IOException e) { System.err.println("[FoundationLogger] IO Exception during load of file: " + log4jFilePath + ". Exception is: " + e.toString()); // NOPMD throw new FoundationIOException("IO Exception during load of file: " + log4jFilePath + ". Exception is: " + e.toString(), e); } finally { if (propertiesInStream != null) { try { propertiesInStream.close(); } catch (IOException e) { System.err.println("[FoundationLogger] IO Exception during close of file: " + log4jFilePath + ". Exception is: " + e.toString()); // NOPMD } } } return properties; } /** * Log a message object at level TRACE. * * @param msg * - the message object to be logged */ public void trace(String msg) { log(FQCN, Level.TRACE, msg, null); } /** * Log a message at level TRACE according to the specified format and * argument. * * <p> * This form avoids superfluous object creation when the logger is disabled * for level TRACE. * </p> * * @param format * the format string * @param arg * the argument */ public void trace(String format, Object arg) { if (isTraceEnabled()) { FormattingTuple ft = MessageFormatter.format(format, arg); log(FQCN, Level.TRACE, ft.getMessage(), ft.getThrowable()); } } /** * Log a message at level TRACE according to the specified format and * arguments. * * <p> * This form avoids superfluous object creation when the logger is disabled * for the TRACE level. * </p> * * @param format * the format string * @param arg1 * the first argument * @param arg2 * the second argument */ public void trace(String format, Object arg1, Object arg2) { if (isTraceEnabled()) { FormattingTuple ft = MessageFormatter.format(format, arg1, arg2); log(FQCN, Level.TRACE, ft.getMessage(), ft.getThrowable()); } } /** * Log a message at level TRACE according to the specified format and * arguments. * * <p> * This form avoids superfluous object creation when the logger is disabled * for the TRACE level. * </p> * * @param format * the format string * @param argArray * an array of arguments */ public void trace(String format, Object[] argArray) { if (isTraceEnabled()) { FormattingTuple ft = MessageFormatter.arrayFormat(format, argArray); log(FQCN, Level.TRACE, ft.getMessage(), ft.getThrowable()); } } /** * Log an exception (throwable) at level TRACE with an accompanying message. * * @param msg * the message accompanying the exception * @param t * the exception (throwable) to log */ public void trace(String msg, Throwable t) { log(FQCN, Level.TRACE, msg, t); } // /** // * Is this logger instance enabled for the DEBUG level? // * // * @return True if this Logger is enabled for level DEBUG, false // otherwise. // */ // public boolean isDebugEnabled() { // return super.isDebugEnabled(); // } /** * Log a message object at level DEBUG. * * @param msg * - the message object to be logged */ public void debug(String msg) { log(FQCN, Level.DEBUG, msg, null); } /** * Log a message at level DEBUG according to the specified format and * argument. * * <p> * This form avoids superfluous object creation when the logger is disabled * for level DEBUG. * </p> * * @param format * the format string * @param arg * the argument */ public void debug(String format, Object arg) { if (isDebugEnabled()) { FormattingTuple ft = MessageFormatter.format(format, arg); log(FQCN, Level.DEBUG, ft.getMessage(), ft.getThrowable()); } } /** * Log a message at level DEBUG according to the specified format and * arguments. * * <p> * This form avoids superfluous object creation when the logger is disabled * for the DEBUG level. * </p> * * @param format * the format string * @param arg1 * the first argument * @param arg2 * the second argument */ public void debug(String format, Object arg1, Object arg2) { if (isDebugEnabled()) { FormattingTuple ft = MessageFormatter.format(format, arg1, arg2); log(FQCN, Level.DEBUG, ft.getMessage(), ft.getThrowable()); } } /** * Log a message at level DEBUG according to the specified format and * arguments. * * <p> * This form avoids superfluous object creation when the logger is disabled * for the DEBUG level. * </p> * * @param format * the format string * @param argArray * an array of arguments */ public void debug(String format, Object[] argArray) { if (isDebugEnabled()) { FormattingTuple ft = MessageFormatter.arrayFormat(format, argArray); log(FQCN, Level.DEBUG, ft.getMessage(), ft.getThrowable()); } } /** * Log an exception (throwable) at level DEBUG with an accompanying message. * * @param msg * the message accompanying the exception * @param t * the exception (throwable) to log */ public void debug(String msg, Throwable t) { log(FQCN, Level.DEBUG, msg, t); } // /** // * Is this logger instance enabled for the INFO level? // * // * @return True if this Logger is enabled for the INFO level, false // otherwise. // */ // public boolean isInfoEnabled() { // return super.isInfoEnabled(); // } /** * Log a message object at the INFO level. * * @param msg * - the message object to be logged */ public void info(String msg) { log(FQCN, Level.INFO, msg, null); } /** * Log a message at level INFO according to the specified format and * argument. * * <p> * This form avoids superfluous object creation when the logger is disabled * for the INFO level. * </p> * * @param format * the format string * @param arg * the argument */ public void info(String format, Object arg) { if (isInfoEnabled()) { FormattingTuple ft = MessageFormatter.format(format, arg); log(FQCN, Level.INFO, ft.getMessage(), ft.getThrowable()); } } /** * Log a message at the INFO level according to the specified format and * arguments. * * <p> * This form avoids superfluous object creation when the logger is disabled * for the INFO level. * </p> * * @param format * the format string * @param arg1 * the first argument * @param arg2 * the second argument */ public void info(String format, Object arg1, Object arg2) { if (isInfoEnabled()) { FormattingTuple ft = MessageFormatter.format(format, arg1, arg2); log(FQCN, Level.INFO, ft.getMessage(), ft.getThrowable()); } } /** * Log a message at level INFO according to the specified format and * arguments. * * <p> * This form avoids superfluous object creation when the logger is disabled * for the INFO level. * </p> * * @param format * the format string * @param argArray * an array of arguments */ public void info(String format, Object[] argArray) { if (isInfoEnabled()) { FormattingTuple ft = MessageFormatter.arrayFormat(format, argArray); log(FQCN, Level.INFO, ft.getMessage(), ft.getThrowable()); } } /** * Log an exception (throwable) at the INFO level with an accompanying * message. * * @param msg * the message accompanying the exception * @param t * the exception (throwable) to log */ public void info(String msg, Throwable t) { log(FQCN, Level.INFO, msg, t); } /** * Is this logger instance enabled for the WARN level? * * @return True if this Logger is enabled for the WARN level, false * otherwise. */ public boolean isWarnEnabled() { return super.isEnabledFor(Level.WARN); } /** * Log a message object at the WARN level. * * @param msg * - the message object to be logged */ public void warn(String msg) { log(FQCN, Level.WARN, msg, null); } /** * Log a message at the WARN level according to the specified format and * argument. * * <p> * This form avoids superfluous object creation when the logger is disabled * for the WARN level. * </p> * * @param format * the format string * @param arg * the argument */ public void warn(String format, Object arg) { if (isEnabledFor(Level.WARN)) { FormattingTuple ft = MessageFormatter.format(format, arg); log(FQCN, Level.WARN, ft.getMessage(), ft.getThrowable()); } } /** * Log a message at the WARN level according to the specified format and * arguments. * * <p> * This form avoids superfluous object creation when the logger is disabled * for the WARN level. * </p> * * @param format * the format string * @param arg1 * the first argument * @param arg2 * the second argument */ public void warn(String format, Object arg1, Object arg2) { if (isEnabledFor(Level.WARN)) { FormattingTuple ft = MessageFormatter.format(format, arg1, arg2); log(FQCN, Level.WARN, ft.getMessage(), ft.getThrowable()); } } /** * Log a message at level WARN according to the specified format and * arguments. * * <p> * This form avoids superfluous object creation when the logger is disabled * for the WARN level. * </p> * * @param format * the format string * @param argArray * an array of arguments */ public void warn(String format, Object[] argArray) { if (isEnabledFor(Level.WARN)) { FormattingTuple ft = MessageFormatter.arrayFormat(format, argArray); log(FQCN, Level.WARN, ft.getMessage(), ft.getThrowable()); } } /** * Log an exception (throwable) at the WARN level with an accompanying * message. * * @param msg * the message accompanying the exception * @param t * the exception (throwable) to log */ public void warn(String msg, Throwable t) { log(FQCN, Level.WARN, msg, t); } /** * Is this logger instance enabled for level ERROR? * * @return True if this Logger is enabled for level ERROR, false otherwise. */ public boolean isErrorEnabled() { return super.isEnabledFor(Level.ERROR); } /** * Log a message object at the ERROR level. * * @param msg * - the message object to be logged */ public void error(String msg) { log(FQCN, Level.ERROR, msg, null); } /** * Log a message at the ERROR level according to the specified format and * argument. * * <p> * This form avoids superfluous object creation when the logger is disabled * for the ERROR level. * </p> * * @param format * the format string * @param arg * the argument */ public void error(String format, Object arg) { if (isEnabledFor(Level.ERROR)) { FormattingTuple ft = MessageFormatter.format(format, arg); log(FQCN, Level.ERROR, ft.getMessage(), ft.getThrowable()); } } /** * Log a message at the ERROR level according to the specified format and * arguments. * * <p> * This form avoids superfluous object creation when the logger is disabled * for the ERROR level. * </p> * * @param format * the format string * @param arg1 * the first argument * @param arg2 * the second argument */ public void error(String format, Object arg1, Object arg2) { if (isEnabledFor(Level.ERROR)) { FormattingTuple ft = MessageFormatter.format(format, arg1, arg2); log(FQCN, Level.ERROR, ft.getMessage(), ft.getThrowable()); } } /** * Log a message at level ERROR according to the specified format and * arguments. * * <p> * This form avoids superfluous object creation when the logger is disabled * for the ERROR level. * </p> * * @param format * the format string * @param argArray * an array of arguments */ public void error(String format, Object[] argArray) { if (isEnabledFor(Level.ERROR)) { FormattingTuple ft = MessageFormatter.arrayFormat(format, argArray); log(FQCN, Level.ERROR, ft.getMessage(), ft.getThrowable()); } } /** * Log an exception (throwable) at the ERROR level with an accompanying * message. * * @param msg * the message accompanying the exception * @param t * the exception (throwable) to log */ public void error(String msg, Throwable t) { log(FQCN, Level.ERROR, msg, t); } @Override public boolean isTraceEnabled(Marker marker) { return isTraceEnabled(); } @Override public void trace(Marker marker, String msg) { log(marker, FQCN, Level.TRACE, msg, null); } @Override public void trace(Marker marker, String format, Object arg) { if (isTraceEnabled()) { FormattingTuple ft = MessageFormatter.format(format, arg); log(marker, FQCN, Level.TRACE, ft.getMessage(), ft.getThrowable()); } } @Override public void trace(Marker marker, String format, Object arg1, Object arg2) { if (isTraceEnabled()) { FormattingTuple ft = MessageFormatter.format(format, arg1, arg2); log(marker, FQCN, Level.TRACE, ft.getMessage(), ft.getThrowable()); } } @Override public void trace(Marker marker, String format, Object[] argArray) { if (isTraceEnabled()) { FormattingTuple ft = MessageFormatter.arrayFormat(format, argArray); log(marker, FQCN, Level.TRACE, ft.getMessage(), ft.getThrowable()); } } @Override public void trace(Marker marker, String msg, Throwable t) { log(marker, FQCN, Level.TRACE, msg, t); } @Override public boolean isDebugEnabled(Marker marker) { return isDebugEnabled(); } @Override public void debug(Marker marker, String msg) { log(marker, FQCN, Level.DEBUG, msg, null); } @Override public void debug(Marker marker, String format, Object arg) { if (isDebugEnabled()) { FormattingTuple ft = MessageFormatter.format(format, arg); log(marker, FQCN, Level.DEBUG, ft.getMessage(), ft.getThrowable()); } } @Override public void debug(Marker marker, String format, Object arg1, Object arg2) { if (isDebugEnabled()) { FormattingTuple ft = MessageFormatter.format(format, arg1, arg2); log(marker, FQCN, Level.DEBUG, ft.getMessage(), ft.getThrowable()); } } @Override public void debug(Marker marker, String format, Object[] argArray) { if (isDebugEnabled()) { FormattingTuple ft = MessageFormatter.arrayFormat(format, argArray); log(marker, FQCN, Level.DEBUG, ft.getMessage(), ft.getThrowable()); } } @Override public void debug(Marker marker, String msg, Throwable t) { log(marker, FQCN, Level.DEBUG, msg, t); } @Override public boolean isInfoEnabled(Marker marker) { return isInfoEnabled(); } @Override public void info(Marker marker, String msg) { log(marker, FQCN, Level.INFO, msg, null); } @Override public void info(Marker marker, String format, Object arg) { if (isInfoEnabled()) { FormattingTuple ft = MessageFormatter.format(format, arg); log(marker, FQCN, Level.INFO, ft.getMessage(), ft.getThrowable()); } } @Override public void info(Marker marker, String format, Object arg1, Object arg2) { if (isInfoEnabled()) { FormattingTuple ft = MessageFormatter.format(format, arg1, arg2); log(marker, FQCN, Level.INFO, ft.getMessage(), ft.getThrowable()); } } @Override public void info(Marker marker, String format, Object[] argArray) { if (isInfoEnabled()) { FormattingTuple ft = MessageFormatter.arrayFormat(format, argArray); log(marker, FQCN, Level.INFO, ft.getMessage(), ft.getThrowable()); } } @Override public void info(Marker marker, String msg, Throwable t) { log(marker, FQCN, Level.INFO, msg, t); } @Override public boolean isWarnEnabled(Marker marker) { return isWarnEnabled(); } @Override public void warn(Marker marker, String msg) { log(marker, FQCN, Level.WARN, msg, null); } @Override public void warn(Marker marker, String format, Object arg) { if (isEnabledFor(Level.WARN)) { FormattingTuple ft = MessageFormatter.format(format, arg); log(marker, FQCN, Level.WARN, ft.getMessage(), ft.getThrowable()); } } @Override public void warn(Marker marker, String format, Object arg1, Object arg2) { if (isEnabledFor(Level.WARN)) { FormattingTuple ft = MessageFormatter.format(format, arg1, arg2); log(marker, FQCN, Level.WARN, ft.getMessage(), ft.getThrowable()); } } @Override public void warn(Marker marker, String format, Object[] argArray) { if (isEnabledFor(Level.WARN)) { FormattingTuple ft = MessageFormatter.arrayFormat(format, argArray); log(marker, FQCN, Level.WARN, ft.getMessage(), ft.getThrowable()); } } @Override public void warn(Marker marker, String msg, Throwable t) { log(marker, FQCN, Level.WARN, msg, t); } @Override public boolean isErrorEnabled(Marker marker) { return isErrorEnabled(); } @Override public void error(Marker marker, String msg) { log(marker, FQCN, Level.ERROR, msg, null); } @Override public void error(Marker marker, String format, Object arg) { if (isEnabledFor(Level.ERROR)) { FormattingTuple ft = MessageFormatter.format(format, arg); log(marker, FQCN, Level.ERROR, ft.getMessage(), ft.getThrowable()); } } @Override public void error(Marker marker, String format, Object arg1, Object arg2) { if (isEnabledFor(Level.ERROR)) { FormattingTuple ft = MessageFormatter.format(format, arg1, arg2); log(marker, FQCN, Level.ERROR, ft.getMessage(), ft.getThrowable()); } } @Override public void error(Marker marker, String format, Object[] argArray) { if (isEnabledFor(Level.ERROR)) { FormattingTuple ft = MessageFormatter.arrayFormat(format, argArray); log(marker, FQCN, Level.ERROR, ft.getMessage(), ft.getThrowable()); } } @Override public void error(Marker marker, String msg, Throwable t) { log(marker, FQCN, Level.ERROR, msg, t); } @Override public void log(Marker marker, String fqcn, int level, String msg, Object[] argArray, Throwable t) { Level log4jLevel; switch (level) { case LocationAwareLogger.TRACE_INT: log4jLevel = Level.TRACE; break; case LocationAwareLogger.DEBUG_INT: log4jLevel = Level.DEBUG; break; case LocationAwareLogger.INFO_INT: log4jLevel = Level.INFO; break; case LocationAwareLogger.WARN_INT: log4jLevel = Level.WARN; break; case LocationAwareLogger.ERROR_INT: log4jLevel = Level.ERROR; break; default: throw new IllegalStateException("Level number " + level + " is not recognized."); } log(FQCN, log4jLevel, msg, t); } public void log(Marker marker, String callerFQCN, Priority level, Object message, Throwable t) { if (repository.isDisabled(level.toInt())) { return; } if (level.isGreaterOrEqual(this.getEffectiveLevel())) { forcedLog(marker, callerFQCN, level, message, t); } } /** * This method creates a new logging event and logs the event without * further checks. */ protected void forcedLog(Marker marker, String fqcn, Priority level, Object message, Throwable t) { callAppenders(new FoundationLof4jLoggingEvent(marker, fqcn, this, level, message, t)); } @Override public void callAppenders(LoggingEvent event) { int writes = 0; Category category = this; while (category != null) { // Protected against simultaneous call to addAppender, // removeAppender,... synchronized (category) { @SuppressWarnings("unchecked") Enumeration<Appender> allAppenders = category.getAllAppenders(); while (allAppenders.hasMoreElements()) { Appender appender = allAppenders.nextElement(); // since we may update the appender layout we must sync so // other threads won't use it by mistake synchronized (appender) { if(event instanceof FoundationLof4jLoggingEvent){ appender.doAppend(new FoundationLof4jLoggingEvent((FoundationLof4jLoggingEvent) event)); }else{ appender.doAppend(event); } } writes++; } if (!category.getAdditivity()) { break; } } category = category.getParent(); } if (writes == 0) { repository.emitNoAppenderWarning(this); } } private static class FoundationRepositorySelector implements RepositorySelector { final private LoggerRepository repository; public FoundationRepositorySelector(final LoggerRepository repository) { this.repository = repository; } @Override public LoggerRepository getLoggerRepository() { return repository; } } private static class FoundationLogFormatter extends java.util.logging.Formatter { MessageFormat messageFormat = new MessageFormat("{3} [{0}] [{2}]: {1}: {5} {4} \n"); DateTimeFormatter dateFormatter = new DateTimeFormatterBuilder().appendPattern("yyyy/MM/dd HH:mm:ss.SSS").toFormatter(); @Override public String format(LogRecord record) { Object[] arguments = new Object[]{ truncateLoggerName(record.getLoggerName(), 1), record.getLevel(), Thread.currentThread().getName(), (new DateTime(record.getMillis(), DateTimeZone.UTC)).toString(dateFormatter), record.getMessage(), FlowContextFactory.getFlowContext() == null ? "" : FlowContextFactory.getFlowContext().toString()}; return messageFormat.format(arguments); } private String truncateLoggerName(String n, int precision) { String[] split = n.split("\\."); return split[split.length-1]; } } }
apache-2.0
mvniekerk/titanium4j
src/com/emitrom/ti4j/mobile/client/cloud/core/AbstractCloudResponse.java
1595
/************************************************************************ AbstractCloudResponse.java is part of Ti4j 3.1.0 Copyright 2013 Emitrom LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. **************************************************************************/ package com.emitrom.ti4j.mobile.client.cloud.core; import com.emitrom.ti4j.core.client.ProxyObject; /** * Base class for chat request objects * */ public abstract class AbstractCloudResponse extends ProxyObject { public native String getCreatedAt()/*-{ var peer = this.@com.emitrom.ti4j.core.client.ProxyObject::getJsObj()(); return peer.created_at; }-*/; public native String getUpdatedAt()/*-{ var peer = this.@com.emitrom.ti4j.core.client.ProxyObject::getJsObj()(); return peer.updated_at; }-*/; public native String getMessage()/*-{ var peer = this.@com.emitrom.ti4j.core.client.ProxyObject::getJsObj()(); return peer.message; }-*/; public native String Id()/*-{ var peer = this.@com.emitrom.ti4j.core.client.ProxyObject::getJsObj()(); return peer.id; }-*/; }
apache-2.0
JoelMarcey/buck
test/com/facebook/buck/cli/endtoend/CommandsEndToEndTest.java
4011
/* * Copyright (c) Facebook, Inc. and 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 com.facebook.buck.cli.endtoend; import static org.hamcrest.Matchers.not; import static org.junit.Assert.assertEquals; import com.facebook.buck.testutil.TemporaryPaths; import com.facebook.buck.testutil.endtoend.EndToEndEnvironment; import com.facebook.buck.testutil.endtoend.EndToEndRunner; import com.facebook.buck.testutil.endtoend.EndToEndTestDescriptor; import com.facebook.buck.testutil.endtoend.EndToEndWorkspace; import com.facebook.buck.testutil.endtoend.Environment; import com.facebook.buck.util.environment.Platform; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import org.junit.Assume; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; @RunWith(EndToEndRunner.class) public class CommandsEndToEndTest { @Rule public TemporaryPaths tmp = new TemporaryPaths(); @Environment public static EndToEndEnvironment getBaseEnvironment() { return new EndToEndEnvironment().withCommand("run").addTemplates("cli"); } @Test public void shouldNotHaveProblemsParsingFlagsPassedByWrapperScript( EndToEndTestDescriptor test, EndToEndWorkspace workspace) throws Exception { // Get a healthy mix of AbstractCommand and AbstractContainerCommand invocations. // This mostly makes sure that the implicit args passed from the buck python // wrapper are understood by the java side of things. ImmutableList<String[]> commands = ImmutableList.of( new String[] {"--help"}, new String[] {"audit", "--help"}, new String[] {"audit", "config", "--help"}, new String[] {"build", "--help"}, new String[] {"cache", "--help"}, new String[] {"perf", "--help"}, new String[] {"perf", "rk", "--help"}, new String[] {"run", "--help"}, new String[] {"test", "--help"}, new String[] {"kill"}, new String[] {"--version"}); for (String[] command : commands) { workspace .runBuckCommand( true, ImmutableMap.copyOf(test.getVariableMap()), test.getTemplateSet(), command) .assertSuccess(); } for (String[] command : commands) { workspace .runBuckCommand( false, ImmutableMap.copyOf(test.getVariableMap()), test.getTemplateSet(), command) .assertSuccess(); } } @Test public void shouldUseTheInterpreterSpecifiedInTheEnvironment( EndToEndTestDescriptor test, EndToEndWorkspace workspace) throws Throwable { Assume.assumeThat(Platform.detect(), not(Platform.WINDOWS)); for (String s : test.getTemplateSet()) { workspace.addPremadeTemplate(s); } workspace.setup(); Path scriptPath = workspace.getPath(Paths.get("test.py")); Files.write(scriptPath, ImmutableList.of("echo --config", "echo foo.bar=baz")); String stdout = workspace .runBuckCommand( ImmutableMap.of("BUCK_WRAPPER_PYTHON_BIN", "/bin/bash"), "audit", "config", "--tab", "@" + scriptPath.toAbsolutePath().toString(), "foo.bar") .assertSuccess() .getStdout() .trim(); assertEquals("foo.bar\tbaz", stdout); } }
apache-2.0
bernhardhuber/kisoonlineapp
kisoonlineapp-gui/src/test/java/org/kisoonlineapp/uc/buchen/fullfills/FullfillVeranstaltungBeginnDateAfterTest.java
2336
/* * Copyright 2016 berni. * * 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.kisoonlineapp.uc.buchen.fullfills; import java.util.Calendar; import org.junit.After; import org.junit.AfterClass; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.kisoonlineapp.model.Teilnehmer; import org.kisoonlineapp.model.TeilnehmerBuilder; import org.kisoonlineapp.model.Veranstaltung; import org.kisoonlineapp.model.VeranstaltungBuilder; /** * * @author berni */ public class FullfillVeranstaltungBeginnDateAfterTest { @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } FullfillVeranstaltungBeginnDateAfter instance; public FullfillVeranstaltungBeginnDateAfterTest() { } @Before public void setUp() { instance = new FullfillVeranstaltungBeginnDateAfter(); } @After public void tearDown() { } /** * Test of fullfill method, of class FullfillVeranstaltungBeginnDateAfter. */ @Test public void testFullfill() { Calendar now = Calendar.getInstance(); Teilnehmer teilnehmer = new TeilnehmerBuilder().vorname("vn").nachname("nn").build(); Veranstaltung veranstaltung = new VeranstaltungBuilder().code("code1").status(Veranstaltung.Status.Buchbar).build(); assertEquals(0, teilnehmer.getTeilnahmeList().size()); FullfillContext ctx = new FullfillContext(teilnehmer, veranstaltung, now); FullfillResult result = instance.fullfill(ctx); assertNotNull(result); assertEquals(FullfillResult.Result.ok, result.getResult()); assertEquals(0, result.getReasonList().size()); } }
apache-2.0
ekonijn/http-tap
src/main/java/nl/xs4all/banaan/tap/web/layout/ClassAppender.java
613
package nl.xs4all.banaan.tap.web.layout; import java.io.Serializable; import org.apache.wicket.behavior.AttributeAppender; import org.apache.wicket.model.IModel; /** append class attribute to a component */ public class ClassAppender extends AttributeAppender { public static final String CLASS = "class"; public ClassAppender(IModel<?> replaceModel) { super(CLASS, replaceModel); } public ClassAppender(Serializable value) { super(CLASS, value); } public ClassAppender(IModel<?> appendModel, String separator) { super(CLASS, appendModel, separator); } }
apache-2.0
PerfCake/pc4nb
src/main/java/org/perfcake/pc4nb/ui/AbstractPC4NBView.java
1118
/* * Copyright (c) 2015 Andrej Halaj * * 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.perfcake.pc4nb.ui; import java.beans.PropertyChangeListener; import javax.swing.JPanel; import org.perfcake.pc4nb.model.PC4NBModel; public abstract class AbstractPC4NBView extends JPanel implements PropertyChangeListener { private PC4NBModel model; public PC4NBModel getModel() { return model; } public void setModel(PC4NBModel model) { this.model = model; if (model != null) { getModel().addPropertyChangeListener(this); } } }
apache-2.0
jentfoo/aws-sdk-java
aws-java-sdk-acmpca/src/main/java/com/amazonaws/services/acmpca/model/transform/ImportCertificateAuthorityCertificateRequestProtocolMarshaller.java
3016
/* * Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.acmpca.model.transform; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.Request; import com.amazonaws.http.HttpMethodName; import com.amazonaws.services.acmpca.model.*; import com.amazonaws.transform.Marshaller; import com.amazonaws.protocol.*; import com.amazonaws.protocol.Protocol; import com.amazonaws.annotation.SdkInternalApi; /** * ImportCertificateAuthorityCertificateRequest Marshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class ImportCertificateAuthorityCertificateRequestProtocolMarshaller implements Marshaller<Request<ImportCertificateAuthorityCertificateRequest>, ImportCertificateAuthorityCertificateRequest> { private static final OperationInfo SDK_OPERATION_BINDING = OperationInfo.builder().protocol(Protocol.AWS_JSON).requestUri("/") .httpMethodName(HttpMethodName.POST).hasExplicitPayloadMember(false).hasPayloadMembers(true) .operationIdentifier("ACMPrivateCA.ImportCertificateAuthorityCertificate").serviceName("AWSACMPCA").build(); private final com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory; public ImportCertificateAuthorityCertificateRequestProtocolMarshaller(com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory) { this.protocolFactory = protocolFactory; } public Request<ImportCertificateAuthorityCertificateRequest> marshall( ImportCertificateAuthorityCertificateRequest importCertificateAuthorityCertificateRequest) { if (importCertificateAuthorityCertificateRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { final ProtocolRequestMarshaller<ImportCertificateAuthorityCertificateRequest> protocolMarshaller = protocolFactory.createProtocolMarshaller( SDK_OPERATION_BINDING, importCertificateAuthorityCertificateRequest); protocolMarshaller.startMarshalling(); ImportCertificateAuthorityCertificateRequestMarshaller.getInstance().marshall(importCertificateAuthorityCertificateRequest, protocolMarshaller); return protocolMarshaller.finishMarshalling(); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
apache-2.0
Esioner/DayDayUp
app/src/main/java/com/esioner/myapplication/neihan/adapter/ShowImageView.java
5245
package com.esioner.myapplication.neihan.adapter; import android.Manifest; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.Color; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.os.SystemClock; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.design.widget.Snackbar; import android.support.v4.app.ActivityCompat; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Toast; import com.esioner.myapplication.R; import com.esioner.myapplication.utils.GlideUtils; import java.io.File; import me.xiaopan.sketch.Sketch; import me.xiaopan.sketch.SketchImageView; import me.xiaopan.sketch.request.CancelCause; import me.xiaopan.sketch.request.DownloadListener; import me.xiaopan.sketch.request.DownloadResult; import me.xiaopan.sketch.request.ErrorCause; public class ShowImageView extends AppCompatActivity implements View.OnClickListener { private SketchImageView iv; private String url; private String title; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); //实现透明状态栏 if (Build.VERSION.SDK_INT >= 21) { View decorView = getWindow().getDecorView(); decorView.setSystemUiVisibility( View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE); getWindow().setStatusBarColor(Color.TRANSPARENT); } setContentView(R.layout.nei_han_show_image_layout); iv = (SketchImageView) findViewById(R.id.iv_show_image); iv.setZoomEnabled(true); url = getIntent().getStringExtra("IMAGE_URL"); title = getIntent().getStringExtra("IMAGE_TITLE"); // Glide.with(this).load(url).into(iv); GlideUtils.showImage(url,iv); findViewById(R.id.btn_return_show_image).setOnClickListener(this); findViewById(R.id.btn_save_show_image).setOnClickListener(this); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { switch (requestCode) { case 0: if (grantResults.length > 0 && grantResults[0] == PackageManager .PERMISSION_GRANTED) { Toast.makeText(this, "获取权限成功,请重新下载", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(this, "权限获取失败,请重新授权", Toast.LENGTH_SHORT).show(); } break; } } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btn_return_show_image: finish(); break; case R.id.btn_save_show_image: if (ActivityCompat.checkSelfPermission(this, Manifest.permission .WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission .WRITE_EXTERNAL_STORAGE}, 0); } else { download(url, title = title.length() > 10 ? SystemClock .currentThreadTimeMillis() + "" : title); } break; } } public void download(final String url, final String imageName) { File file = null; file = new File(Environment.getExternalStoragePublicDirectory(Environment .DIRECTORY_PICTURES).getAbsolutePath(), imageName + ".png"); final File finalFile = file; Sketch.with(ShowImageView.this).download(url, new DownloadListener() { @Override public void onCompleted(DownloadResult result) { Toast.makeText(ShowImageView.this, "下载成功,请到相册查看", Toast.LENGTH_SHORT) .show(); // 最后通知图库更新 sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(new File(finalFile.getPath())))); } @Override public void onStarted() { Toast.makeText(ShowImageView.this, "正在下载,请稍后", Toast.LENGTH_SHORT) .show(); } @Override public void onError(ErrorCause errorCause) { Snackbar.make(null, "下载失败,请重新下载", 3000) .setAction("重新下载", new View.OnClickListener() { @Override public void onClick(View v) { download(url, imageName); } }).show(); } @Override public void onCanceled(CancelCause cancelCause) { } }).commit(); } }
apache-2.0
vam-google/google-cloud-java
google-cloud-clients/google-cloud-talent/src/main/java/com/google/cloud/talent/v4beta1/package-info.java
4510
/* * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * A client to Cloud Talent Solution API. * * <p>The interfaces provided are listed below, along with usage samples. * * <p>==================== CompanyServiceClient ==================== * * <p>Service Description: A service that handles company management, including CRUD and * enumeration. * * <p>Sample for CompanyServiceClient: * * <pre> * <code> * try (CompanyServiceClient companyServiceClient = CompanyServiceClient.create()) { * ProjectName parent = ProjectName.of("[PROJECT]"); * Company company = Company.newBuilder().build(); * Company response = companyServiceClient.createCompany(parent, company); * } * </code> * </pre> * * ================ CompletionClient ================ * * <p>Service Description: A service handles auto completion. * * <p>Sample for CompletionClient: * * <pre> * <code> * try (CompletionClient completionClient = CompletionClient.create()) { * ProjectName name = ProjectName.of("[PROJECT]"); * String query = ""; * int pageSize = 0; * CompleteQueryRequest request = CompleteQueryRequest.newBuilder() * .setName(name.toString()) * .setQuery(query) * .setPageSize(pageSize) * .build(); * CompleteQueryResponse response = completionClient.completeQuery(request); * } * </code> * </pre> * * ================== EventServiceClient ================== * * <p>Service Description: A service handles client event report. * * <p>Sample for EventServiceClient: * * <pre> * <code> * try (EventServiceClient eventServiceClient = EventServiceClient.create()) { * ProjectName parent = ProjectName.of("[PROJECT]"); * ClientEvent clientEvent = ClientEvent.newBuilder().build(); * ClientEvent response = eventServiceClient.createClientEvent(parent, clientEvent); * } * </code> * </pre> * * ================ JobServiceClient ================ * * <p>Service Description: A service handles job management, including job CRUD, enumeration and * search. * * <p>Sample for JobServiceClient: * * <pre> * <code> * try (JobServiceClient jobServiceClient = JobServiceClient.create()) { * ProjectName parent = ProjectName.of("[PROJECT]"); * Job job = Job.newBuilder().build(); * Job response = jobServiceClient.createJob(parent, job); * } * </code> * </pre> * * ==================== ProfileServiceClient ==================== * * <p>Service Description: A service that handles profile management, including profile CRUD, * enumeration and search. * * <p>Sample for ProfileServiceClient: * * <pre> * <code> * try (ProfileServiceClient profileServiceClient = ProfileServiceClient.create()) { * TenantName parent = TenantName.of("[PROJECT]", "[TENANT]"); * Profile profile = Profile.newBuilder().build(); * Profile response = profileServiceClient.createProfile(parent, profile); * } * </code> * </pre> * * =================== ResumeServiceClient =================== * * <p>Service Description: A service that handles resume parsing. * * <p>Sample for ResumeServiceClient: * * <pre> * <code> * try (ResumeServiceClient resumeServiceClient = ResumeServiceClient.create()) { * ProjectName parent = ProjectName.of("[PROJECT]"); * ByteString resume = ByteString.copyFromUtf8(""); * ParseResumeResponse response = resumeServiceClient.parseResume(parent, resume); * } * </code> * </pre> * * =================== TenantServiceClient =================== * * <p>Service Description: A service that handles tenant management, including CRUD and enumeration. * * <p>Sample for TenantServiceClient: * * <pre> * <code> * try (TenantServiceClient tenantServiceClient = TenantServiceClient.create()) { * ProjectName parent = ProjectName.of("[PROJECT]"); * Tenant tenant = Tenant.newBuilder().build(); * Tenant response = tenantServiceClient.createTenant(parent, tenant); * } * </code> * </pre> */ package com.google.cloud.talent.v4beta1;
apache-2.0
wanliwang/cayman
cm-idea/src/main/java/com/bjorktech/cayman/idea/corejava/io/nio/channel/XNIOClient.java
1122
package com.bjorktech.cayman.idea.corejava.io.nio.channel; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.SocketChannel; /** * User: sheshan * Date: 2018/8/9 * content: */ public class XNIOClient { /** * */ public static void main(String[] args) { /** * 静态内部类创建对象 */ try (SocketChannel channel = SocketChannel.open()) { //自己需要绑定么? //channel.bind() if (channel.connect(new InetSocketAddress(10110))) { //ByteBuffer(int mark, int pos, int lim, int cap, // package-private //byte[] hb, int offset) writeMessage(channel); } } catch (IOException e) { e.printStackTrace(); } finally { } } private static void writeMessage(SocketChannel channel) throws IOException { ByteBuffer buffer = ByteBuffer.allocate(8096); buffer.put("lie tou jiu shi luan lai!".getBytes()); channel.write(buffer); } }
apache-2.0
lburgazzoli/apache-activemq-artemis
artemis-junit/src/test/java/org/apache/activemq/artemis/junit/EmbeddedActiveMQResourceCustomConfigurationTest.java
2721
/* * 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.junit; import java.util.List; import org.apache.activemq.artemis.core.config.Configuration; import org.apache.activemq.artemis.core.config.CoreQueueConfiguration; import org.apache.activemq.artemis.core.config.impl.ConfigurationImpl; import org.apache.activemq.artemis.core.server.Queue; import org.junit.Rule; import org.junit.Test; import org.junit.rules.RuleChain; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; public class EmbeddedActiveMQResourceCustomConfigurationTest { static final String TEST_QUEUE = "test.queue"; static final String TEST_ADDRESS = "test.address"; CoreQueueConfiguration queueConfiguration = new CoreQueueConfiguration().setAddress(TEST_ADDRESS).setName(TEST_QUEUE); Configuration customConfiguration = new ConfigurationImpl().setPersistenceEnabled(false).setSecurityEnabled(true).addQueueConfiguration(queueConfiguration); private EmbeddedActiveMQResource server = new EmbeddedActiveMQResource(customConfiguration); @Rule public RuleChain rulechain = RuleChain.outerRule(new ThreadLeakCheckRule()).around(server); @Test public void testCustomConfiguration() throws Exception { Configuration configuration = server.getServer().getActiveMQServer().getConfiguration(); assertFalse("Persistence should have been disabled", configuration.isPersistenceEnabled()); assertTrue( "Security should have been enabled", configuration.isSecurityEnabled()); assertNotNull(TEST_QUEUE + " should exist", server.locateQueue(TEST_QUEUE)); List<Queue> boundQueues = server.getBoundQueues(TEST_ADDRESS); assertNotNull("List should never be null", boundQueues); assertEquals("Should have one queue bound to address " + TEST_ADDRESS, 1, boundQueues.size()); } }
apache-2.0
adko-pl/rest-workshop
security-stormpath/src/main/java/com/workshop/rest/SecurityStormpathApplication.java
343
package com.workshop.rest; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class SecurityStormpathApplication { public static void main(String[] args) { SpringApplication.run(SecurityStormpathApplication.class, args); } }
apache-2.0
mikvor/compressedMaps
src/main/java/info/javaperformance/serializers/IFloatSerializer.java
2557
/* * (C) Copyright 2015 Mikhail Vorontsov ( http://java-performance.info/ ) and others. * * 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. * * Contributors: * Mikhail Vorontsov */ package info.javaperformance.serializers; /** * (De)Serialization logic for map keys/values. * Exposing this interface allows you to create more space efficient methods if you know some special properties * of your data, like being non-negative. * * All classes implementing this interface must be thread safe. */ public interface IFloatSerializer { /** * Write a value into a buffer. * The method must hold an invariant: a value=N written by {@code write} and then read by {@code read} should be equal to N again. * This method allows you to gain extra storage savings for composite keys. * @param v Value to write * @param buf Output buffer */ public void write( final float v, final ByteArray buf ); /** * Read a value previously written by {@code write} * The method must hold an invariant: a value=N written by {@code write} and then read by {@code read} should be equal to N again. * This method allows you to gain extra storage savings for composite keys. * @param buf Input buffer * @return A value */ public float read( final ByteArray buf ); public void writeDelta( final float prevValue, final float curValue, final ByteArray buf, final boolean sorted ); public float readDelta( final float prevValue, final ByteArray buf, final boolean sorted ); /** * Skip the current value in the buffer. This method should work faster than actual reading. * @param buf Input buffer */ public void skip( final ByteArray buf ); /** * Get the maximal length of a value binary representation in this encoding. You must not return too low results * from this method. Slightly bigger results are tolerable. * @return The maximal length of a value binary representation in this encoding */ public int getMaxLength(); }
apache-2.0
mhus/mhus-inka
de.mhus.app.inka.morse/src/de/mhu/com/morse/utils/ObjectUtil.java
5779
package de.mhu.com.morse.utils; import java.io.File; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.util.Hashtable; import java.util.Iterator; import java.util.LinkedList; import java.util.Map; import de.mhu.lib.AMath; import de.mhu.lib.ASql; import de.mhu.lib.log.AL; import de.mhu.com.morse.cache.ContentCache; import de.mhu.com.morse.cache.MemoryCache; import de.mhu.com.morse.channel.IConnection; import de.mhu.com.morse.mql.IQueryResult; import de.mhu.com.morse.mql.Query; import de.mhu.com.morse.obj.IFunctionConfig; import de.mhu.com.morse.obj.ITableRead; import de.mhu.com.morse.types.IAttribute; public class ObjectUtil { private static AL log = new AL( ObjectUtil.class ); /** * Returns true if the id is a valide Morse-ID. * NULL is not valide. * * @param id A morse ID * @return true if valide */ public static boolean validateId( String id ) { if ( id == null || id.length() != 32 ) return false; for ( int i = 0; i< 32; i++ ) { char c = id.charAt( i ); if ( ! ( c >= 'a' && c <= 'z' ) && ! ( c >= '0' && c <= '9' ) && c != '_' ) return false; } return true; } /** * Throws a MorseException if the id is not valide. * * @param id A Morse-ID * @throws MorseException Will be thrown if the id is not valide. */ public static void assetId(String id) throws MorseException { if ( ! validateId( id ) ) throw new MorseException( MorseException.INVALID_OBJECT_ID, id ); } /** * Validate a ACL Name. If the name is not valide, NULL or to long it returns * false. * @param id A Morse-ID * @return true if the ACL-NAME is valide. */ public static boolean validateAcl( String id ) { if ( id == null || id.length() > 64 ) return false; for ( int i = 0; i < id.length(); i++ ) { char c = id.charAt( i ); if ( ! ( c >= 'a' && c <= 'z' ) && ! ( c >= '0' && c <= '9' ) && c != '_' ) return false; } return true; } /** * Creates a byte-representation of the Morse-ID ( 24 Byte). * * @param id * @return byte-Array with 24 Elements * @throws MorseException */ public static byte[] idToByte( String id ) throws MorseException { byte[] out = new byte[24]; for ( int i = 0; i < 32; i++ ) { char c = id.charAt( i ); if ( c == '_' ) { } else if ( c >= '0' && c <= '9' ) { byte b = (byte)( c - '0' + 1); for ( int j = 0; j < 6; j++ ) { int a = i * 6 + j; out[ a / 8 ] = AMath.setBit( out[ a / 8 ], a % 8, AMath.getBit( b, j ) ); } } else if ( c >= 'a' && c <= 'z' ) { byte b = (byte)( c - 'a' + 12); for ( int j = 0; j < 6; j++ ) { int a = i * 6 + j; out[ a / 8 ] = AMath.setBit( out[ a / 8 ], a % 8, AMath.getBit( b, j ) ); } } else throw new MorseException( MorseException.INVALID_OBJECT_ID, id ); } return out; } /** * Byte-Array to Morse-ID converter. * * @param in Byte-Array with min 24 elements. * @return */ public static String byteToId( byte[] in ) { char[] out = new char[ 32 ]; for ( int i = 0; i < 32; i++ ) { byte b = 0; for ( int j = 0; j < 6; j++ ) { int a = i * 6 + j; b = AMath.setBit( b, j, AMath.getBit( in[ a / 8 ], a % 8 ) ); } if ( b == 0 ) { out[ i ] = '_'; } else if ( b >= 1 && b <= 11 ) { out[ i ] = (char)('0' + b - 1); } else out[ i ] = (char)('a' + b - 12 ); } return new String( out ); } /* public static void main( String[] args ) throws MorseException { System.out.println( byteToId( idToByte( "0123456789_abcdefghijklmnopqrstuvwxyz" ) ) ); } */ /** * Create a unique Map from a table. The function will also close the table. */ public static Map<String,String> tableToMap(ITableRead table, String keyCol, String valueCol ) throws MorseException { table.reset(); Hashtable<String,String> out = new Hashtable<String,String>(); while ( table.next() ) out.put( table.getString( keyCol ), table.getString( valueCol ) ); table.close(); return out; } /** * Validate the three letter Morse-Base ID. * * @param id * @throws MorseException */ public static void assetMBaseId(String id) throws MorseException { if ( id == null || id.length() != 3 ) throw new MorseException( MorseException.INVALID_MORSE_BASE_ID, id ); for ( int i = 0; i< 3; i++ ) { char c = id.charAt( i ); if ( ! ( c >= 'a' && c <= 'z' ) && ! ( c >= '0' && c <= '9' ) && c != '_' ) throw new MorseException( MorseException.INVALID_OBJECT_ID, id ); } if ( id.charAt(0) == '_' ) throw new MorseException( MorseException.INVALID_OBJECT_ID, id ); } /** * Create a list from a table. The fields will be stored in one line for each row. * The function will also close the table. The function will always return LinkedList, * maybe a empty list but never NULL. */ public static LinkedList<Object[]> tableToList(ITableRead table, String[] fields) throws MorseException { LinkedList<Object[]> out = new LinkedList<Object[]>(); table.reset(); while ( table.next() ) { Object[] val = new Object[ fields.length ]; for ( int i = 0; i < fields.length; i++ ) val[ i ] = table.getObject( fields[ i ] ); out.add( val ); } table.close(); return out; } public static String toString(Object value) { return value.toString(); } public static long toLong(Object value) { if ( value == null ) return 0; if ( value instanceof Long ) return ((Long)value).longValue(); if ( value instanceof Integer ) return ((Integer)value).intValue(); return Long.parseLong( value.toString() ); } }
apache-2.0
jyotisingh/gocd
api/api-access-token-v1/src/main/java/com/thoughtworks/go/apiv1/accessToken/representers/AccessTokenRepresenter.java
2170
/* * 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.apiv1.accessToken.representers; import com.thoughtworks.go.api.base.OutputWriter; import com.thoughtworks.go.api.representers.ErrorGetter; import com.thoughtworks.go.domain.AccessToken; import com.thoughtworks.go.spark.Routes; import java.util.Collections; public class AccessTokenRepresenter { public static void toJSON(OutputWriter outputWriter, AccessToken token) { outputWriter.addLinks(linksWriter -> linksWriter .addLink("self", Routes.AccessToken.find(token.getId())) .addAbsoluteLink("doc", Routes.AccessToken.DOC) .addLink("find", Routes.AccessToken.find())); outputWriter.add("id", token.getId()) .add("description", token.getDescription()) .add("auth_config_id", token.getAuthConfigId()) .addChild("_meta", metaWriter -> { metaWriter.add("is_revoked", token.isRevoked()) .add("revoked_at", token.getRevokedAt()) .add("created_at", token.getCreatedAt()) .add("last_used_at", token.getLastUsed()); }); if (token instanceof AccessToken.AccessTokenWithDisplayValue) { outputWriter.addIfNotNull("token", ((AccessToken.AccessTokenWithDisplayValue) token).getDisplayValue()); } if (!token.errors().isEmpty()) { outputWriter.addChild("errors", errorWriter -> new ErrorGetter(Collections.emptyMap()).toJSON(errorWriter, token)); } } }
apache-2.0
MSourceCoded/SourceCodedCore
src/main/java/sourcecoded/core/crash/ThreadCrash.java
5176
package sourcecoded.core.crash; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.google.gson.stream.JsonWriter; import sourcecoded.core.SourceCodedCore; import java.awt.*; import java.io.*; import java.net.HttpURLConnection; import java.net.URI; import java.net.URL; import java.util.ArrayList; import java.util.List; public class ThreadCrash extends Thread { List<String> packageIDs; public ThreadCrash(List<String> packageIDs) { setName("SourceCodedCore -- Crash Reporter"); this.packageIDs = packageIDs; } @Override public void run() { File dirPath = new File(SourceCodedCore.getForgeRoot(), "crash-reports"); File report = lastFileModified(dirPath); try { BufferedReader reader = new BufferedReader(new FileReader(report)); boolean sccModInvolved = false; ArrayList<String> lines = new ArrayList<String>(); String lastLine; lines.add("-----------------------------------------------------------------------------------------------------------"); lines.add("You are reading this because your game has crashed."); lines.add("The cause of this crash was detected as a mod that uses SourceCodedCore."); lines.add("Please send this to SourceCoded in the appropriate issue tracker. All relevant information is listed below."); lines.add("-----------------------------------------------------------------------------------------------------------"); while ((lastLine = reader.readLine()) != null) { if (!sccModInvolved) { for (String packageID : packageIDs) if (lastLine.trim().startsWith("at") && lastLine.contains(packageID)) { sccModInvolved = true; } } lines.add(lastLine); } reader.close(); if (sccModInvolved) { String response = uploadGist(lines); response = parseResponse(response); Desktop.getDesktop().browse(new URI(response)); } } catch (Exception e) { System.err.println("Could not upload Crash Report to Gist"); } } public static File lastFileModified(File fl) { File[] files = fl.listFiles(new FileFilter() { public boolean accept(File file) { return file.isFile(); } }); if (files != null) { long lastMod = Long.MIN_VALUE; File choice = null; for (File file : files) { if (file.lastModified() > lastMod) { choice = file; lastMod = file.lastModified(); } } return choice; } return null; } public static String uploadGist(List<String> lines) throws IOException { URL url = new URL("https://api.github.com/gists"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("User-Agent", "Mozilla/5.0"); String data = null; data = encodeFile(lines); conn.connect(); StringBuilder stb = new StringBuilder(); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(data); wr.flush(); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = rd.readLine()) != null) { stb.append(line).append("\n"); } wr.close(); rd.close(); return stb.toString(); } public static String encodeFile(List<String> lines) throws IOException { StringWriter sw = new StringWriter(); JsonWriter writer = new JsonWriter(sw); StringBuilder builder = new StringBuilder(); for (String line : lines) { builder.append(line).append("\n"); } String details = builder.toString(); writer.beginObject(); writer.name("public"); writer.value(true); writer.name("description"); writer.value("SourceCodedCore crash report"); writer.name("files"); writer.beginObject(); writer.name("RawCrashLog.txt"); writer.beginObject(); writer.name("content"); writer.value(details); writer.endObject(); writer.endObject(); writer.endObject(); writer.close(); return sw.toString(); } public static String parseResponse(String response) { try { JsonObject obj = new JsonParser().parse(response).getAsJsonObject(); return obj.get("html_url").getAsString(); } catch (Exception e) { System.err.println("Could not upload Crash Report to Gist"); } return ""; } }
apache-2.0
josealmeida/opereffa
bosphorus/xsd/org/openehr/schemas/v1/DVIDENTIFIER.java
3578
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.3 in JDK 1.6 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2011.10.12 at 12:10:04 PM BST // package org.openehr.schemas.v1; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for DV_IDENTIFIER complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="DV_IDENTIFIER"> * &lt;complexContent> * &lt;extension base="{http://schemas.openehr.org/v1}DATA_VALUE"> * &lt;sequence> * &lt;element name="issuer" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="assigner" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="id" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="type" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "DV_IDENTIFIER", propOrder = { "issuer", "assigner", "id", "type" }) public class DVIDENTIFIER extends DATAVALUE { @XmlElement(required = true) protected String issuer; @XmlElement(required = true) protected String assigner; @XmlElement(required = true) protected String id; @XmlElement(required = true) protected String type; /** * Gets the value of the issuer property. * * @return * possible object is * {@link String } * */ public String getIssuer() { return issuer; } /** * Sets the value of the issuer property. * * @param value * allowed object is * {@link String } * */ public void setIssuer(String value) { this.issuer = value; } /** * Gets the value of the assigner property. * * @return * possible object is * {@link String } * */ public String getAssigner() { return assigner; } /** * Sets the value of the assigner property. * * @param value * allowed object is * {@link String } * */ public void setAssigner(String value) { this.assigner = value; } /** * Gets the value of the id property. * * @return * possible object is * {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } /** * Gets the value of the type property. * * @return * possible object is * {@link String } * */ public String getType() { return type; } /** * Sets the value of the type property. * * @param value * allowed object is * {@link String } * */ public void setType(String value) { this.type = value; } }
apache-2.0
yangxiaoxiao/learning-algorithm
src/main/java/org/adg/learning/algorithm/leetcode/Solution0653_findTarget.java
2695
package org.adg.learning.algorithm.leetcode; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import org.adg.learning.algorithm.leetcode.utils.TreeUtils; import org.adg.learning.algorithm.leetcode.utils.TreeUtils.TreeNode; //653. Two Sum IV - Input is a BST //Easy // //1317 // //133 // //Add to List // //Share //Given a Binary Search Tree and a target number, return true if there exist two elements in the BST such that their sum is equal to the given target. // //Example 1: // //Input: // 5 // / \ // 3 6 // / \ \ //2 4 7 // //Target = 9 // //Output: True // // //Example 2: // //Input: // 5 // / \ // 3 6 // / \ \ //2 4 7 // //Target = 28 // //Output: False // // //Accepted //132,176 //Submissions //241,141 class Solution0653_findTarget { public boolean findTarget(TreeNode root, int k) { if (null == root) { return false; } return dfs(root, root, k); } /** * 遍历树,先选择一个参与求和的节点,然后再BST中查找另一个节点<br/> * 时间复杂度O(NlogN),空间复杂度O(N) * * @param curr 参与求和的一个节点 * @param root 树根 * @param k 目标数 * @return */ private boolean dfs(TreeNode curr, TreeNode root, int k) { int val = k - curr.val; boolean b = find(curr, root.left, val); if (!b) { b = find(curr, root.right, val); } if (!b) { // 当前节点作为一个目标节点不可行,因此继续遍历查找,但选择新的当前节点 boolean bleft = (null != curr.left) ? dfs(curr.left, root, k) : false; return bleft ? true : ((null != curr.right) ? dfs(curr.right, root, k) : false); } return true; } private boolean find(TreeNode curr, TreeNode node, int k) { if (null == node) { return false; } // 要注意不能使用重复节点 if (node.val == k && node != curr) { return true; } return (node.val > k) ? find(curr, node.left, k) : find(curr, node.right, k); } public static void main(String args[]) { Solution0653_findTarget inst = new Solution0653_findTarget(); // result: // List<Integer> list = new LinkedList<>(Arrays.asList(new Integer[] { 5, 3, 6, 2, 4, null, 7 })); List<Integer> list = new LinkedList<>(Arrays.asList(new Integer[] { 1, 0, 4, -2, null, 3 })); TreeNode root = TreeUtils.makeTree(list); TreeUtils.printTree(root); System.out.println("----------------------------------"); int k = 7; boolean rst = inst.findTarget(root, k); System.out.println(String.format("input: %s output: %s", Arrays.toString(list.toArray()), rst)); } }
apache-2.0
zhihaoSong/com-szh-concurrent
src/main/java/com/szh/net/URLConnDemo.java
956
package com.szh.net; import java.net.*; import java.io.*; public class URLConnDemo { public static void main(String [] args) { try { URL url = new URL("http://www.dajie.com"); URLConnection urlConnection = url.openConnection(); HttpURLConnection connection = null; if(urlConnection instanceof HttpURLConnection) { connection = (HttpURLConnection) urlConnection; } else { System.out.println("请输入 URL 地址"); return; } BufferedReader in = new BufferedReader( new InputStreamReader(connection.getInputStream())); String urlString = ""; String current; while((current = in.readLine()) != null) { urlString += current; } System.out.println(urlString); }catch(IOException e) { e.printStackTrace(); } } }
apache-2.0
johncarpenter/MarketAndroid
mobile/src/main/java/com/twolinessoftware/smarterlist/view/SmartListCardRecyclerViewAdapter.java
6992
/* * Copyright (c) 2015. 2Lines Software,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.twolinessoftware.smarterlist.view; import android.content.Context; import android.os.Handler; import android.os.Message; import android.support.v7.widget.RecyclerView; import android.text.format.DateUtils; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.squareup.otto.Bus; import com.squareup.picasso.Picasso; import com.twolinessoftware.smarterlist.Injector; import com.twolinessoftware.smarterlist.R; import com.twolinessoftware.smarterlist.event.OnEditListSelectEvent; import com.twolinessoftware.smarterlist.event.OnOverflowSelectedEvent; import com.twolinessoftware.smarterlist.event.OnShoppingListSelectEvent; import com.twolinessoftware.smarterlist.model.SmartList; import com.twolinessoftware.smarterlist.model.dao.SmartListItemDAO; import com.twolinessoftware.smarterlist.util.AccountUtils; import com.twolinessoftware.smarterlist.util.Ln; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import javax.inject.Inject; import rx.Observable; import rx.Subscriber; import rx.schedulers.Schedulers; /** * Created by John on 2015-03-26. */ public class SmartListCardRecyclerViewAdapter extends RecyclerView.Adapter<GenericCardViewHolder> implements AdapterLifecycleInterface{ private final Context m_context; private Observable<List<SmartList>> m_queryObservable; public List<SmartList> m_entries = new ArrayList<SmartList>(); private HashMap<Long,Integer> m_uncheckedCounts = new HashMap<>(); @Inject SmartListItemDAO m_smartListItemDao; @Inject Bus m_eventBus; @Inject AccountUtils m_accountUtils; private final Handler m_refreshHandler = new Handler(){ @Override public void handleMessage(Message msg) { notifyDataSetChanged(); } }; public SmartListCardRecyclerViewAdapter(Context context, Observable<List<SmartList>> queryObservable) { this.m_context = context; this.m_queryObservable = queryObservable; Injector.inject(this); } private SmartListChangesSubscriber m_masterListChangesSubscriber; private class SmartListChangesSubscriber extends Subscriber<List<SmartList>>{ @Override public void onCompleted() { } @Override public void onError(Throwable e) { Ln.e("Error loading data: "+ Log.getStackTraceString(e)); } @Override public void onNext(List<SmartList> items) { Ln.v("SmartList updates. Showing "+items.size()+" cards"); m_entries = items; m_refreshHandler.sendEmptyMessage(0); } } private UncheckedCountSubscriber m_uncheckedCountSubscriber; private class UncheckedCountSubscriber extends Subscriber<HashMap<Long, Integer>> { @Override public void onCompleted() { } @Override public void onError(Throwable e) { Ln.e("Error processing counts:"+Log.getStackTraceString(e)); } @Override public void onNext(HashMap<Long, Integer> mapUpdatingCounts) { Ln.v("Unchecked count updates"); m_uncheckedCounts = mapUpdatingCounts; m_refreshHandler.sendEmptyMessage(0); } } private void registerObservers() { Ln.v("Registering card observers"); m_masterListChangesSubscriber = new SmartListChangesSubscriber(); m_queryObservable .subscribeOn(Schedulers.newThread()) .subscribe(m_masterListChangesSubscriber); m_uncheckedCountSubscriber = new UncheckedCountSubscriber(); m_smartListItemDao.monitorSmartListUncheckedCounts() .subscribeOn(Schedulers.newThread()) .subscribe(m_uncheckedCountSubscriber); } @Override public void onPause() { Ln.v("Pausing card observers"); m_masterListChangesSubscriber.unsubscribe(); m_uncheckedCountSubscriber.unsubscribe(); } @Override public void onResume() { registerObservers(); } @Override public int getItemViewType(int position) { return super.getItemViewType(position); } @Override public GenericCardViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View v = LayoutInflater.from(parent.getContext()) .inflate(R.layout.item_cardview, parent, false); GenericCardViewHolder vh = new GenericCardViewHolder(v); return vh; } @Override public void onBindViewHolder(GenericCardViewHolder holder, int position) { SmartList item = m_entries.get(position); holder.getView().setOnClickListener(view ->{ m_eventBus.post(new OnShoppingListSelectEvent(holder.getView(),item)); }); holder.m_createdDate.setText(m_context.getString(R.string.card_date_created, DateUtils.getRelativeTimeSpanString(item.getCreated().getTime(),System.currentTimeMillis(),DateUtils.MINUTE_IN_MILLIS,0))); holder.getView().setTag(item); holder.setText(item.getName()); if(m_accountUtils.isOwner(item)){ holder.getView().setBackgroundColor(m_context.getResources().getColor(R.color.pal_grey_1)); }else{ holder.getView().setBackgroundColor(m_context.getResources().getColor(R.color.pal_grey_2)); } // Get Count of Items in SmartList Integer countOfItems = m_uncheckedCounts.get(Long.valueOf(item.getItemId())); int count = countOfItems != null?countOfItems.intValue():0; holder.setCaption(m_context.getResources().getQuantityString(R.plurals.card_caption_items,count,count)); Picasso.with(m_context).load(item.getIconUrl()).into(holder.icon); holder.imageOverflow.setOnClickListener(v1 ->{ m_eventBus.post(new OnOverflowSelectedEvent(v1,item)); }); holder.buttonAction1.setOnClickListener(v1 -> { m_eventBus.post(new OnShoppingListSelectEvent(holder.getView(),item)); }); holder.buttonAction2.setOnClickListener(v1 -> { m_eventBus.post(new OnEditListSelectEvent(holder.getView(),item)); }); } @Override public int getItemCount() { return m_entries.size(); } }
apache-2.0
spring-projects/spring-data-examples
jpa/deferred/src/main/java/example/model/Customer388.java
624
package example.model; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Entity public class Customer388 { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String firstName; private String lastName; protected Customer388() {} public Customer388(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } @Override public String toString() { return String.format("Customer388[id=%d, firstName='%s', lastName='%s']", id, firstName, lastName); } }
apache-2.0
hortonworks/cloudbreak
datalake/src/main/java/com/sequenceiq/datalake/converter/DatabaseServerConverter.java
4483
package com.sequenceiq.datalake.converter; import org.springframework.stereotype.Component; import com.sequenceiq.cloudbreak.api.endpoint.v4.stacks.response.database.DatabaseServerResourceStatus; import com.sequenceiq.cloudbreak.api.endpoint.v4.stacks.response.database.DatabaseServerSslCertificateType; import com.sequenceiq.cloudbreak.api.endpoint.v4.stacks.response.database.DatabaseServerSslConfig; import com.sequenceiq.cloudbreak.api.endpoint.v4.stacks.response.database.DatabaseServerSslMode; import com.sequenceiq.cloudbreak.api.endpoint.v4.stacks.response.database.DatabaseServerStatus; import com.sequenceiq.cloudbreak.api.endpoint.v4.stacks.response.database.StackDatabaseServerResponse; import com.sequenceiq.redbeams.api.endpoint.v4.ResourceStatus; import com.sequenceiq.redbeams.api.endpoint.v4.databaseserver.requests.SslMode; import com.sequenceiq.redbeams.api.endpoint.v4.databaseserver.responses.DatabaseServerV4Response; import com.sequenceiq.redbeams.api.endpoint.v4.databaseserver.responses.SslCertificateType; import com.sequenceiq.redbeams.api.endpoint.v4.databaseserver.responses.SslConfigV4Response; import com.sequenceiq.redbeams.api.model.common.Status; @Component public class DatabaseServerConverter { public StackDatabaseServerResponse convert(DatabaseServerV4Response databaseServerV4Response) { StackDatabaseServerResponse stackDatabaseServerResponse = new StackDatabaseServerResponse(); stackDatabaseServerResponse.setCrn(databaseServerV4Response.getCrn()); stackDatabaseServerResponse.setName(databaseServerV4Response.getName()); stackDatabaseServerResponse.setDescription(databaseServerV4Response.getDescription()); stackDatabaseServerResponse.setEnvironmentCrn(databaseServerV4Response.getEnvironmentCrn()); stackDatabaseServerResponse.setHost(databaseServerV4Response.getHost()); stackDatabaseServerResponse.setPort(databaseServerV4Response.getPort()); stackDatabaseServerResponse.setDatabaseVendor(databaseServerV4Response.getDatabaseVendor()); stackDatabaseServerResponse.setDatabaseVendorDisplayName(databaseServerV4Response.getDatabaseVendorDisplayName()); stackDatabaseServerResponse.setCreationDate(databaseServerV4Response.getCreationDate()); if (databaseServerV4Response.getResourceStatus() != null) { stackDatabaseServerResponse.setResourceStatus(resourceStatusToDatabaseServerResourceStatus(databaseServerV4Response.getResourceStatus())); } if (databaseServerV4Response.getStatus() != null) { stackDatabaseServerResponse.setStatus(statusToDatabaseServerStatus(databaseServerV4Response.getStatus())); } stackDatabaseServerResponse.setStatusReason(databaseServerV4Response.getStatusReason()); stackDatabaseServerResponse.setClusterCrn(databaseServerV4Response.getClusterCrn()); if (databaseServerV4Response.getSslConfig() != null) { SslConfigV4Response sslConfig = databaseServerV4Response.getSslConfig(); DatabaseServerSslConfig databaseServerSslConfig = new DatabaseServerSslConfig(); databaseServerSslConfig.setSslCertificates(sslConfig.getSslCertificates()); if (sslConfig.getSslMode() != null) { databaseServerSslConfig.setSslMode(sslModeToDatabaseServerSslMode(sslConfig.getSslMode())); } if (sslConfig.getSslCertificateType() != null) { databaseServerSslConfig.setSslCertificateType(sslCertificateTypeToDatabaseServerSslCertificateType(sslConfig.getSslCertificateType())); } stackDatabaseServerResponse.setSslConfig(databaseServerSslConfig); } return stackDatabaseServerResponse; } private DatabaseServerResourceStatus resourceStatusToDatabaseServerResourceStatus(ResourceStatus resourceStatus) { return DatabaseServerResourceStatus.valueOf(resourceStatus.name()); } private DatabaseServerStatus statusToDatabaseServerStatus(Status status) { return DatabaseServerStatus.valueOf(status.name()); } private DatabaseServerSslMode sslModeToDatabaseServerSslMode(SslMode sslMode) { return DatabaseServerSslMode.valueOf(sslMode.name()); } private DatabaseServerSslCertificateType sslCertificateTypeToDatabaseServerSslCertificateType(SslCertificateType sslCertificateType) { return DatabaseServerSslCertificateType.valueOf(sslCertificateType.name()); } }
apache-2.0
tobyweston/simple-excel
src/test/java/bad/robot/excel/matchers/StubCell.java
2912
/* * Copyright (c) 2012-2013, bad robot (london) ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package bad.robot.excel.matchers; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.CellType; import org.apache.poi.ss.usermodel.*; import java.util.Date; import static org.apache.poi.ss.usermodel.CellType.*; class StubCell { static Cell createBlankCell(int row, int column) { return create(row, column, BLANK); } static Cell createCell(int row, int column, Boolean aBoolean) { Cell cell = create(row, column, BOOLEAN); cell.setCellValue(aBoolean); return cell; } static Cell createCell(Boolean aBoolean) { return createCell(0, 0, aBoolean); } static Cell createCell(int row, int column, Byte value) { Cell cell = create(row, column, ERROR); cell.setCellErrorValue(value); return cell; } static Cell createFormulaCell(int row, int column, String formula) { Cell cell = create(row, column, FORMULA); cell.setCellFormula(formula); return cell; } static Cell createCell(int row, int column, Double aDouble) { Cell cell = create(row, column, NUMERIC); cell.setCellValue(aDouble); return cell; } static Cell createCell(Double aDouble) { return createCell(0, 0, aDouble); } static Cell createCell(int row, int column, Date date) { Workbook workbook = new HSSFWorkbook(); Sheet sheet = workbook.createSheet(); Cell cell = sheet.createRow(row).createCell(column, NUMERIC); cell.setCellValue(date); CellStyle style = workbook.createCellStyle(); style.setDataFormat(workbook.getCreationHelper().createDataFormat().getFormat("m/d/yy h:mm")); cell.setCellStyle(style); return cell; } static Cell createCell(int row, int column, String value) { Cell cell = create(row, column, STRING); cell.setCellValue(value); return cell; } static Cell createCell(String value) { return createCell(0, 0, value); } private static Cell create(int row, int column, CellType type) { Workbook workbook = new HSSFWorkbook(); Sheet sheet = workbook.createSheet(); Cell cell = sheet.createRow(row).createCell(column, type); return cell; } }
apache-2.0
jeanlopes/dcoo_projeto_n2
src/main/java/com/qieventos/common/TestHib.java
724
package com.qieventos.common; import com.qieventos.models.TipoEvento; import com.qieventos.persistence.Connection; public class TestHib { /** * @param args */ public static void main(String[] args) { System.out.println("Maven + hibernate + mysql"); try (Connection conn = Connection.getConnection()) { conn.getSession().beginTransaction(); TipoEvento tipo = new TipoEvento(); tipo.setDescricao("bla bla bla"); conn.getSession().save(tipo); conn.getSession().getTransaction().commit(); } catch (Exception e) { System.out.println(e.getMessage()); System.out.println(e.toString()); // TODO Auto-generated catch block e.printStackTrace(); } finally { } } }
apache-2.0
camac/Bootlegger
org.openntf.bootlegger/src/org/openntf/bootlegger/pref/IBootleggerPreferenceListener.java
903
/******************************************************************************* * Copyright 2015 Cameron Gregor * 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.openntf.bootlegger.pref; public abstract interface IBootleggerPreferenceListener { public abstract void preferenceChanged(BootleggerPreferenceChangeEvent e); }
apache-2.0
nakamura5akihito/six-oval
src/main/java/io/opensec/six/oval/model/independent/EntityItemLdaptypeType.java
2562
/** * SIX OVAL - https://nakamura5akihito.github.io/ * Copyright (C) 2010 Akihito Nakamura * * 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.opensec.six.oval.model.independent; import io.opensec.six.oval.model.sc.EntityItemStringType; /** * The EntityItemLdaptypeType restricts a string value * to a specific set of values that specify the different types * of information that an ldap attribute can represent. * * @author Akihito Nakamura, AIST * @see <a href="http://oval.mitre.org/language/">OVAL Language</a> */ public class EntityItemLdaptypeType extends EntityItemStringType { /** * Constructor. */ public EntityItemLdaptypeType() { } public EntityItemLdaptypeType( final String content ) { super( content ); } public EntityItemLdaptypeType( final HashTypeEnumeration content ) { super( (content == null ? null : content.value()) ); } //************************************************************** // EntityItemBase //************************************************************** @Override public void setContent( final String content ) { if (content != null) { //validation HashTypeEnumeration.fromValue( content ); } super.setContent( content ); } //************************************************************** // java.lang.Object //************************************************************** @Override public int hashCode() { return super.hashCode(); } @Override public boolean equals( final Object obj ) { if (this == obj) { return true; } if (!(obj instanceof EntityItemLdaptypeType)) { return false; } return super.equals( obj ); } } //EntityItemLdaptypeType
apache-2.0
o3project/openflowj-otn
src/main/java/org/projectfloodlight/openflow/protocol/ver14/OFAsyncConfigPropExperimenterSlaveVer14.java
5573
// 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.ver14; 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.oxm.*; 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 org.jboss.netty.buffer.ChannelBuffer; import com.google.common.hash.PrimitiveSink; import com.google.common.hash.Funnel; class OFAsyncConfigPropExperimenterSlaveVer14 implements OFAsyncConfigPropExperimenterSlave { private static final Logger logger = LoggerFactory.getLogger(OFAsyncConfigPropExperimenterSlaveVer14.class); // version: 1.4 final static byte WIRE_VERSION = 5; final static int LENGTH = 4; // OF message fields // // Immutable default instance final static OFAsyncConfigPropExperimenterSlaveVer14 DEFAULT = new OFAsyncConfigPropExperimenterSlaveVer14( ); final static OFAsyncConfigPropExperimenterSlaveVer14 INSTANCE = new OFAsyncConfigPropExperimenterSlaveVer14(); // private empty constructor - use shared instance! private OFAsyncConfigPropExperimenterSlaveVer14() { } // Accessors for OF message fields @Override public int getType() { return 0xfffe; } @Override public OFVersion getVersion() { return OFVersion.OF_14; } // no data members - do not support builder public OFAsyncConfigPropExperimenterSlave.Builder createBuilder() { throw new UnsupportedOperationException("OFAsyncConfigPropExperimenterSlaveVer14 has no mutable properties -- builder unneeded"); } final static Reader READER = new Reader(); static class Reader implements OFMessageReader<OFAsyncConfigPropExperimenterSlave> { @Override public OFAsyncConfigPropExperimenterSlave readFrom(ChannelBuffer bb) throws OFParseError { int start = bb.readerIndex(); // fixed value property type == 0xfffe short type = bb.readShort(); if(type != (short) 0xfffe) throw new OFParseError("Wrong type: Expected=0xfffe(0xfffe), got="+type); int length = U16.f(bb.readShort()); if(length != 4) throw new OFParseError("Wrong length: Expected=4(4), 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); if(logger.isTraceEnabled()) logger.trace("readFrom - returning shared instance={}", INSTANCE); return INSTANCE; } } public void putTo(PrimitiveSink sink) { FUNNEL.funnel(this, sink); } final static OFAsyncConfigPropExperimenterSlaveVer14Funnel FUNNEL = new OFAsyncConfigPropExperimenterSlaveVer14Funnel(); static class OFAsyncConfigPropExperimenterSlaveVer14Funnel implements Funnel<OFAsyncConfigPropExperimenterSlaveVer14> { private static final long serialVersionUID = 1L; @Override public void funnel(OFAsyncConfigPropExperimenterSlaveVer14 message, PrimitiveSink sink) { // fixed value property type = 0xfffe sink.putShort((short) 0xfffe); // fixed value property length = 4 sink.putShort((short) 0x4); } } public void writeTo(ChannelBuffer bb) { WRITER.write(bb, this); } final static Writer WRITER = new Writer(); static class Writer implements OFMessageWriter<OFAsyncConfigPropExperimenterSlaveVer14> { @Override public void write(ChannelBuffer bb, OFAsyncConfigPropExperimenterSlaveVer14 message) { // fixed value property type = 0xfffe bb.writeShort((short) 0xfffe); // fixed value property length = 4 bb.writeShort((short) 0x4); } } @Override public String toString() { StringBuilder b = new StringBuilder("OFAsyncConfigPropExperimenterSlaveVer14("); 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; return true; } @Override public int hashCode() { int result = 1; return result; } }
apache-2.0
xushaomin/diamond-v2.1.1
diamond-utils/src/main/java/com/taobao/diamond/io/watch/WatchKey.java
7651
/* * (C) 2007-2012 Alibaba Group Holding Limited. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * Authors: * leiwen <chrisredfield1985@126.com> , boyan <killme2008@gmail.com> */ package com.taobao.diamond.io.watch; import java.io.File; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Set; import com.taobao.diamond.io.Path; import com.taobao.diamond.io.watch.util.PathNode; /** * WatchKey,表示一个注册的的凭证 * * @author boyan * @date 2010-5-4 */ public class WatchKey { private volatile boolean valid; private final PathNode root; private List<WatchEvent<?>> changedEvents; private final Set<WatchEvent.Kind<?>> filterSet = new HashSet<WatchEvent.Kind<?>>(); private final WatchService watcher; public WatchKey(final Path path, final WatchService watcher, boolean fireCreatedEventOnIndex, WatchEvent.Kind<?>... events) { valid = true; this.watcher = watcher; // 建立内存索引 this.root = new PathNode(path, true); if (events != null) { for (WatchEvent.Kind<?> event : events) { filterSet.add(event); } } LinkedList<WatchEvent<?>> changedEvents = new LinkedList<WatchEvent<?>>(); index(this.root, fireCreatedEventOnIndex, changedEvents); this.changedEvents = changedEvents; } /** * 索引目录 * * @param node */ private void index(PathNode node, boolean fireCreatedEventOnIndex, LinkedList<WatchEvent<?>> changedEvents) { File file = node.getPath().getFile(); if (!file.isDirectory()) { return; } File[] subFiles = file.listFiles(); if (subFiles != null) { for (File subFile : subFiles) { PathNode subNode = new PathNode(new Path(subFile), false); if (fireCreatedEventOnIndex) { changedEvents.add(new WatchEvent<Path>(StandardWatchEventKind.ENTRY_CREATE, 1, subNode.getPath())); } node.addChild(subNode); if (subNode.getPath().isDirectory()) { index(subNode, fireCreatedEventOnIndex, changedEvents); } } } } public void cancel() { this.valid = false; } @Override public String toString() { return "WatchKey [root=" + root + ", valid=" + valid + "]"; } public boolean isValid() { return valid && root != null; } public List<WatchEvent<?>> pollEvents() { if (changedEvents != null) { List<WatchEvent<?>> result = changedEvents; changedEvents = null; return result; } return null; } /** * 检测是否有变化 * * @return */ boolean check() { if (this.changedEvents != null && this.changedEvents.size() > 0) return true; if (!this.valid) return false; List<WatchEvent<?>> list = new LinkedList<WatchEvent<?>>(); if (check(root, list)) { this.changedEvents = list; return true; } else { return false; } } @SuppressWarnings("unused") private boolean check(PathNode node, List<WatchEvent<?>> changedEvents) { Path nodePath = node.getPath(); File nodeNewFile = new File(nodePath.getAbsolutePath()); if (nodePath != null) { if (node.isRoot()) { if (!nodeNewFile.exists()) return fireOnRootDeleted(changedEvents, nodeNewFile); else { return checkNodeChildren(node, changedEvents, nodeNewFile); } } else { return checkNodeChildren(node, changedEvents, nodeNewFile); } } else throw new IllegalStateException("PathNode没有path"); } private boolean checkNodeChildren(PathNode node, List<WatchEvent<?>> changedEvents, File nodeNewFile) { boolean changed = false; Iterator<PathNode> it = node.getChildren().iterator(); // 用于判断是否有新增文件或者目录的现有名称集合 Set<String> childNameSet = new HashSet<String>(); while (it.hasNext()) { PathNode child = it.next(); Path childPath = child.getPath(); childNameSet.add(childPath.getName()); File childNewFile = new File(childPath.getAbsolutePath()); // 1、判断文件是否还存在 if (!childNewFile.exists() && filterSet.contains(StandardWatchEventKind.ENTRY_DELETE)) { changed = true; changedEvents.add(new WatchEvent<Path>(StandardWatchEventKind.ENTRY_DELETE, 1, childPath)); it.remove();// 移除节点 } // 2、如果是文件,判断是否被修改 if (childPath.isFile()) { if (checkFile(changedEvents, child, childNewFile) && !changed) { changed = true; } } // 3、递归检测目录 if (childPath.isDirectory()) { if (check(child, changedEvents) && !changed) { changed = true; } } } // 查看是否有新增文件 File[] newChildFiles = nodeNewFile.listFiles(); if(newChildFiles!=null) for (File newChildFile : newChildFiles) { if (!childNameSet.contains(newChildFile.getName()) && filterSet.contains(StandardWatchEventKind.ENTRY_CREATE)) { changed = true; Path newChildPath = new Path(newChildFile); changedEvents.add(new WatchEvent<Path>(StandardWatchEventKind.ENTRY_CREATE, 1, newChildPath)); PathNode newSubNode = new PathNode(newChildPath, false); node.addChild(newSubNode);// 新增子节点 // 如果是目录,递归调用 if (newChildFile.isDirectory()) { checkNodeChildren(newSubNode, changedEvents, newChildFile); } } } return changed; } private boolean checkFile(List<WatchEvent<?>> changedEvents, PathNode child, File childNewFile) { boolean changed = false; // 查看文件是否被修改 if (childNewFile.lastModified() != child.lastModified() && filterSet.contains(StandardWatchEventKind.ENTRY_MODIFY)) { changed = true; Path newChildPath = new Path(childNewFile); changedEvents.add(new WatchEvent<Path>(StandardWatchEventKind.ENTRY_MODIFY, 1, newChildPath)); child.setPath(newChildPath);// 更新path } return changed; } private boolean fireOnRootDeleted(List<WatchEvent<?>> changedEvents, File nodeNewFile) { this.valid = false; if (filterSet.contains(StandardWatchEventKind.ENTRY_DELETE)) { changedEvents.add(new WatchEvent<Path>(StandardWatchEventKind.ENTRY_DELETE, 1, new Path(nodeNewFile))); return true; } return false; } public boolean reset() { if (!valid) return false; if (root == null) return false; return this.watcher.resetKey(this); } }
apache-2.0
VHAINNOVATIONS/Telepathology
Source/Java/VixCommon/main/src/java/gov/va/med/imaging/VixURNProvider.java
1544
/** * Package: MAG - VistA Imaging WARNING: Per VHA Directive 2004-038, this routine should not be modified. Date Created: Jun 30, 2011 Site Name: Washington OI Field Office, Silver Spring, MD Developer: VHAISWWERFEJ Description: ;; +--------------------------------------------------------------------+ ;; Property of the US Government. ;; No permission to copy or redistribute this software is given. ;; Use of unreleased versions of this software requires the user ;; to execute a written test agreement with the VistA Imaging ;; Development Office of the Department of Veterans Affairs, ;; telephone (301) 734-0100. ;; ;; The Food and Drug Administration classifies this software as ;; a Class II medical device. As such, it may not be changed ;; in any way. Modifications to this software may result in an ;; adulterated medical device under 21CFR820, the use of which ;; is considered to be a violation of US Federal Statutes. ;; +--------------------------------------------------------------------+ */ package gov.va.med.imaging; import gov.va.med.URN; import gov.va.med.URNProvider; /** * Provides URNs common to the VIX * * @author VHAISWWERFEJ * */ public class VixURNProvider extends URNProvider { @SuppressWarnings("unchecked") @Override protected Class<? extends URN>[] getUrnClasses() { return new Class [] { ImageAnnotationURN.class }; } }
apache-2.0
google/nomulus
core/src/main/java/google/registry/tools/DedupeOneTimeBillingEventIdsCommand.java
3672
// Copyright 2020 The Nomulus 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. package google.registry.tools; import static com.google.common.base.Preconditions.checkState; import static google.registry.persistence.transaction.TransactionManagerFactory.tm; import com.beust.jcommander.Parameters; import google.registry.model.billing.BillingEvent; import google.registry.model.billing.BillingEvent.OneTime; import google.registry.model.domain.DomainBase; import google.registry.persistence.VKey; /** * Command to dedupe {@link BillingEvent.OneTime} entities having duplicate IDs. * * <p>This command is used to address the duplicate id issue we found for certain {@link * BillingEvent.OneTime} entities. The command reassigns an application wide unique id to the * problematic entity and resaves it, it also resaves the entity having reference to the problematic * entity with the updated id. * * <p>To use this command, you will need to provide the path to a file containing a list of strings * representing the literal of Objectify key for the problematic entities. An example key literal * is: * * <pre> * "DomainBase", "111111-TEST", "HistoryEntry", 2222222, "OneTime", 3333333 * </pre> * * <p>Note that the double quotes are part of the key literal. The key literal can be retrieved from * the column <code>__key__.path</code> in BigQuery. */ @Parameters( separators = " =", commandDescription = "Dedupe BillingEvent.OneTime entities with duplicate IDs.") public class DedupeOneTimeBillingEventIdsCommand extends ReadEntityFromKeyPathCommand<OneTime> { @Override void process(OneTime entity) { VKey<OneTime> key = entity.createVKey(); VKey<DomainBase> domainKey = getGrandParentAsDomain(key); DomainBase domain = tm().transact(() -> tm().loadByKey(domainKey)); // The BillingEvent.OneTime entity to be resaved should be the billing event created a few // years ago, so they should not be referenced from TransferData and GracePeriod in the domain. assertNotInDomainTransferData(domain, key); domain .getGracePeriods() .forEach( gracePeriod -> checkState( !gracePeriod.getOneTimeBillingEvent().equals(key), "Entity %s is referenced by a grace period in domain %s", key, domainKey)); // By setting id to 0L, Buildable.build() will assign an application wide unique id to it. BillingEvent.OneTime uniqIdBillingEvent = entity.asBuilder().setId(0L).build(); stageEntityKeyChange(entity, uniqIdBillingEvent); } private static void assertNotInDomainTransferData(DomainBase domainBase, VKey<?> key) { if (!domainBase.getTransferData().isEmpty()) { domainBase .getTransferData() .getServerApproveEntities() .forEach( entityKey -> checkState( !entityKey.equals(key), "Entity %s is referenced by the transfer data in domain %s", key, domainBase.createVKey())); } } }
apache-2.0
markkimsal/pengyou-clients
webdavclient/ant/src/java/org/apache/webdav/ant/WebdavFileSet.java
4547
// vi: set ts=3 sw=3: /* * $Header$ * $Revision: 207687 $ * $Date: 2004-08-20 18:53:22 +0800 (Fri, 20 Aug 2004) $ * ======================================================================== * Copyright 2004 The Apache Software 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. * ======================================================================== */ package org.apache.webdav.ant; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpURL; import org.apache.commons.httpclient.URIException; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Project; import org.apache.tools.ant.types.PatternSet; /** */ public class WebdavFileSet { private PatternSet patterns = new PatternSet(); private List patternSets = new ArrayList(); private String directory = null; private boolean isCaseSensitive = true; private static final String[] DEFAULT_INCLUDES = { "**/*" }; public WebdavFileSet() { } public CollectionScanner getCollectionScanner( Project project, HttpClient httpClient, HttpURL baseUrl) { validate(); CollectionScanner scanner = new CollectionScanner(); try { scanner.setBaseURL(Utils.createHttpURL(baseUrl, directory)); } catch (URIException e) { throw new BuildException("Invalid URL. " + e.toString(), e); } scanner.setHttpClient(httpClient); scanner.setCaseSensitive(this.isCaseSensitive); if (this.patterns.getExcludePatterns(project) == null && this.patterns.getIncludePatterns(project) == null && this.patternSets.size() == 0) { scanner.setIncludes(DEFAULT_INCLUDES); } else { scanner.setExcludes(this.patterns.getExcludePatterns(project)); scanner.setIncludes(this.patterns.getIncludePatterns(project)); for (Iterator i = this.patternSets.iterator(); i.hasNext();) { PatternSet patternSet = (PatternSet)i.next(); scanner.addExcludes(patternSet.getExcludePatterns(project)); scanner.addIncludes(patternSet.getIncludePatterns(project)); } } scanner.scan(); return scanner; } protected void validate() { if (this.directory == null) this.directory = ""; } /** * Sets the <code>dir</code> attribute. * @param dir */ public void setDir(String dir) { this.directory = dir; if (!this.directory.endsWith("/")) { this.directory += "/"; } if (this.directory.startsWith("/")) { this.directory = this.directory.substring(1); } } /** * Sets the <code>casesensitive</code> attribute. * @param b */ public void setCasesensitive(boolean b) { this.isCaseSensitive = b; } /** * Creates nested include and adds it to the patterns. */ public PatternSet.NameEntry createInclude() { return this.patterns.createInclude(); } /** * Creates nested includesfile and adds it to the patterns. */ public PatternSet.NameEntry createIncludesFile() { return this.patterns.createIncludesFile(); } /** * Creates nested exclude and adds it to the patterns. */ public PatternSet.NameEntry createExclude() { return this.patterns.createExclude(); } /** * Creates nested excludesfile and adds it to the patterns. */ public PatternSet.NameEntry createExcludesFile() { return this.patterns.createExcludesFile(); } /** * Creates a nested patternset. */ public PatternSet createPatternSet() { PatternSet patterns = new PatternSet(); this.patternSets.add(patterns); return patterns; } }
apache-2.0
brendandouglas/intellij
java/tests/integrationtests/com/google/idea/blaze/java/run/producers/BlazeJavaAbstractTestCaseConfigurationProducerTest.java
10585
/* * Copyright 2017 The Bazel 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. */ package com.google.idea.blaze.java.run.producers; import static com.google.common.truth.Truth.assertThat; import com.google.idea.blaze.base.command.BlazeFlags; import com.google.idea.blaze.base.ideinfo.TargetIdeInfo; import com.google.idea.blaze.base.ideinfo.TargetMapBuilder; import com.google.idea.blaze.base.lang.buildfile.psi.util.PsiUtils; import com.google.idea.blaze.base.model.MockBlazeProjectDataBuilder; import com.google.idea.blaze.base.model.MockBlazeProjectDataManager; import com.google.idea.blaze.base.model.primitives.TargetExpression; import com.google.idea.blaze.base.model.primitives.WorkspacePath; import com.google.idea.blaze.base.run.BlazeCommandRunConfiguration; import com.google.idea.blaze.base.run.producer.BlazeRunConfigurationProducerTestCase; import com.google.idea.blaze.base.sync.data.BlazeProjectDataManager; import com.intellij.execution.actions.ConfigurationContext; import com.intellij.execution.actions.ConfigurationFromContext; import com.intellij.execution.configurations.RunConfiguration; import com.intellij.openapi.util.EmptyRunnable; import com.intellij.psi.PsiClass; import com.intellij.psi.PsiClassOwner; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiMethod; import java.util.List; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Integration tests for {@link BlazeJavaAbstractTestCaseConfigurationProducer}. */ @RunWith(JUnit4.class) public class BlazeJavaAbstractTestCaseConfigurationProducerTest extends BlazeRunConfigurationProducerTestCase { @Test public void testIgnoreTestClassWitNoTestSubclasses() { PsiFile javaFile = createAndIndexFile( new WorkspacePath("java/com/google/test/TestClass.java"), "package com.google.test;", "@org.junit.runner.RunWith(org.junit.runners.JUnit4.class)", "public class TestClass {", " @org.junit.Test", " public void testMethod1() {}", " @org.junit.Test", " public void testMethod2() {}", "}"); PsiClass javaClass = ((PsiClassOwner) javaFile).getClasses()[0]; assertThat(javaClass).isNotNull(); ConfigurationContext context = createContextFromPsi(javaClass); ConfigurationFromContext fromContext = new BlazeJavaAbstractTestCaseConfigurationProducer() .createConfigurationFromContext(context); assertThat(fromContext).isNull(); } @Test public void testHandlesNonAbstractClassWithTestSubclass() { workspace.createPsiDirectory(new WorkspacePath("java/com/google/test")); PsiFile superClassFile = createAndIndexFile( new WorkspacePath("java/com/google/test/NonAbstractSuperClassTestCase.java"), "package com.google.test;", "@org.junit.runner.RunWith(org.junit.runners.JUnit4.class)", "public class NonAbstractSuperClassTestCase {", " @org.junit.Test", " public void testMethod() {}", "}"); createAndIndexFile( new WorkspacePath("java/com/google/test/TestClass.java"), "package com.google.test;", "import com.google.test.NonAbstractSuperClassTestCase;", "@org.junit.runner.RunWith(org.junit.runners.JUnit4.class)", "public class TestClass extends NonAbstractSuperClassTestCase {", " @org.junit.Test", " public void anotherTestMethod() {}", "}"); PsiClass javaClass = ((PsiClassOwner) superClassFile).getClasses()[0]; assertThat(javaClass).isNotNull(); ConfigurationContext context = createContextFromPsi(superClassFile); List<ConfigurationFromContext> configurations = context.getConfigurationsFromContext(); assertThat(configurations).hasSize(1); ConfigurationFromContext fromContext = configurations.get(0); assertThat(fromContext.isProducedBy(BlazeJavaAbstractTestCaseConfigurationProducer.class)) .isTrue(); assertThat(fromContext.getSourceElement()).isEqualTo(javaClass); RunConfiguration config = fromContext.getConfiguration(); assertThat(config).isInstanceOf(BlazeCommandRunConfiguration.class); BlazeCommandRunConfiguration blazeConfig = (BlazeCommandRunConfiguration) config; assertThat(blazeConfig.getTarget()).isNull(); assertThat(blazeConfig.getName()) .isEqualTo("Choose subclass for NonAbstractSuperClassTestCase"); } @Test public void testConfigurationCreatedFromAbstractClass() { workspace.createPsiDirectory(new WorkspacePath("java/com/google/test")); PsiFile abstractClassFile = createAndIndexFile( new WorkspacePath("java/com/google/test/AbstractTestCase.java"), "package com.google.test;", "public abstract class AbstractTestCase {}"); createAndIndexFile( new WorkspacePath("java/com/google/test/TestClass.java"), "package com.google.test;", "import com.google.test.AbstractTestCase;", "@org.junit.runner.RunWith(org.junit.runners.JUnit4.class)", "public class TestClass extends AbstractTestCase {", " @org.junit.Test", " public void testMethod1() {}", " @org.junit.Test", " public void testMethod2() {}", "}"); PsiClass javaClass = ((PsiClassOwner) abstractClassFile).getClasses()[0]; assertThat(javaClass).isNotNull(); ConfigurationContext context = createContextFromPsi(abstractClassFile); List<ConfigurationFromContext> configurations = context.getConfigurationsFromContext(); assertThat(configurations).hasSize(1); ConfigurationFromContext fromContext = configurations.get(0); assertThat(fromContext.isProducedBy(BlazeJavaAbstractTestCaseConfigurationProducer.class)) .isTrue(); assertThat(fromContext.getSourceElement()).isEqualTo(javaClass); RunConfiguration config = fromContext.getConfiguration(); assertThat(config).isInstanceOf(BlazeCommandRunConfiguration.class); BlazeCommandRunConfiguration blazeConfig = (BlazeCommandRunConfiguration) config; assertThat(blazeConfig.getTarget()).isNull(); assertThat(blazeConfig.getName()).isEqualTo("Choose subclass for AbstractTestCase"); MockBlazeProjectDataBuilder builder = MockBlazeProjectDataBuilder.builder(workspaceRoot); builder.setTargetMap( TargetMapBuilder.builder() .addTarget( TargetIdeInfo.builder() .setKind("java_test") .setLabel("//java/com/google/test:TestClass") .addSource(sourceRoot("java/com/google/test/TestClass.java")) .build()) .build()); registerProjectService( BlazeProjectDataManager.class, new MockBlazeProjectDataManager(builder.build())); BlazeJavaAbstractTestCaseConfigurationProducer.chooseSubclass( fromContext, context, EmptyRunnable.INSTANCE); assertThat(blazeConfig.getTarget()) .isEqualTo(TargetExpression.fromStringSafe("//java/com/google/test:TestClass")); assertThat(getTestFilterContents(blazeConfig)) .isEqualTo(BlazeFlags.TEST_FILTER + "=com.google.test.TestClass#"); } @Test public void testConfigurationCreatedFromMethodInAbstractClass() { PsiFile abstractClassFile = createAndIndexFile( new WorkspacePath("java/com/google/test/AbstractTestCase.java"), "package com.google.test;", "public abstract class AbstractTestCase {", " @org.junit.Test", " public void testMethod() {}", "}"); createAndIndexFile( new WorkspacePath("java/com/google/test/TestClass.java"), "package com.google.test;", "import com.google.test.AbstractTestCase;", "import org.junit.runner.RunWith;", "import org.junit.runners.JUnit4;", "@org.junit.runner.RunWith(org.junit.runners.JUnit4.class)", "public class TestClass extends AbstractTestCase {}"); PsiClass javaClass = ((PsiClassOwner) abstractClassFile).getClasses()[0]; PsiMethod method = PsiUtils.findFirstChildOfClassRecursive(javaClass, PsiMethod.class); assertThat(method).isNotNull(); ConfigurationContext context = createContextFromPsi(method); List<ConfigurationFromContext> configurations = context.getConfigurationsFromContext(); assertThat(configurations).hasSize(1); ConfigurationFromContext fromContext = configurations.get(0); assertThat(fromContext.isProducedBy(BlazeJavaAbstractTestCaseConfigurationProducer.class)) .isTrue(); assertThat(fromContext.getSourceElement()).isEqualTo(method); RunConfiguration config = fromContext.getConfiguration(); assertThat(config).isInstanceOf(BlazeCommandRunConfiguration.class); BlazeCommandRunConfiguration blazeConfig = (BlazeCommandRunConfiguration) config; assertThat(blazeConfig.getTarget()).isNull(); assertThat(blazeConfig.getName()).isEqualTo("Choose subclass for AbstractTestCase.testMethod"); MockBlazeProjectDataBuilder builder = MockBlazeProjectDataBuilder.builder(workspaceRoot); builder.setTargetMap( TargetMapBuilder.builder() .addTarget( TargetIdeInfo.builder() .setKind("java_test") .setLabel("//java/com/google/test:TestClass") .addSource(sourceRoot("java/com/google/test/TestClass.java")) .build()) .build()); registerProjectService( BlazeProjectDataManager.class, new MockBlazeProjectDataManager(builder.build())); BlazeJavaAbstractTestCaseConfigurationProducer.chooseSubclass( fromContext, context, EmptyRunnable.INSTANCE); assertThat(blazeConfig.getTarget()) .isEqualTo(TargetExpression.fromStringSafe("//java/com/google/test:TestClass")); assertThat(getTestFilterContents(blazeConfig)) .isEqualTo(BlazeFlags.TEST_FILTER + "=com.google.test.TestClass#testMethod$"); } }
apache-2.0
14kw/stash2chatwork
src/main/java/com/pragbits/stash/tools/ChatworkPayload.java
1331
package com.pragbits.stash.tools; import java.util.LinkedList; import java.util.List; public class ChatworkPayload { public String getChannel() { return channel; } public void setChannel(String channelName) { this.channel = channelName; } private String channel; public String getText() { return text; } public void setText(String text) { this.text = text; } private String text; public String getReqType() { return req_type; } public void setReqType(String req_type) { this.req_type = req_type; } private String req_type; public boolean isLinkNames() { return link_names; } public void setLinkNames(boolean link_names) { this.link_names = link_names; } private boolean link_names; public String getComment() { return comment; } public void setComment(String comment) { this.comment = comment; } private String comment; private List<ChatworkAttachment> attachments = new LinkedList<ChatworkAttachment>(); public void addAttachment(ChatworkAttachment chatworkAttachment) { this.attachments.add(chatworkAttachment); } public void removeAttachment(int index) { this.attachments.remove(index); } }
apache-2.0
JFixby/RedTriplane
red-triplane-ui-api/src/com/jfixby/r3/api/ui/unit/txt/TextBarMargin.java
144
package com.jfixby.r3.api.ui.unit.txt; public interface TextBarMargin { boolean isPixels(); boolean isPercentage(); float getValue(); }
apache-2.0
xushaomin/apple-jms
apple-jms-kafka/src/main/java/com/appleframework/jms/kafka/consumer/multithread/group/OriginalMessageConsumerThread.java
4214
package com.appleframework.jms.kafka.consumer.multithread.group; import java.time.Duration; import java.util.HashSet; import java.util.Properties; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; import org.apache.kafka.clients.consumer.ConsumerRecord; import org.apache.kafka.clients.consumer.ConsumerRecords; import org.apache.kafka.clients.consumer.KafkaConsumer; import org.apache.kafka.common.errors.WakeupException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.MDC; import com.appleframework.jms.core.config.TraceConfig; import com.appleframework.jms.core.consumer.AbstractMessageConusmer; import com.appleframework.jms.core.consumer.ErrorMessageProcessor; import com.appleframework.jms.core.utils.UuidUtils; /** * @author Cruise.Xu * */ public class OriginalMessageConsumerThread implements Runnable { private static Logger logger = LoggerFactory.getLogger(OriginalMessageConsumerThread.class); private String topic; private String prefix = ""; private ErrorMessageProcessor<ConsumerRecord<String, byte[]>> errorProcessor; private AbstractMessageConusmer<ConsumerRecord<String, byte[]>> messageConusmer; private Boolean errorProcessorLock = true; private KafkaConsumer<String, byte[]> consumer; private AtomicBoolean closed = new AtomicBoolean(false); private long timeout = Long.MAX_VALUE; private Properties properties; @Override public void run() { try { String[] topics = topic.split(","); Set<String> topicSet = new HashSet<String>(); for (String tp : topics) { String topicc = prefix + tp; topicSet.add(topicc); logger.warn("subscribe the topic -> " + topicc); } consumer = new KafkaConsumer<String, byte[]>(properties); consumer.subscribe(topicSet); Duration duration = Duration.ofMillis(timeout); while (!closed.get()) { ConsumerRecords<String, byte[]> records = consumer.poll(duration); for (ConsumerRecord<String, byte[]> record : records) { if (logger.isDebugEnabled()) { logger.debug("offset = %d, key = %s, value = %s%n", record.offset(), record.key(), record.value()); } if(TraceConfig.isSwitchTrace()) { if(null != record.key()) { MDC.put(TraceConfig.getTraceIdKey(), record.key()); } else { MDC.put(TraceConfig.getTraceIdKey(), UuidUtils.genUUID()); } } if(errorProcessorLock) { messageConusmer.processMessage(record); } else { try { messageConusmer.processMessage(record); } catch (Exception e) { processErrorMessage(record); } } } } } catch (WakeupException e) { if (!closed.get()) throw e; } } protected void processErrorMessage(ConsumerRecord<String, byte[]> message) { if(!errorProcessorLock && null != errorProcessor) { errorProcessor.processErrorMessage(message, messageConusmer); } } public void setTopic(String topic) { this.topic = topic.trim().replaceAll(" ", ""); } public void setErrorProcessorLock(Boolean errorProcessorLock) { this.errorProcessorLock = errorProcessorLock; } public void setTimeout(long timeout) { this.timeout = timeout; } public void destroy() { closed.set(true); consumer.wakeup(); if (null != errorProcessor) { errorProcessor.close(); } } public void commitSync() { consumer.commitSync(); } public void commitAsync() { consumer.commitAsync(); } public void setErrorProcessor(ErrorMessageProcessor<ConsumerRecord<String, byte[]>> errorProcessor) { this.errorProcessor = errorProcessor; } public void setPrefix(String prefix) { this.prefix = prefix; } public void setMessageConusmer(AbstractMessageConusmer<ConsumerRecord<String, byte[]>> messageConusmer) { this.messageConusmer = messageConusmer; } public void setProperties(Properties properties) { this.properties = properties; } }
apache-2.0
ibm-cds-labs/on-prem-connectivity-test-java-sample
src/main/java/com/ibm/cds/labs/onprem/OnPremDataSourceNotSupportedException.java
1171
/*------------------------------------------------------------------------------- Copyright IBM Corp. 2015 Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -------------------------------------------------------------------------------*/ package com.ibm.cds.labs.onprem; /** * Wraps the standard Java exception class * @author ptitzler * */ public class OnPremDataSourceNotSupportedException extends java.lang.Exception { private static final long serialVersionUID = 1L; public OnPremDataSourceNotSupportedException(String message) { super(message); } public OnPremDataSourceNotSupportedException(String message, Throwable throwable) { super(message, throwable); } } // class
apache-2.0
MarchMachao/ZHFS-WEB
src/main/java/com/smates/dbc2/vo/BaseMsg.java
518
package com.smates.dbc2.vo; public class BaseMsg { private boolean isSuccess; private String content; public BaseMsg(boolean isSuccess, String content) { super(); this.isSuccess = isSuccess; this.content = content; } public boolean isSuccess() { return isSuccess; } public void setSuccess(boolean isSuccess) { this.isSuccess = isSuccess; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } }
apache-2.0
jentfoo/aws-sdk-java
aws-java-sdk-iotthingsgraph/src/main/java/com/amazonaws/services/iotthingsgraph/model/transform/UpdateFlowTemplateRequestProtocolMarshaller.java
2769
/* * Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.iotthingsgraph.model.transform; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.Request; import com.amazonaws.http.HttpMethodName; import com.amazonaws.services.iotthingsgraph.model.*; import com.amazonaws.transform.Marshaller; import com.amazonaws.protocol.*; import com.amazonaws.protocol.Protocol; import com.amazonaws.annotation.SdkInternalApi; /** * UpdateFlowTemplateRequest Marshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class UpdateFlowTemplateRequestProtocolMarshaller implements Marshaller<Request<UpdateFlowTemplateRequest>, UpdateFlowTemplateRequest> { private static final OperationInfo SDK_OPERATION_BINDING = OperationInfo.builder().protocol(Protocol.AWS_JSON).requestUri("/") .httpMethodName(HttpMethodName.POST).hasExplicitPayloadMember(false).hasPayloadMembers(true) .operationIdentifier("IotThingsGraphFrontEndService.UpdateFlowTemplate").serviceName("AWSIoTThingsGraph").build(); private final com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory; public UpdateFlowTemplateRequestProtocolMarshaller(com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory) { this.protocolFactory = protocolFactory; } public Request<UpdateFlowTemplateRequest> marshall(UpdateFlowTemplateRequest updateFlowTemplateRequest) { if (updateFlowTemplateRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { final ProtocolRequestMarshaller<UpdateFlowTemplateRequest> protocolMarshaller = protocolFactory.createProtocolMarshaller(SDK_OPERATION_BINDING, updateFlowTemplateRequest); protocolMarshaller.startMarshalling(); UpdateFlowTemplateRequestMarshaller.getInstance().marshall(updateFlowTemplateRequest, protocolMarshaller); return protocolMarshaller.finishMarshalling(); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
apache-2.0
airomem/airomem
airomem-core/src/main/java/pl/setblack/airomem/core/kryo/ReferenceResolver.java
2682
/* * Copyright (c) Jarek Ratajski, Licensed under the Apache License, Version 2.0 * http://www.apache.org/licenses/LICENSE-2.0 */ package pl.setblack.airomem.core.kryo; import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.util.Util; import java.math.BigDecimal; import java.math.BigInteger; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.Map; /** * */ public class ReferenceResolver implements com.esotericsoftware.kryo.ReferenceResolver { protected Kryo kryo; protected Map<Value, Integer> map = new HashMap<Value, Integer>(); protected final ArrayList<Object> readObjects = new ArrayList<Object>(); private static class Value { private Object val; //private int hash; public Value(Object val) { this.val = val; //this.hash = } @Override public int hashCode() { return System.identityHashCode(val); } @Override public boolean equals(Object obj) { return val == ((Value) obj).val; } } public void setKryo(Kryo kryo) { this.kryo = kryo; } public int addWrittenObject(Object object) { Value v = new Value(object); Integer i = map.get(v); if (i == null) { int ret = map.size(); map.put(v, ret); return ret; } else { return i; } } public int getWrittenId(Object object) { Value v = new Value(object); Integer i = map.get(v); if (i == null) { return -1; } else { return i; } } @SuppressWarnings("rawtypes") public int nextReadId(Class type) { int id = readObjects.size(); readObjects.add(null); return id; } public void setReadObject(int id, Object object) { readObjects.set(id, object); } @SuppressWarnings("rawtypes") public Object getReadObject(Class type, int id) { return readObjects.get(id); } public void reset() { readObjects.clear(); map.clear(); } /** * Returns false for all primitive wrappers. */ @SuppressWarnings("rawtypes") public boolean useReferences(Class type) { return !Util.isWrapperClass(type) && !type.equals(String.class) && !type.equals(Date.class) && !type.equals(BigDecimal.class) && !type.equals(BigInteger.class); } public void addReadObject(int id, Object object) { while (id >= readObjects.size()) { readObjects.add(null); } readObjects.set(id, object); } }
apache-2.0
eug48/hapi-fhir
hapi-fhir-structures-hl7org-dstu2/src/main/java/org/hl7/fhir/instance/model/ImplementationGuide.java
159361
package org.hl7.fhir.instance.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 Wed, Jul 13, 2016 05:32+1000 for FHIR v1.0.2 import java.util.*; import org.hl7.fhir.exceptions.FHIRException; import org.hl7.fhir.instance.model.Enumerations.ConformanceResourceStatus; import org.hl7.fhir.instance.model.Enumerations.ConformanceResourceStatusEnumFactory; import org.hl7.fhir.instance.model.api.IBaseBackboneElement; import org.hl7.fhir.utilities.Utilities; import ca.uhn.fhir.model.api.annotation.*; /** * A set of rules or how FHIR is used to solve a particular problem. This resource is used to gather all the parts of an implementation guide into a logical whole, and to publish a computable definition of all the parts. */ @ResourceDef(name="ImplementationGuide", profile="http://hl7.org/fhir/Profile/ImplementationGuide") public class ImplementationGuide extends DomainResource { public enum GuideDependencyType { /** * The guide is referred to by URL. */ REFERENCE, /** * The guide is embedded in this guide when published. */ INCLUSION, /** * added to help the parsers */ NULL; public static GuideDependencyType fromCode(String codeString) throws FHIRException { if (codeString == null || "".equals(codeString)) return null; if ("reference".equals(codeString)) return REFERENCE; if ("inclusion".equals(codeString)) return INCLUSION; throw new FHIRException("Unknown GuideDependencyType code '"+codeString+"'"); } public String toCode() { switch (this) { case REFERENCE: return "reference"; case INCLUSION: return "inclusion"; default: return "?"; } } public String getSystem() { switch (this) { case REFERENCE: return "http://hl7.org/fhir/guide-dependency-type"; case INCLUSION: return "http://hl7.org/fhir/guide-dependency-type"; default: return "?"; } } public String getDefinition() { switch (this) { case REFERENCE: return "The guide is referred to by URL."; case INCLUSION: return "The guide is embedded in this guide when published."; default: return "?"; } } public String getDisplay() { switch (this) { case REFERENCE: return "Reference"; case INCLUSION: return "Inclusion"; default: return "?"; } } } public static class GuideDependencyTypeEnumFactory implements EnumFactory<GuideDependencyType> { public GuideDependencyType fromCode(String codeString) throws IllegalArgumentException { if (codeString == null || "".equals(codeString)) if (codeString == null || "".equals(codeString)) return null; if ("reference".equals(codeString)) return GuideDependencyType.REFERENCE; if ("inclusion".equals(codeString)) return GuideDependencyType.INCLUSION; throw new IllegalArgumentException("Unknown GuideDependencyType code '"+codeString+"'"); } public Enumeration<GuideDependencyType> 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 ("reference".equals(codeString)) return new Enumeration<GuideDependencyType>(this, GuideDependencyType.REFERENCE); if ("inclusion".equals(codeString)) return new Enumeration<GuideDependencyType>(this, GuideDependencyType.INCLUSION); throw new FHIRException("Unknown GuideDependencyType code '"+codeString+"'"); } public String toCode(GuideDependencyType code) { if (code == GuideDependencyType.REFERENCE) return "reference"; if (code == GuideDependencyType.INCLUSION) return "inclusion"; return "?"; } } public enum GuideResourcePurpose { /** * The resource is intended as an example. */ EXAMPLE, /** * The resource defines a value set or concept map used in the implementation guide. */ TERMINOLOGY, /** * The resource defines a profile (StructureDefinition) that is used in the implementation guide. */ PROFILE, /** * The resource defines an extension (StructureDefinition) that is used in the implementation guide. */ EXTENSION, /** * The resource contains a dictionary that is part of the implementation guide. */ DICTIONARY, /** * The resource defines a logical model (in a StructureDefinition) that is used in the implementation guide. */ LOGICAL, /** * added to help the parsers */ NULL; public static GuideResourcePurpose fromCode(String codeString) throws FHIRException { if (codeString == null || "".equals(codeString)) return null; if ("example".equals(codeString)) return EXAMPLE; if ("terminology".equals(codeString)) return TERMINOLOGY; if ("profile".equals(codeString)) return PROFILE; if ("extension".equals(codeString)) return EXTENSION; if ("dictionary".equals(codeString)) return DICTIONARY; if ("logical".equals(codeString)) return LOGICAL; throw new FHIRException("Unknown GuideResourcePurpose code '"+codeString+"'"); } public String toCode() { switch (this) { case EXAMPLE: return "example"; case TERMINOLOGY: return "terminology"; case PROFILE: return "profile"; case EXTENSION: return "extension"; case DICTIONARY: return "dictionary"; case LOGICAL: return "logical"; default: return "?"; } } public String getSystem() { switch (this) { case EXAMPLE: return "http://hl7.org/fhir/guide-resource-purpose"; case TERMINOLOGY: return "http://hl7.org/fhir/guide-resource-purpose"; case PROFILE: return "http://hl7.org/fhir/guide-resource-purpose"; case EXTENSION: return "http://hl7.org/fhir/guide-resource-purpose"; case DICTIONARY: return "http://hl7.org/fhir/guide-resource-purpose"; case LOGICAL: return "http://hl7.org/fhir/guide-resource-purpose"; default: return "?"; } } public String getDefinition() { switch (this) { case EXAMPLE: return "The resource is intended as an example."; case TERMINOLOGY: return "The resource defines a value set or concept map used in the implementation guide."; case PROFILE: return "The resource defines a profile (StructureDefinition) that is used in the implementation guide."; case EXTENSION: return "The resource defines an extension (StructureDefinition) that is used in the implementation guide."; case DICTIONARY: return "The resource contains a dictionary that is part of the implementation guide."; case LOGICAL: return "The resource defines a logical model (in a StructureDefinition) that is used in the implementation guide."; default: return "?"; } } public String getDisplay() { switch (this) { case EXAMPLE: return "Example"; case TERMINOLOGY: return "Terminology"; case PROFILE: return "Profile"; case EXTENSION: return "Extension"; case DICTIONARY: return "Dictionary"; case LOGICAL: return "Logical Model"; default: return "?"; } } } public static class GuideResourcePurposeEnumFactory implements EnumFactory<GuideResourcePurpose> { public GuideResourcePurpose fromCode(String codeString) throws IllegalArgumentException { if (codeString == null || "".equals(codeString)) if (codeString == null || "".equals(codeString)) return null; if ("example".equals(codeString)) return GuideResourcePurpose.EXAMPLE; if ("terminology".equals(codeString)) return GuideResourcePurpose.TERMINOLOGY; if ("profile".equals(codeString)) return GuideResourcePurpose.PROFILE; if ("extension".equals(codeString)) return GuideResourcePurpose.EXTENSION; if ("dictionary".equals(codeString)) return GuideResourcePurpose.DICTIONARY; if ("logical".equals(codeString)) return GuideResourcePurpose.LOGICAL; throw new IllegalArgumentException("Unknown GuideResourcePurpose code '"+codeString+"'"); } public Enumeration<GuideResourcePurpose> 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 ("example".equals(codeString)) return new Enumeration<GuideResourcePurpose>(this, GuideResourcePurpose.EXAMPLE); if ("terminology".equals(codeString)) return new Enumeration<GuideResourcePurpose>(this, GuideResourcePurpose.TERMINOLOGY); if ("profile".equals(codeString)) return new Enumeration<GuideResourcePurpose>(this, GuideResourcePurpose.PROFILE); if ("extension".equals(codeString)) return new Enumeration<GuideResourcePurpose>(this, GuideResourcePurpose.EXTENSION); if ("dictionary".equals(codeString)) return new Enumeration<GuideResourcePurpose>(this, GuideResourcePurpose.DICTIONARY); if ("logical".equals(codeString)) return new Enumeration<GuideResourcePurpose>(this, GuideResourcePurpose.LOGICAL); throw new FHIRException("Unknown GuideResourcePurpose code '"+codeString+"'"); } public String toCode(GuideResourcePurpose code) { if (code == GuideResourcePurpose.EXAMPLE) return "example"; if (code == GuideResourcePurpose.TERMINOLOGY) return "terminology"; if (code == GuideResourcePurpose.PROFILE) return "profile"; if (code == GuideResourcePurpose.EXTENSION) return "extension"; if (code == GuideResourcePurpose.DICTIONARY) return "dictionary"; if (code == GuideResourcePurpose.LOGICAL) return "logical"; return "?"; } } public enum GuidePageKind { /** * This is a page of content that is included in the implementation guide. It has no particular function. */ PAGE, /** * This is a page that represents a human readable rendering of an example. */ EXAMPLE, /** * This is a page that represents a list of resources of one or more types. */ LIST, /** * This is a page showing where an included guide is injected. */ INCLUDE, /** * This is a page that lists the resources of a given type, and also creates pages for all the listed types as other pages in the section. */ DIRECTORY, /** * This is a page that creates the listed resources as a dictionary. */ DICTIONARY, /** * This is a generated page that contains the table of contents. */ TOC, /** * This is a page that represents a presented resource. This is typically used for generated conformance resource presentations. */ RESOURCE, /** * added to help the parsers */ NULL; public static GuidePageKind fromCode(String codeString) throws FHIRException { if (codeString == null || "".equals(codeString)) return null; if ("page".equals(codeString)) return PAGE; if ("example".equals(codeString)) return EXAMPLE; if ("list".equals(codeString)) return LIST; if ("include".equals(codeString)) return INCLUDE; if ("directory".equals(codeString)) return DIRECTORY; if ("dictionary".equals(codeString)) return DICTIONARY; if ("toc".equals(codeString)) return TOC; if ("resource".equals(codeString)) return RESOURCE; throw new FHIRException("Unknown GuidePageKind code '"+codeString+"'"); } public String toCode() { switch (this) { case PAGE: return "page"; case EXAMPLE: return "example"; case LIST: return "list"; case INCLUDE: return "include"; case DIRECTORY: return "directory"; case DICTIONARY: return "dictionary"; case TOC: return "toc"; case RESOURCE: return "resource"; default: return "?"; } } public String getSystem() { switch (this) { case PAGE: return "http://hl7.org/fhir/guide-page-kind"; case EXAMPLE: return "http://hl7.org/fhir/guide-page-kind"; case LIST: return "http://hl7.org/fhir/guide-page-kind"; case INCLUDE: return "http://hl7.org/fhir/guide-page-kind"; case DIRECTORY: return "http://hl7.org/fhir/guide-page-kind"; case DICTIONARY: return "http://hl7.org/fhir/guide-page-kind"; case TOC: return "http://hl7.org/fhir/guide-page-kind"; case RESOURCE: return "http://hl7.org/fhir/guide-page-kind"; default: return "?"; } } public String getDefinition() { switch (this) { case PAGE: return "This is a page of content that is included in the implementation guide. It has no particular function."; case EXAMPLE: return "This is a page that represents a human readable rendering of an example."; case LIST: return "This is a page that represents a list of resources of one or more types."; case INCLUDE: return "This is a page showing where an included guide is injected."; case DIRECTORY: return "This is a page that lists the resources of a given type, and also creates pages for all the listed types as other pages in the section."; case DICTIONARY: return "This is a page that creates the listed resources as a dictionary."; case TOC: return "This is a generated page that contains the table of contents."; case RESOURCE: return "This is a page that represents a presented resource. This is typically used for generated conformance resource presentations."; default: return "?"; } } public String getDisplay() { switch (this) { case PAGE: return "Page"; case EXAMPLE: return "Example"; case LIST: return "List"; case INCLUDE: return "Include"; case DIRECTORY: return "Directory"; case DICTIONARY: return "Dictionary"; case TOC: return "Table Of Contents"; case RESOURCE: return "Resource"; default: return "?"; } } } public static class GuidePageKindEnumFactory implements EnumFactory<GuidePageKind> { public GuidePageKind fromCode(String codeString) throws IllegalArgumentException { if (codeString == null || "".equals(codeString)) if (codeString == null || "".equals(codeString)) return null; if ("page".equals(codeString)) return GuidePageKind.PAGE; if ("example".equals(codeString)) return GuidePageKind.EXAMPLE; if ("list".equals(codeString)) return GuidePageKind.LIST; if ("include".equals(codeString)) return GuidePageKind.INCLUDE; if ("directory".equals(codeString)) return GuidePageKind.DIRECTORY; if ("dictionary".equals(codeString)) return GuidePageKind.DICTIONARY; if ("toc".equals(codeString)) return GuidePageKind.TOC; if ("resource".equals(codeString)) return GuidePageKind.RESOURCE; throw new IllegalArgumentException("Unknown GuidePageKind code '"+codeString+"'"); } public Enumeration<GuidePageKind> 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 ("page".equals(codeString)) return new Enumeration<GuidePageKind>(this, GuidePageKind.PAGE); if ("example".equals(codeString)) return new Enumeration<GuidePageKind>(this, GuidePageKind.EXAMPLE); if ("list".equals(codeString)) return new Enumeration<GuidePageKind>(this, GuidePageKind.LIST); if ("include".equals(codeString)) return new Enumeration<GuidePageKind>(this, GuidePageKind.INCLUDE); if ("directory".equals(codeString)) return new Enumeration<GuidePageKind>(this, GuidePageKind.DIRECTORY); if ("dictionary".equals(codeString)) return new Enumeration<GuidePageKind>(this, GuidePageKind.DICTIONARY); if ("toc".equals(codeString)) return new Enumeration<GuidePageKind>(this, GuidePageKind.TOC); if ("resource".equals(codeString)) return new Enumeration<GuidePageKind>(this, GuidePageKind.RESOURCE); throw new FHIRException("Unknown GuidePageKind code '"+codeString+"'"); } public String toCode(GuidePageKind code) { if (code == GuidePageKind.PAGE) return "page"; if (code == GuidePageKind.EXAMPLE) return "example"; if (code == GuidePageKind.LIST) return "list"; if (code == GuidePageKind.INCLUDE) return "include"; if (code == GuidePageKind.DIRECTORY) return "directory"; if (code == GuidePageKind.DICTIONARY) return "dictionary"; if (code == GuidePageKind.TOC) return "toc"; if (code == GuidePageKind.RESOURCE) return "resource"; return "?"; } } @Block() public static class ImplementationGuideContactComponent extends BackboneElement implements IBaseBackboneElement { /** * The name of an individual to contact regarding the implementation guide. */ @Child(name = "name", type = {StringType.class}, order=1, min=0, max=1, modifier=false, summary=true) @Description(shortDefinition="Name of a individual to contact", formalDefinition="The name of an individual to contact regarding the implementation guide." ) protected StringType name; /** * Contact details for individual (if a name was provided) or the publisher. */ @Child(name = "telecom", type = {ContactPoint.class}, order=2, min=0, max=Child.MAX_UNLIMITED, modifier=false, summary=true) @Description(shortDefinition="Contact details for individual or publisher", formalDefinition="Contact details for individual (if a name was provided) or the publisher." ) protected List<ContactPoint> telecom; private static final long serialVersionUID = -1179697803L; /* * Constructor */ public ImplementationGuideContactComponent() { super(); } /** * @return {@link #name} (The name of an individual to contact regarding the implementation guide.). This is the underlying object with id, value and extensions. The accessor "getName" gives direct access to the value */ public StringType getNameElement() { if (this.name == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create ImplementationGuideContactComponent.name"); else if (Configuration.doAutoCreate()) this.name = new StringType(); // bb return this.name; } public boolean hasNameElement() { return this.name != null && !this.name.isEmpty(); } public boolean hasName() { return this.name != null && !this.name.isEmpty(); } /** * @param value {@link #name} (The name of an individual to contact regarding the implementation guide.). This is the underlying object with id, value and extensions. The accessor "getName" gives direct access to the value */ public ImplementationGuideContactComponent setNameElement(StringType value) { this.name = value; return this; } /** * @return The name of an individual to contact regarding the implementation guide. */ public String getName() { return this.name == null ? null : this.name.getValue(); } /** * @param value The name of an individual to contact regarding the implementation guide. */ public ImplementationGuideContactComponent setName(String value) { if (Utilities.noString(value)) this.name = null; else { if (this.name == null) this.name = new StringType(); this.name.setValue(value); } return this; } /** * @return {@link #telecom} (Contact details for individual (if a name was provided) or the publisher.) */ public List<ContactPoint> getTelecom() { if (this.telecom == null) this.telecom = new ArrayList<ContactPoint>(); return this.telecom; } public boolean hasTelecom() { if (this.telecom == null) return false; for (ContactPoint item : this.telecom) if (!item.isEmpty()) return true; return false; } /** * @return {@link #telecom} (Contact details for individual (if a name was provided) or the publisher.) */ // syntactic sugar public ContactPoint addTelecom() { //3 ContactPoint t = new ContactPoint(); if (this.telecom == null) this.telecom = new ArrayList<ContactPoint>(); this.telecom.add(t); return t; } // syntactic sugar public ImplementationGuideContactComponent addTelecom(ContactPoint t) { //3 if (t == null) return this; if (this.telecom == null) this.telecom = new ArrayList<ContactPoint>(); this.telecom.add(t); return this; } protected void listChildren(List<Property> childrenList) { super.listChildren(childrenList); childrenList.add(new Property("name", "string", "The name of an individual to contact regarding the implementation guide.", 0, java.lang.Integer.MAX_VALUE, name)); childrenList.add(new Property("telecom", "ContactPoint", "Contact details for individual (if a name was provided) or the publisher.", 0, java.lang.Integer.MAX_VALUE, telecom)); } @Override public void setProperty(String name, Base value) throws FHIRException { if (name.equals("name")) this.name = castToString(value); // StringType else if (name.equals("telecom")) this.getTelecom().add(castToContactPoint(value)); else super.setProperty(name, value); } @Override public Base addChild(String name) throws FHIRException { if (name.equals("name")) { throw new FHIRException("Cannot call addChild on a primitive type ImplementationGuide.name"); } else if (name.equals("telecom")) { return addTelecom(); } else return super.addChild(name); } public ImplementationGuideContactComponent copy() { ImplementationGuideContactComponent dst = new ImplementationGuideContactComponent(); copyValues(dst); dst.name = name == null ? null : name.copy(); if (telecom != null) { dst.telecom = new ArrayList<ContactPoint>(); for (ContactPoint i : telecom) dst.telecom.add(i.copy()); }; return dst; } @Override public boolean equalsDeep(Base other) { if (!super.equalsDeep(other)) return false; if (!(other instanceof ImplementationGuideContactComponent)) return false; ImplementationGuideContactComponent o = (ImplementationGuideContactComponent) other; return compareDeep(name, o.name, true) && compareDeep(telecom, o.telecom, true); } @Override public boolean equalsShallow(Base other) { if (!super.equalsShallow(other)) return false; if (!(other instanceof ImplementationGuideContactComponent)) return false; ImplementationGuideContactComponent o = (ImplementationGuideContactComponent) other; return compareValues(name, o.name, true); } public boolean isEmpty() { return super.isEmpty() && (name == null || name.isEmpty()) && (telecom == null || telecom.isEmpty()) ; } public String fhirType() { return "ImplementationGuide.contact"; } } @Block() public static class ImplementationGuideDependencyComponent extends BackboneElement implements IBaseBackboneElement { /** * How the dependency is represented when the guide is published. */ @Child(name = "type", type = {CodeType.class}, order=1, min=1, max=1, modifier=false, summary=true) @Description(shortDefinition="reference | inclusion", formalDefinition="How the dependency is represented when the guide is published." ) protected Enumeration<GuideDependencyType> type; /** * Where the dependency is located. */ @Child(name = "uri", type = {UriType.class}, order=2, min=1, max=1, modifier=false, summary=true) @Description(shortDefinition="Where to find dependency", formalDefinition="Where the dependency is located." ) protected UriType uri; private static final long serialVersionUID = 162447098L; /* * Constructor */ public ImplementationGuideDependencyComponent() { super(); } /* * Constructor */ public ImplementationGuideDependencyComponent(Enumeration<GuideDependencyType> type, UriType uri) { super(); this.type = type; this.uri = uri; } /** * @return {@link #type} (How the dependency is represented when the guide is published.). This is the underlying object with id, value and extensions. The accessor "getType" gives direct access to the value */ public Enumeration<GuideDependencyType> getTypeElement() { if (this.type == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create ImplementationGuideDependencyComponent.type"); else if (Configuration.doAutoCreate()) this.type = new Enumeration<GuideDependencyType>(new GuideDependencyTypeEnumFactory()); // 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} (How the dependency is represented when the guide is published.). This is the underlying object with id, value and extensions. The accessor "getType" gives direct access to the value */ public ImplementationGuideDependencyComponent setTypeElement(Enumeration<GuideDependencyType> value) { this.type = value; return this; } /** * @return How the dependency is represented when the guide is published. */ public GuideDependencyType getType() { return this.type == null ? null : this.type.getValue(); } /** * @param value How the dependency is represented when the guide is published. */ public ImplementationGuideDependencyComponent setType(GuideDependencyType value) { if (this.type == null) this.type = new Enumeration<GuideDependencyType>(new GuideDependencyTypeEnumFactory()); this.type.setValue(value); return this; } /** * @return {@link #uri} (Where the dependency is located.). This is the underlying object with id, value and extensions. The accessor "getUri" gives direct access to the value */ public UriType getUriElement() { if (this.uri == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create ImplementationGuideDependencyComponent.uri"); else if (Configuration.doAutoCreate()) this.uri = new UriType(); // bb return this.uri; } public boolean hasUriElement() { return this.uri != null && !this.uri.isEmpty(); } public boolean hasUri() { return this.uri != null && !this.uri.isEmpty(); } /** * @param value {@link #uri} (Where the dependency is located.). This is the underlying object with id, value and extensions. The accessor "getUri" gives direct access to the value */ public ImplementationGuideDependencyComponent setUriElement(UriType value) { this.uri = value; return this; } /** * @return Where the dependency is located. */ public String getUri() { return this.uri == null ? null : this.uri.getValue(); } /** * @param value Where the dependency is located. */ public ImplementationGuideDependencyComponent setUri(String value) { if (this.uri == null) this.uri = new UriType(); this.uri.setValue(value); return this; } protected void listChildren(List<Property> childrenList) { super.listChildren(childrenList); childrenList.add(new Property("type", "code", "How the dependency is represented when the guide is published.", 0, java.lang.Integer.MAX_VALUE, type)); childrenList.add(new Property("uri", "uri", "Where the dependency is located.", 0, java.lang.Integer.MAX_VALUE, uri)); } @Override public void setProperty(String name, Base value) throws FHIRException { if (name.equals("type")) this.type = new GuideDependencyTypeEnumFactory().fromType(value); // Enumeration<GuideDependencyType> else if (name.equals("uri")) this.uri = castToUri(value); // UriType else super.setProperty(name, value); } @Override public Base addChild(String name) throws FHIRException { if (name.equals("type")) { throw new FHIRException("Cannot call addChild on a primitive type ImplementationGuide.type"); } else if (name.equals("uri")) { throw new FHIRException("Cannot call addChild on a primitive type ImplementationGuide.uri"); } else return super.addChild(name); } public ImplementationGuideDependencyComponent copy() { ImplementationGuideDependencyComponent dst = new ImplementationGuideDependencyComponent(); copyValues(dst); dst.type = type == null ? null : type.copy(); dst.uri = uri == null ? null : uri.copy(); return dst; } @Override public boolean equalsDeep(Base other) { if (!super.equalsDeep(other)) return false; if (!(other instanceof ImplementationGuideDependencyComponent)) return false; ImplementationGuideDependencyComponent o = (ImplementationGuideDependencyComponent) other; return compareDeep(type, o.type, true) && compareDeep(uri, o.uri, true); } @Override public boolean equalsShallow(Base other) { if (!super.equalsShallow(other)) return false; if (!(other instanceof ImplementationGuideDependencyComponent)) return false; ImplementationGuideDependencyComponent o = (ImplementationGuideDependencyComponent) other; return compareValues(type, o.type, true) && compareValues(uri, o.uri, true); } public boolean isEmpty() { return super.isEmpty() && (type == null || type.isEmpty()) && (uri == null || uri.isEmpty()) ; } public String fhirType() { return "ImplementationGuide.dependency"; } } @Block() public static class ImplementationGuidePackageComponent extends BackboneElement implements IBaseBackboneElement { /** * The name for the group, as used in page.package. */ @Child(name = "name", type = {StringType.class}, order=1, min=1, max=1, modifier=false, summary=true) @Description(shortDefinition="Name used .page.package", formalDefinition="The name for the group, as used in page.package." ) protected StringType name; /** * Human readable text describing the package. */ @Child(name = "description", type = {StringType.class}, order=2, min=0, max=1, modifier=false, summary=false) @Description(shortDefinition="Human readable text describing the package", formalDefinition="Human readable text describing the package." ) protected StringType description; /** * A resource that is part of the implementation guide. Conformance resources (value set, structure definition, conformance statements etc.) are obvious candidates for inclusion, but any kind of resource can be included as an example resource. */ @Child(name = "resource", type = {}, order=3, min=1, max=Child.MAX_UNLIMITED, modifier=false, summary=true) @Description(shortDefinition="Resource in the implementation guide", formalDefinition="A resource that is part of the implementation guide. Conformance resources (value set, structure definition, conformance statements etc.) are obvious candidates for inclusion, but any kind of resource can be included as an example resource." ) protected List<ImplementationGuidePackageResourceComponent> resource; private static final long serialVersionUID = -701846580L; /* * Constructor */ public ImplementationGuidePackageComponent() { super(); } /* * Constructor */ public ImplementationGuidePackageComponent(StringType name) { super(); this.name = name; } /** * @return {@link #name} (The name for the group, as used in page.package.). This is the underlying object with id, value and extensions. The accessor "getName" gives direct access to the value */ public StringType getNameElement() { if (this.name == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create ImplementationGuidePackageComponent.name"); else if (Configuration.doAutoCreate()) this.name = new StringType(); // bb return this.name; } public boolean hasNameElement() { return this.name != null && !this.name.isEmpty(); } public boolean hasName() { return this.name != null && !this.name.isEmpty(); } /** * @param value {@link #name} (The name for the group, as used in page.package.). This is the underlying object with id, value and extensions. The accessor "getName" gives direct access to the value */ public ImplementationGuidePackageComponent setNameElement(StringType value) { this.name = value; return this; } /** * @return The name for the group, as used in page.package. */ public String getName() { return this.name == null ? null : this.name.getValue(); } /** * @param value The name for the group, as used in page.package. */ public ImplementationGuidePackageComponent setName(String value) { if (this.name == null) this.name = new StringType(); this.name.setValue(value); return this; } /** * @return {@link #description} (Human readable text describing the package.). This is the underlying object with id, value and extensions. The accessor "getDescription" gives direct access to the value */ public StringType getDescriptionElement() { if (this.description == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create ImplementationGuidePackageComponent.description"); else if (Configuration.doAutoCreate()) this.description = new StringType(); // bb return this.description; } public boolean hasDescriptionElement() { return this.description != null && !this.description.isEmpty(); } public boolean hasDescription() { return this.description != null && !this.description.isEmpty(); } /** * @param value {@link #description} (Human readable text describing the package.). This is the underlying object with id, value and extensions. The accessor "getDescription" gives direct access to the value */ public ImplementationGuidePackageComponent setDescriptionElement(StringType value) { this.description = value; return this; } /** * @return Human readable text describing the package. */ public String getDescription() { return this.description == null ? null : this.description.getValue(); } /** * @param value Human readable text describing the package. */ public ImplementationGuidePackageComponent setDescription(String value) { if (Utilities.noString(value)) this.description = null; else { if (this.description == null) this.description = new StringType(); this.description.setValue(value); } return this; } /** * @return {@link #resource} (A resource that is part of the implementation guide. Conformance resources (value set, structure definition, conformance statements etc.) are obvious candidates for inclusion, but any kind of resource can be included as an example resource.) */ public List<ImplementationGuidePackageResourceComponent> getResource() { if (this.resource == null) this.resource = new ArrayList<ImplementationGuidePackageResourceComponent>(); return this.resource; } public boolean hasResource() { if (this.resource == null) return false; for (ImplementationGuidePackageResourceComponent item : this.resource) if (!item.isEmpty()) return true; return false; } /** * @return {@link #resource} (A resource that is part of the implementation guide. Conformance resources (value set, structure definition, conformance statements etc.) are obvious candidates for inclusion, but any kind of resource can be included as an example resource.) */ // syntactic sugar public ImplementationGuidePackageResourceComponent addResource() { //3 ImplementationGuidePackageResourceComponent t = new ImplementationGuidePackageResourceComponent(); if (this.resource == null) this.resource = new ArrayList<ImplementationGuidePackageResourceComponent>(); this.resource.add(t); return t; } // syntactic sugar public ImplementationGuidePackageComponent addResource(ImplementationGuidePackageResourceComponent t) { //3 if (t == null) return this; if (this.resource == null) this.resource = new ArrayList<ImplementationGuidePackageResourceComponent>(); this.resource.add(t); return this; } protected void listChildren(List<Property> childrenList) { super.listChildren(childrenList); childrenList.add(new Property("name", "string", "The name for the group, as used in page.package.", 0, java.lang.Integer.MAX_VALUE, name)); childrenList.add(new Property("description", "string", "Human readable text describing the package.", 0, java.lang.Integer.MAX_VALUE, description)); childrenList.add(new Property("resource", "", "A resource that is part of the implementation guide. Conformance resources (value set, structure definition, conformance statements etc.) are obvious candidates for inclusion, but any kind of resource can be included as an example resource.", 0, java.lang.Integer.MAX_VALUE, resource)); } @Override public void setProperty(String name, Base value) throws FHIRException { if (name.equals("name")) this.name = castToString(value); // StringType else if (name.equals("description")) this.description = castToString(value); // StringType else if (name.equals("resource")) this.getResource().add((ImplementationGuidePackageResourceComponent) value); else super.setProperty(name, value); } @Override public Base addChild(String name) throws FHIRException { if (name.equals("name")) { throw new FHIRException("Cannot call addChild on a primitive type ImplementationGuide.name"); } else if (name.equals("description")) { throw new FHIRException("Cannot call addChild on a primitive type ImplementationGuide.description"); } else if (name.equals("resource")) { return addResource(); } else return super.addChild(name); } public ImplementationGuidePackageComponent copy() { ImplementationGuidePackageComponent dst = new ImplementationGuidePackageComponent(); copyValues(dst); dst.name = name == null ? null : name.copy(); dst.description = description == null ? null : description.copy(); if (resource != null) { dst.resource = new ArrayList<ImplementationGuidePackageResourceComponent>(); for (ImplementationGuidePackageResourceComponent i : resource) dst.resource.add(i.copy()); }; return dst; } @Override public boolean equalsDeep(Base other) { if (!super.equalsDeep(other)) return false; if (!(other instanceof ImplementationGuidePackageComponent)) return false; ImplementationGuidePackageComponent o = (ImplementationGuidePackageComponent) other; return compareDeep(name, o.name, true) && compareDeep(description, o.description, true) && compareDeep(resource, o.resource, true) ; } @Override public boolean equalsShallow(Base other) { if (!super.equalsShallow(other)) return false; if (!(other instanceof ImplementationGuidePackageComponent)) return false; ImplementationGuidePackageComponent o = (ImplementationGuidePackageComponent) other; return compareValues(name, o.name, true) && compareValues(description, o.description, true); } public boolean isEmpty() { return super.isEmpty() && (name == null || name.isEmpty()) && (description == null || description.isEmpty()) && (resource == null || resource.isEmpty()); } public String fhirType() { return "ImplementationGuide.package"; } } @Block() public static class ImplementationGuidePackageResourceComponent extends BackboneElement implements IBaseBackboneElement { /** * Why the resource is included in the guide. */ @Child(name = "purpose", type = {CodeType.class}, order=1, min=1, max=1, modifier=false, summary=true) @Description(shortDefinition="example | terminology | profile | extension | dictionary | logical", formalDefinition="Why the resource is included in the guide." ) protected Enumeration<GuideResourcePurpose> purpose; /** * A human assigned name for the resource. All resources SHOULD have a name, but the name may be extracted from the resource (e.g. ValueSet.name). */ @Child(name = "name", type = {StringType.class}, order=2, min=0, max=1, modifier=false, summary=true) @Description(shortDefinition="Human Name for the resource", formalDefinition="A human assigned name for the resource. All resources SHOULD have a name, but the name may be extracted from the resource (e.g. ValueSet.name)." ) protected StringType name; /** * A description of the reason that a resource has been included in the implementation guide. */ @Child(name = "description", type = {StringType.class}, order=3, min=0, max=1, modifier=false, summary=false) @Description(shortDefinition="Reason why included in guide", formalDefinition="A description of the reason that a resource has been included in the implementation guide." ) protected StringType description; /** * A short code that may be used to identify the resource throughout the implementation guide. */ @Child(name = "acronym", type = {StringType.class}, order=4, min=0, max=1, modifier=false, summary=false) @Description(shortDefinition="Short code to identify the resource", formalDefinition="A short code that may be used to identify the resource throughout the implementation guide." ) protected StringType acronym; /** * Where this resource is found. */ @Child(name = "source", type = {UriType.class}, order=5, min=1, max=1, modifier=false, summary=true) @Description(shortDefinition="Location of the resource", formalDefinition="Where this resource is found." ) protected Type source; /** * Another resource that this resource is an example for. This is mostly used for resources that are included as examples of StructureDefinitions. */ @Child(name = "exampleFor", type = {StructureDefinition.class}, order=6, min=0, max=1, modifier=false, summary=false) @Description(shortDefinition="Resource this is an example of (if applicable)", formalDefinition="Another resource that this resource is an example for. This is mostly used for resources that are included as examples of StructureDefinitions." ) protected Reference exampleFor; /** * The actual object that is the target of the reference (Another resource that this resource is an example for. This is mostly used for resources that are included as examples of StructureDefinitions.) */ protected StructureDefinition exampleForTarget; private static final long serialVersionUID = 428339533L; /* * Constructor */ public ImplementationGuidePackageResourceComponent() { super(); } /* * Constructor */ public ImplementationGuidePackageResourceComponent(Enumeration<GuideResourcePurpose> purpose, Type source) { super(); this.purpose = purpose; this.source = source; } /** * @return {@link #purpose} (Why the resource is included in the guide.). This is the underlying object with id, value and extensions. The accessor "getPurpose" gives direct access to the value */ public Enumeration<GuideResourcePurpose> getPurposeElement() { if (this.purpose == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create ImplementationGuidePackageResourceComponent.purpose"); else if (Configuration.doAutoCreate()) this.purpose = new Enumeration<GuideResourcePurpose>(new GuideResourcePurposeEnumFactory()); // bb return this.purpose; } public boolean hasPurposeElement() { return this.purpose != null && !this.purpose.isEmpty(); } public boolean hasPurpose() { return this.purpose != null && !this.purpose.isEmpty(); } /** * @param value {@link #purpose} (Why the resource is included in the guide.). This is the underlying object with id, value and extensions. The accessor "getPurpose" gives direct access to the value */ public ImplementationGuidePackageResourceComponent setPurposeElement(Enumeration<GuideResourcePurpose> value) { this.purpose = value; return this; } /** * @return Why the resource is included in the guide. */ public GuideResourcePurpose getPurpose() { return this.purpose == null ? null : this.purpose.getValue(); } /** * @param value Why the resource is included in the guide. */ public ImplementationGuidePackageResourceComponent setPurpose(GuideResourcePurpose value) { if (this.purpose == null) this.purpose = new Enumeration<GuideResourcePurpose>(new GuideResourcePurposeEnumFactory()); this.purpose.setValue(value); return this; } /** * @return {@link #name} (A human assigned name for the resource. All resources SHOULD have a name, but the name may be extracted from the resource (e.g. ValueSet.name).). This is the underlying object with id, value and extensions. The accessor "getName" gives direct access to the value */ public StringType getNameElement() { if (this.name == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create ImplementationGuidePackageResourceComponent.name"); else if (Configuration.doAutoCreate()) this.name = new StringType(); // bb return this.name; } public boolean hasNameElement() { return this.name != null && !this.name.isEmpty(); } public boolean hasName() { return this.name != null && !this.name.isEmpty(); } /** * @param value {@link #name} (A human assigned name for the resource. All resources SHOULD have a name, but the name may be extracted from the resource (e.g. ValueSet.name).). This is the underlying object with id, value and extensions. The accessor "getName" gives direct access to the value */ public ImplementationGuidePackageResourceComponent setNameElement(StringType value) { this.name = value; return this; } /** * @return A human assigned name for the resource. All resources SHOULD have a name, but the name may be extracted from the resource (e.g. ValueSet.name). */ public String getName() { return this.name == null ? null : this.name.getValue(); } /** * @param value A human assigned name for the resource. All resources SHOULD have a name, but the name may be extracted from the resource (e.g. ValueSet.name). */ public ImplementationGuidePackageResourceComponent setName(String value) { if (Utilities.noString(value)) this.name = null; else { if (this.name == null) this.name = new StringType(); this.name.setValue(value); } return this; } /** * @return {@link #description} (A description of the reason that a resource has been included in the implementation guide.). This is the underlying object with id, value and extensions. The accessor "getDescription" gives direct access to the value */ public StringType getDescriptionElement() { if (this.description == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create ImplementationGuidePackageResourceComponent.description"); else if (Configuration.doAutoCreate()) this.description = new StringType(); // bb return this.description; } public boolean hasDescriptionElement() { return this.description != null && !this.description.isEmpty(); } public boolean hasDescription() { return this.description != null && !this.description.isEmpty(); } /** * @param value {@link #description} (A description of the reason that a resource has been included in the implementation guide.). This is the underlying object with id, value and extensions. The accessor "getDescription" gives direct access to the value */ public ImplementationGuidePackageResourceComponent setDescriptionElement(StringType value) { this.description = value; return this; } /** * @return A description of the reason that a resource has been included in the implementation guide. */ public String getDescription() { return this.description == null ? null : this.description.getValue(); } /** * @param value A description of the reason that a resource has been included in the implementation guide. */ public ImplementationGuidePackageResourceComponent setDescription(String value) { if (Utilities.noString(value)) this.description = null; else { if (this.description == null) this.description = new StringType(); this.description.setValue(value); } return this; } /** * @return {@link #acronym} (A short code that may be used to identify the resource throughout the implementation guide.). This is the underlying object with id, value and extensions. The accessor "getAcronym" gives direct access to the value */ public StringType getAcronymElement() { if (this.acronym == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create ImplementationGuidePackageResourceComponent.acronym"); else if (Configuration.doAutoCreate()) this.acronym = new StringType(); // bb return this.acronym; } public boolean hasAcronymElement() { return this.acronym != null && !this.acronym.isEmpty(); } public boolean hasAcronym() { return this.acronym != null && !this.acronym.isEmpty(); } /** * @param value {@link #acronym} (A short code that may be used to identify the resource throughout the implementation guide.). This is the underlying object with id, value and extensions. The accessor "getAcronym" gives direct access to the value */ public ImplementationGuidePackageResourceComponent setAcronymElement(StringType value) { this.acronym = value; return this; } /** * @return A short code that may be used to identify the resource throughout the implementation guide. */ public String getAcronym() { return this.acronym == null ? null : this.acronym.getValue(); } /** * @param value A short code that may be used to identify the resource throughout the implementation guide. */ public ImplementationGuidePackageResourceComponent setAcronym(String value) { if (Utilities.noString(value)) this.acronym = null; else { if (this.acronym == null) this.acronym = new StringType(); this.acronym.setValue(value); } return this; } /** * @return {@link #source} (Where this resource is found.) */ public Type getSource() { return this.source; } /** * @return {@link #source} (Where this resource is found.) */ public UriType getSourceUriType() throws FHIRException { if (!(this.source instanceof UriType)) throw new FHIRException("Type mismatch: the type UriType was expected, but "+this.source.getClass().getName()+" was encountered"); return (UriType) this.source; } public boolean hasSourceUriType() { return this.source instanceof UriType; } /** * @return {@link #source} (Where this resource is found.) */ public Reference getSourceReference() throws FHIRException { if (!(this.source instanceof Reference)) throw new FHIRException("Type mismatch: the type Reference was expected, but "+this.source.getClass().getName()+" was encountered"); return (Reference) this.source; } public boolean hasSourceReference() { return this.source instanceof Reference; } public boolean hasSource() { return this.source != null && !this.source.isEmpty(); } /** * @param value {@link #source} (Where this resource is found.) */ public ImplementationGuidePackageResourceComponent setSource(Type value) { this.source = value; return this; } /** * @return {@link #exampleFor} (Another resource that this resource is an example for. This is mostly used for resources that are included as examples of StructureDefinitions.) */ public Reference getExampleFor() { if (this.exampleFor == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create ImplementationGuidePackageResourceComponent.exampleFor"); else if (Configuration.doAutoCreate()) this.exampleFor = new Reference(); // cc return this.exampleFor; } public boolean hasExampleFor() { return this.exampleFor != null && !this.exampleFor.isEmpty(); } /** * @param value {@link #exampleFor} (Another resource that this resource is an example for. This is mostly used for resources that are included as examples of StructureDefinitions.) */ public ImplementationGuidePackageResourceComponent setExampleFor(Reference value) { this.exampleFor = value; return this; } /** * @return {@link #exampleFor} 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. (Another resource that this resource is an example for. This is mostly used for resources that are included as examples of StructureDefinitions.) */ public StructureDefinition getExampleForTarget() { if (this.exampleForTarget == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create ImplementationGuidePackageResourceComponent.exampleFor"); else if (Configuration.doAutoCreate()) this.exampleForTarget = new StructureDefinition(); // aa return this.exampleForTarget; } /** * @param value {@link #exampleFor} 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. (Another resource that this resource is an example for. This is mostly used for resources that are included as examples of StructureDefinitions.) */ public ImplementationGuidePackageResourceComponent setExampleForTarget(StructureDefinition value) { this.exampleForTarget = value; return this; } protected void listChildren(List<Property> childrenList) { super.listChildren(childrenList); childrenList.add(new Property("purpose", "code", "Why the resource is included in the guide.", 0, java.lang.Integer.MAX_VALUE, purpose)); childrenList.add(new Property("name", "string", "A human assigned name for the resource. All resources SHOULD have a name, but the name may be extracted from the resource (e.g. ValueSet.name).", 0, java.lang.Integer.MAX_VALUE, name)); childrenList.add(new Property("description", "string", "A description of the reason that a resource has been included in the implementation guide.", 0, java.lang.Integer.MAX_VALUE, description)); childrenList.add(new Property("acronym", "string", "A short code that may be used to identify the resource throughout the implementation guide.", 0, java.lang.Integer.MAX_VALUE, acronym)); childrenList.add(new Property("source[x]", "uri|Reference(Any)", "Where this resource is found.", 0, java.lang.Integer.MAX_VALUE, source)); childrenList.add(new Property("exampleFor", "Reference(StructureDefinition)", "Another resource that this resource is an example for. This is mostly used for resources that are included as examples of StructureDefinitions.", 0, java.lang.Integer.MAX_VALUE, exampleFor)); } @Override public void setProperty(String name, Base value) throws FHIRException { if (name.equals("purpose")) this.purpose = new GuideResourcePurposeEnumFactory().fromType(value); // Enumeration<GuideResourcePurpose> else if (name.equals("name")) this.name = castToString(value); // StringType else if (name.equals("description")) this.description = castToString(value); // StringType else if (name.equals("acronym")) this.acronym = castToString(value); // StringType else if (name.equals("source[x]")) this.source = (Type) value; // Type else if (name.equals("exampleFor")) this.exampleFor = castToReference(value); // Reference else super.setProperty(name, value); } @Override public Base addChild(String name) throws FHIRException { if (name.equals("purpose")) { throw new FHIRException("Cannot call addChild on a primitive type ImplementationGuide.purpose"); } else if (name.equals("name")) { throw new FHIRException("Cannot call addChild on a primitive type ImplementationGuide.name"); } else if (name.equals("description")) { throw new FHIRException("Cannot call addChild on a primitive type ImplementationGuide.description"); } else if (name.equals("acronym")) { throw new FHIRException("Cannot call addChild on a primitive type ImplementationGuide.acronym"); } else if (name.equals("sourceUri")) { this.source = new UriType(); return this.source; } else if (name.equals("sourceReference")) { this.source = new Reference(); return this.source; } else if (name.equals("exampleFor")) { this.exampleFor = new Reference(); return this.exampleFor; } else return super.addChild(name); } public ImplementationGuidePackageResourceComponent copy() { ImplementationGuidePackageResourceComponent dst = new ImplementationGuidePackageResourceComponent(); copyValues(dst); dst.purpose = purpose == null ? null : purpose.copy(); dst.name = name == null ? null : name.copy(); dst.description = description == null ? null : description.copy(); dst.acronym = acronym == null ? null : acronym.copy(); dst.source = source == null ? null : source.copy(); dst.exampleFor = exampleFor == null ? null : exampleFor.copy(); return dst; } @Override public boolean equalsDeep(Base other) { if (!super.equalsDeep(other)) return false; if (!(other instanceof ImplementationGuidePackageResourceComponent)) return false; ImplementationGuidePackageResourceComponent o = (ImplementationGuidePackageResourceComponent) other; return compareDeep(purpose, o.purpose, true) && compareDeep(name, o.name, true) && compareDeep(description, o.description, true) && compareDeep(acronym, o.acronym, true) && compareDeep(source, o.source, true) && compareDeep(exampleFor, o.exampleFor, true) ; } @Override public boolean equalsShallow(Base other) { if (!super.equalsShallow(other)) return false; if (!(other instanceof ImplementationGuidePackageResourceComponent)) return false; ImplementationGuidePackageResourceComponent o = (ImplementationGuidePackageResourceComponent) other; return compareValues(purpose, o.purpose, true) && compareValues(name, o.name, true) && compareValues(description, o.description, true) && compareValues(acronym, o.acronym, true); } public boolean isEmpty() { return super.isEmpty() && (purpose == null || purpose.isEmpty()) && (name == null || name.isEmpty()) && (description == null || description.isEmpty()) && (acronym == null || acronym.isEmpty()) && (source == null || source.isEmpty()) && (exampleFor == null || exampleFor.isEmpty()); } public String fhirType() { return "ImplementationGuide.package.resource"; } } @Block() public static class ImplementationGuideGlobalComponent extends BackboneElement implements IBaseBackboneElement { /** * The type of resource that all instances must conform to. */ @Child(name = "type", type = {CodeType.class}, order=1, min=1, max=1, modifier=false, summary=true) @Description(shortDefinition="Type this profiles applies to", formalDefinition="The type of resource that all instances must conform to." ) protected CodeType type; /** * A reference to the profile that all instances must conform to. */ @Child(name = "profile", type = {StructureDefinition.class}, order=2, min=1, max=1, modifier=false, summary=true) @Description(shortDefinition="Profile that all resources must conform to", formalDefinition="A reference to the profile that all instances must conform to." ) protected Reference profile; /** * The actual object that is the target of the reference (A reference to the profile that all instances must conform to.) */ protected StructureDefinition profileTarget; private static final long serialVersionUID = 2011731959L; /* * Constructor */ public ImplementationGuideGlobalComponent() { super(); } /* * Constructor */ public ImplementationGuideGlobalComponent(CodeType type, Reference profile) { super(); this.type = type; this.profile = profile; } /** * @return {@link #type} (The type of resource that all instances must conform to.). This is the underlying object with id, value and extensions. The accessor "getType" gives direct access to the value */ public CodeType getTypeElement() { if (this.type == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create ImplementationGuideGlobalComponent.type"); else if (Configuration.doAutoCreate()) this.type = new CodeType(); // 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 resource that all instances must conform to.). This is the underlying object with id, value and extensions. The accessor "getType" gives direct access to the value */ public ImplementationGuideGlobalComponent setTypeElement(CodeType value) { this.type = value; return this; } /** * @return The type of resource that all instances must conform to. */ public String getType() { return this.type == null ? null : this.type.getValue(); } /** * @param value The type of resource that all instances must conform to. */ public ImplementationGuideGlobalComponent setType(String value) { if (this.type == null) this.type = new CodeType(); this.type.setValue(value); return this; } /** * @return {@link #profile} (A reference to the profile that all instances must conform to.) */ public Reference getProfile() { if (this.profile == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create ImplementationGuideGlobalComponent.profile"); else if (Configuration.doAutoCreate()) this.profile = new Reference(); // cc return this.profile; } public boolean hasProfile() { return this.profile != null && !this.profile.isEmpty(); } /** * @param value {@link #profile} (A reference to the profile that all instances must conform to.) */ public ImplementationGuideGlobalComponent setProfile(Reference value) { this.profile = value; return this; } /** * @return {@link #profile} 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. (A reference to the profile that all instances must conform to.) */ public StructureDefinition getProfileTarget() { if (this.profileTarget == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create ImplementationGuideGlobalComponent.profile"); else if (Configuration.doAutoCreate()) this.profileTarget = new StructureDefinition(); // aa return this.profileTarget; } /** * @param value {@link #profile} 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. (A reference to the profile that all instances must conform to.) */ public ImplementationGuideGlobalComponent setProfileTarget(StructureDefinition value) { this.profileTarget = value; return this; } protected void listChildren(List<Property> childrenList) { super.listChildren(childrenList); childrenList.add(new Property("type", "code", "The type of resource that all instances must conform to.", 0, java.lang.Integer.MAX_VALUE, type)); childrenList.add(new Property("profile", "Reference(StructureDefinition)", "A reference to the profile that all instances must conform to.", 0, java.lang.Integer.MAX_VALUE, profile)); } @Override public void setProperty(String name, Base value) throws FHIRException { if (name.equals("type")) this.type = castToCode(value); // CodeType else if (name.equals("profile")) this.profile = castToReference(value); // Reference else super.setProperty(name, value); } @Override public Base addChild(String name) throws FHIRException { if (name.equals("type")) { throw new FHIRException("Cannot call addChild on a primitive type ImplementationGuide.type"); } else if (name.equals("profile")) { this.profile = new Reference(); return this.profile; } else return super.addChild(name); } public ImplementationGuideGlobalComponent copy() { ImplementationGuideGlobalComponent dst = new ImplementationGuideGlobalComponent(); copyValues(dst); dst.type = type == null ? null : type.copy(); dst.profile = profile == null ? null : profile.copy(); return dst; } @Override public boolean equalsDeep(Base other) { if (!super.equalsDeep(other)) return false; if (!(other instanceof ImplementationGuideGlobalComponent)) return false; ImplementationGuideGlobalComponent o = (ImplementationGuideGlobalComponent) other; return compareDeep(type, o.type, true) && compareDeep(profile, o.profile, true); } @Override public boolean equalsShallow(Base other) { if (!super.equalsShallow(other)) return false; if (!(other instanceof ImplementationGuideGlobalComponent)) return false; ImplementationGuideGlobalComponent o = (ImplementationGuideGlobalComponent) other; return compareValues(type, o.type, true); } public boolean isEmpty() { return super.isEmpty() && (type == null || type.isEmpty()) && (profile == null || profile.isEmpty()) ; } public String fhirType() { return "ImplementationGuide.global"; } } @Block() public static class ImplementationGuidePageComponent extends BackboneElement implements IBaseBackboneElement { /** * The source address for the page. */ @Child(name = "source", type = {UriType.class}, order=1, min=1, max=1, modifier=false, summary=true) @Description(shortDefinition="Where to find that page", formalDefinition="The source address for the page." ) protected UriType source; /** * A short name used to represent this page in navigational structures such as table of contents, bread crumbs, etc. */ @Child(name = "name", type = {StringType.class}, order=2, min=1, max=1, modifier=false, summary=true) @Description(shortDefinition="Short name shown for navigational assistance", formalDefinition="A short name used to represent this page in navigational structures such as table of contents, bread crumbs, etc." ) protected StringType name; /** * The kind of page that this is. Some pages are autogenerated (list, example), and other kinds are of interest so that tools can navigate the user to the page of interest. */ @Child(name = "kind", type = {CodeType.class}, order=3, min=1, max=1, modifier=false, summary=true) @Description(shortDefinition="page | example | list | include | directory | dictionary | toc | resource", formalDefinition="The kind of page that this is. Some pages are autogenerated (list, example), and other kinds are of interest so that tools can navigate the user to the page of interest." ) protected Enumeration<GuidePageKind> kind; /** * For constructed pages, what kind of resources to include in the list. */ @Child(name = "type", type = {CodeType.class}, order=4, min=0, max=Child.MAX_UNLIMITED, modifier=false, summary=false) @Description(shortDefinition="Kind of resource to include in the list", formalDefinition="For constructed pages, what kind of resources to include in the list." ) protected List<CodeType> type; /** * For constructed pages, a list of packages to include in the page (or else empty for everything). */ @Child(name = "package", type = {StringType.class}, order=5, min=0, max=Child.MAX_UNLIMITED, modifier=false, summary=false) @Description(shortDefinition="Name of package to include", formalDefinition="For constructed pages, a list of packages to include in the page (or else empty for everything)." ) protected List<StringType> package_; /** * The format of the page. */ @Child(name = "format", type = {CodeType.class}, order=6, min=0, max=1, modifier=false, summary=false) @Description(shortDefinition="Format of the page (e.g. html, markdown, etc.)", formalDefinition="The format of the page." ) protected CodeType format; /** * Nested Pages/Sections under this page. */ @Child(name = "page", type = {ImplementationGuidePageComponent.class}, order=7, min=0, max=Child.MAX_UNLIMITED, modifier=false, summary=false) @Description(shortDefinition="Nested Pages / Sections", formalDefinition="Nested Pages/Sections under this page." ) protected List<ImplementationGuidePageComponent> page; private static final long serialVersionUID = -1620890043L; /* * Constructor */ public ImplementationGuidePageComponent() { super(); } /* * Constructor */ public ImplementationGuidePageComponent(UriType source, StringType name, Enumeration<GuidePageKind> kind) { super(); this.source = source; this.name = name; this.kind = kind; } /** * @return {@link #source} (The source address for the page.). This is the underlying object with id, value and extensions. The accessor "getSource" gives direct access to the value */ public UriType getSourceElement() { if (this.source == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create ImplementationGuidePageComponent.source"); else if (Configuration.doAutoCreate()) this.source = new UriType(); // bb return this.source; } public boolean hasSourceElement() { return this.source != null && !this.source.isEmpty(); } public boolean hasSource() { return this.source != null && !this.source.isEmpty(); } /** * @param value {@link #source} (The source address for the page.). This is the underlying object with id, value and extensions. The accessor "getSource" gives direct access to the value */ public ImplementationGuidePageComponent setSourceElement(UriType value) { this.source = value; return this; } /** * @return The source address for the page. */ public String getSource() { return this.source == null ? null : this.source.getValue(); } /** * @param value The source address for the page. */ public ImplementationGuidePageComponent setSource(String value) { if (this.source == null) this.source = new UriType(); this.source.setValue(value); return this; } /** * @return {@link #name} (A short name used to represent this page in navigational structures such as table of contents, bread crumbs, etc.). This is the underlying object with id, value and extensions. The accessor "getName" gives direct access to the value */ public StringType getNameElement() { if (this.name == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create ImplementationGuidePageComponent.name"); else if (Configuration.doAutoCreate()) this.name = new StringType(); // bb return this.name; } public boolean hasNameElement() { return this.name != null && !this.name.isEmpty(); } public boolean hasName() { return this.name != null && !this.name.isEmpty(); } /** * @param value {@link #name} (A short name used to represent this page in navigational structures such as table of contents, bread crumbs, etc.). This is the underlying object with id, value and extensions. The accessor "getName" gives direct access to the value */ public ImplementationGuidePageComponent setNameElement(StringType value) { this.name = value; return this; } /** * @return A short name used to represent this page in navigational structures such as table of contents, bread crumbs, etc. */ public String getName() { return this.name == null ? null : this.name.getValue(); } /** * @param value A short name used to represent this page in navigational structures such as table of contents, bread crumbs, etc. */ public ImplementationGuidePageComponent setName(String value) { if (this.name == null) this.name = new StringType(); this.name.setValue(value); return this; } /** * @return {@link #kind} (The kind of page that this is. Some pages are autogenerated (list, example), and other kinds are of interest so that tools can navigate the user to the page of interest.). This is the underlying object with id, value and extensions. The accessor "getKind" gives direct access to the value */ public Enumeration<GuidePageKind> getKindElement() { if (this.kind == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create ImplementationGuidePageComponent.kind"); else if (Configuration.doAutoCreate()) this.kind = new Enumeration<GuidePageKind>(new GuidePageKindEnumFactory()); // bb return this.kind; } public boolean hasKindElement() { return this.kind != null && !this.kind.isEmpty(); } public boolean hasKind() { return this.kind != null && !this.kind.isEmpty(); } /** * @param value {@link #kind} (The kind of page that this is. Some pages are autogenerated (list, example), and other kinds are of interest so that tools can navigate the user to the page of interest.). This is the underlying object with id, value and extensions. The accessor "getKind" gives direct access to the value */ public ImplementationGuidePageComponent setKindElement(Enumeration<GuidePageKind> value) { this.kind = value; return this; } /** * @return The kind of page that this is. Some pages are autogenerated (list, example), and other kinds are of interest so that tools can navigate the user to the page of interest. */ public GuidePageKind getKind() { return this.kind == null ? null : this.kind.getValue(); } /** * @param value The kind of page that this is. Some pages are autogenerated (list, example), and other kinds are of interest so that tools can navigate the user to the page of interest. */ public ImplementationGuidePageComponent setKind(GuidePageKind value) { if (this.kind == null) this.kind = new Enumeration<GuidePageKind>(new GuidePageKindEnumFactory()); this.kind.setValue(value); return this; } /** * @return {@link #type} (For constructed pages, what kind of resources to include in the list.) */ public List<CodeType> getType() { if (this.type == null) this.type = new ArrayList<CodeType>(); return this.type; } public boolean hasType() { if (this.type == null) return false; for (CodeType item : this.type) if (!item.isEmpty()) return true; return false; } /** * @return {@link #type} (For constructed pages, what kind of resources to include in the list.) */ // syntactic sugar public CodeType addTypeElement() {//2 CodeType t = new CodeType(); if (this.type == null) this.type = new ArrayList<CodeType>(); this.type.add(t); return t; } /** * @param value {@link #type} (For constructed pages, what kind of resources to include in the list.) */ public ImplementationGuidePageComponent addType(String value) { //1 CodeType t = new CodeType(); t.setValue(value); if (this.type == null) this.type = new ArrayList<CodeType>(); this.type.add(t); return this; } /** * @param value {@link #type} (For constructed pages, what kind of resources to include in the list.) */ public boolean hasType(String value) { if (this.type == null) return false; for (CodeType v : this.type) if (v.equals(value)) // code return true; return false; } /** * @return {@link #package_} (For constructed pages, a list of packages to include in the page (or else empty for everything).) */ public List<StringType> getPackage() { if (this.package_ == null) this.package_ = new ArrayList<StringType>(); return this.package_; } public boolean hasPackage() { if (this.package_ == null) return false; for (StringType item : this.package_) if (!item.isEmpty()) return true; return false; } /** * @return {@link #package_} (For constructed pages, a list of packages to include in the page (or else empty for everything).) */ // syntactic sugar public StringType addPackageElement() {//2 StringType t = new StringType(); if (this.package_ == null) this.package_ = new ArrayList<StringType>(); this.package_.add(t); return t; } /** * @param value {@link #package_} (For constructed pages, a list of packages to include in the page (or else empty for everything).) */ public ImplementationGuidePageComponent addPackage(String value) { //1 StringType t = new StringType(); t.setValue(value); if (this.package_ == null) this.package_ = new ArrayList<StringType>(); this.package_.add(t); return this; } /** * @param value {@link #package_} (For constructed pages, a list of packages to include in the page (or else empty for everything).) */ public boolean hasPackage(String value) { if (this.package_ == null) return false; for (StringType v : this.package_) if (v.equals(value)) // string return true; return false; } /** * @return {@link #format} (The format of the page.). This is the underlying object with id, value and extensions. The accessor "getFormat" gives direct access to the value */ public CodeType getFormatElement() { if (this.format == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create ImplementationGuidePageComponent.format"); else if (Configuration.doAutoCreate()) this.format = new CodeType(); // bb return this.format; } public boolean hasFormatElement() { return this.format != null && !this.format.isEmpty(); } public boolean hasFormat() { return this.format != null && !this.format.isEmpty(); } /** * @param value {@link #format} (The format of the page.). This is the underlying object with id, value and extensions. The accessor "getFormat" gives direct access to the value */ public ImplementationGuidePageComponent setFormatElement(CodeType value) { this.format = value; return this; } /** * @return The format of the page. */ public String getFormat() { return this.format == null ? null : this.format.getValue(); } /** * @param value The format of the page. */ public ImplementationGuidePageComponent setFormat(String value) { if (Utilities.noString(value)) this.format = null; else { if (this.format == null) this.format = new CodeType(); this.format.setValue(value); } return this; } /** * @return {@link #page} (Nested Pages/Sections under this page.) */ public List<ImplementationGuidePageComponent> getPage() { if (this.page == null) this.page = new ArrayList<ImplementationGuidePageComponent>(); return this.page; } public boolean hasPage() { if (this.page == null) return false; for (ImplementationGuidePageComponent item : this.page) if (!item.isEmpty()) return true; return false; } /** * @return {@link #page} (Nested Pages/Sections under this page.) */ // syntactic sugar public ImplementationGuidePageComponent addPage() { //3 ImplementationGuidePageComponent t = new ImplementationGuidePageComponent(); if (this.page == null) this.page = new ArrayList<ImplementationGuidePageComponent>(); this.page.add(t); return t; } // syntactic sugar public ImplementationGuidePageComponent addPage(ImplementationGuidePageComponent t) { //3 if (t == null) return this; if (this.page == null) this.page = new ArrayList<ImplementationGuidePageComponent>(); this.page.add(t); return this; } protected void listChildren(List<Property> childrenList) { super.listChildren(childrenList); childrenList.add(new Property("source", "uri", "The source address for the page.", 0, java.lang.Integer.MAX_VALUE, source)); childrenList.add(new Property("name", "string", "A short name used to represent this page in navigational structures such as table of contents, bread crumbs, etc.", 0, java.lang.Integer.MAX_VALUE, name)); childrenList.add(new Property("kind", "code", "The kind of page that this is. Some pages are autogenerated (list, example), and other kinds are of interest so that tools can navigate the user to the page of interest.", 0, java.lang.Integer.MAX_VALUE, kind)); childrenList.add(new Property("type", "code", "For constructed pages, what kind of resources to include in the list.", 0, java.lang.Integer.MAX_VALUE, type)); childrenList.add(new Property("package", "string", "For constructed pages, a list of packages to include in the page (or else empty for everything).", 0, java.lang.Integer.MAX_VALUE, package_)); childrenList.add(new Property("format", "code", "The format of the page.", 0, java.lang.Integer.MAX_VALUE, format)); childrenList.add(new Property("page", "@ImplementationGuide.page", "Nested Pages/Sections under this page.", 0, java.lang.Integer.MAX_VALUE, page)); } @Override public void setProperty(String name, Base value) throws FHIRException { if (name.equals("source")) this.source = castToUri(value); // UriType else if (name.equals("name")) this.name = castToString(value); // StringType else if (name.equals("kind")) this.kind = new GuidePageKindEnumFactory().fromType(value); // Enumeration<GuidePageKind> else if (name.equals("type")) this.getType().add(castToCode(value)); else if (name.equals("package")) this.getPackage().add(castToString(value)); else if (name.equals("format")) this.format = castToCode(value); // CodeType else if (name.equals("page")) this.getPage().add((ImplementationGuidePageComponent) value); else super.setProperty(name, value); } @Override public Base addChild(String name) throws FHIRException { if (name.equals("source")) { throw new FHIRException("Cannot call addChild on a primitive type ImplementationGuide.source"); } else if (name.equals("name")) { throw new FHIRException("Cannot call addChild on a primitive type ImplementationGuide.name"); } else if (name.equals("kind")) { throw new FHIRException("Cannot call addChild on a primitive type ImplementationGuide.kind"); } else if (name.equals("type")) { throw new FHIRException("Cannot call addChild on a primitive type ImplementationGuide.type"); } else if (name.equals("package")) { throw new FHIRException("Cannot call addChild on a primitive type ImplementationGuide.package"); } else if (name.equals("format")) { throw new FHIRException("Cannot call addChild on a primitive type ImplementationGuide.format"); } else if (name.equals("page")) { return addPage(); } else return super.addChild(name); } public ImplementationGuidePageComponent copy() { ImplementationGuidePageComponent dst = new ImplementationGuidePageComponent(); copyValues(dst); dst.source = source == null ? null : source.copy(); dst.name = name == null ? null : name.copy(); dst.kind = kind == null ? null : kind.copy(); if (type != null) { dst.type = new ArrayList<CodeType>(); for (CodeType i : type) dst.type.add(i.copy()); }; if (package_ != null) { dst.package_ = new ArrayList<StringType>(); for (StringType i : package_) dst.package_.add(i.copy()); }; dst.format = format == null ? null : format.copy(); if (page != null) { dst.page = new ArrayList<ImplementationGuidePageComponent>(); for (ImplementationGuidePageComponent i : page) dst.page.add(i.copy()); }; return dst; } @Override public boolean equalsDeep(Base other) { if (!super.equalsDeep(other)) return false; if (!(other instanceof ImplementationGuidePageComponent)) return false; ImplementationGuidePageComponent o = (ImplementationGuidePageComponent) other; return compareDeep(source, o.source, true) && compareDeep(name, o.name, true) && compareDeep(kind, o.kind, true) && compareDeep(type, o.type, true) && compareDeep(package_, o.package_, true) && compareDeep(format, o.format, true) && compareDeep(page, o.page, true); } @Override public boolean equalsShallow(Base other) { if (!super.equalsShallow(other)) return false; if (!(other instanceof ImplementationGuidePageComponent)) return false; ImplementationGuidePageComponent o = (ImplementationGuidePageComponent) other; return compareValues(source, o.source, true) && compareValues(name, o.name, true) && compareValues(kind, o.kind, true) && compareValues(type, o.type, true) && compareValues(package_, o.package_, true) && compareValues(format, o.format, true) ; } public boolean isEmpty() { return super.isEmpty() && (source == null || source.isEmpty()) && (name == null || name.isEmpty()) && (kind == null || kind.isEmpty()) && (type == null || type.isEmpty()) && (package_ == null || package_.isEmpty()) && (format == null || format.isEmpty()) && (page == null || page.isEmpty()); } public String fhirType() { return "ImplementationGuide.page"; } } /** * An absolute URL that is used to identify this implementation guide when it is referenced in a specification, model, design or an instance. This SHALL be a URL, SHOULD be globally unique, and SHOULD be an address at which this implementation guide is (or will be) published. */ @Child(name = "url", type = {UriType.class}, order=0, min=1, max=1, modifier=false, summary=true) @Description(shortDefinition="Absolute URL used to reference this Implementation Guide", formalDefinition="An absolute URL that is used to identify this implementation guide when it is referenced in a specification, model, design or an instance. This SHALL be a URL, SHOULD be globally unique, and SHOULD be an address at which this implementation guide is (or will be) published." ) protected UriType url; /** * The identifier that is used to identify this version of the Implementation Guide when it is referenced in a specification, model, design or instance. This is an arbitrary value managed by the Implementation Guide author manually. */ @Child(name = "version", type = {StringType.class}, order=1, min=0, max=1, modifier=false, summary=true) @Description(shortDefinition="Logical id for this version of the Implementation Guide", formalDefinition="The identifier that is used to identify this version of the Implementation Guide when it is referenced in a specification, model, design or instance. This is an arbitrary value managed by the Implementation Guide author manually." ) protected StringType version; /** * A free text natural language name identifying the Implementation Guide. */ @Child(name = "name", type = {StringType.class}, order=2, min=1, max=1, modifier=false, summary=true) @Description(shortDefinition="Informal name for this Implementation Guide", formalDefinition="A free text natural language name identifying the Implementation Guide." ) protected StringType name; /** * The status of the Implementation Guide. */ @Child(name = "status", type = {CodeType.class}, order=3, min=1, max=1, modifier=true, summary=true) @Description(shortDefinition="draft | active | retired", formalDefinition="The status of the Implementation Guide." ) protected Enumeration<ConformanceResourceStatus> status; /** * This Implementation Guide was authored for testing purposes (or education/evaluation/marketing), and is not intended to be used for genuine usage. */ @Child(name = "experimental", type = {BooleanType.class}, order=4, min=0, max=1, modifier=false, summary=true) @Description(shortDefinition="If for testing purposes, not real usage", formalDefinition="This Implementation Guide was authored for testing purposes (or education/evaluation/marketing), and is not intended to be used for genuine usage." ) protected BooleanType experimental; /** * The name of the individual or organization that published the implementation guide. */ @Child(name = "publisher", type = {StringType.class}, order=5, min=0, max=1, modifier=false, summary=true) @Description(shortDefinition="Name of the publisher (Organization or individual)", formalDefinition="The name of the individual or organization that published the implementation guide." ) protected StringType publisher; /** * Contacts to assist a user in finding and communicating with the publisher. */ @Child(name = "contact", type = {}, order=6, min=0, max=Child.MAX_UNLIMITED, modifier=false, summary=true) @Description(shortDefinition="Contact details of the publisher", formalDefinition="Contacts to assist a user in finding and communicating with the publisher." ) protected List<ImplementationGuideContactComponent> contact; /** * The date this version of the implementation guide was published. The date must change when the business version changes, if it does, and it must change if the status code changes. In addition, it should change when the substantive content of the implementation guide changes. */ @Child(name = "date", type = {DateTimeType.class}, order=7, min=0, max=1, modifier=false, summary=true) @Description(shortDefinition="Date for this version of the Implementation Guide", formalDefinition="The date this version of the implementation guide was published. The date must change when the business version changes, if it does, and it must change if the status code changes. In addition, it should change when the substantive content of the implementation guide changes." ) protected DateTimeType date; /** * A free text natural language description of the Implementation Guide and its use. */ @Child(name = "description", type = {StringType.class}, order=8, min=0, max=1, modifier=false, summary=true) @Description(shortDefinition="Natural language description of the Implementation Guide", formalDefinition="A free text natural language description of the Implementation Guide and its use." ) protected StringType description; /** * The content was developed with a focus and intent of supporting the contexts that are listed. These terms may be used to assist with indexing and searching of implementation guides. The most common use of this element is to represent the country / jurisdiction for which this implementation guide was defined. */ @Child(name = "useContext", type = {CodeableConcept.class}, order=9, min=0, max=Child.MAX_UNLIMITED, modifier=false, summary=true) @Description(shortDefinition="The implementation guide is intended to support these contexts", formalDefinition="The content was developed with a focus and intent of supporting the contexts that are listed. These terms may be used to assist with indexing and searching of implementation guides. The most common use of this element is to represent the country / jurisdiction for which this implementation guide was defined." ) protected List<CodeableConcept> useContext; /** * A copyright statement relating to the implementation guide and/or its contents. Copyright statements are generally legal restrictions on the use and publishing of the details of the constraints and mappings. */ @Child(name = "copyright", type = {StringType.class}, order=10, min=0, max=1, modifier=false, summary=false) @Description(shortDefinition="Use and/or publishing restrictions", formalDefinition="A copyright statement relating to the implementation guide and/or its contents. Copyright statements are generally legal restrictions on the use and publishing of the details of the constraints and mappings." ) protected StringType copyright; /** * The version of the FHIR specification on which this ImplementationGuide is based - this is the formal version of the specification, without the revision number, e.g. [publication].[major].[minor], which is 1.0.2 for this version. */ @Child(name = "fhirVersion", type = {IdType.class}, order=11, min=0, max=1, modifier=false, summary=true) @Description(shortDefinition="FHIR Version this Implementation Guide targets", formalDefinition="The version of the FHIR specification on which this ImplementationGuide is based - this is the formal version of the specification, without the revision number, e.g. [publication].[major].[minor], which is 1.0.2 for this version." ) protected IdType fhirVersion; /** * Another implementation guide that this implementation depends on. Typically, an implementation guide uses value sets, profiles etc.defined in other implementation guides. */ @Child(name = "dependency", type = {}, order=12, min=0, max=Child.MAX_UNLIMITED, modifier=false, summary=true) @Description(shortDefinition="Another Implementation guide this depends on", formalDefinition="Another implementation guide that this implementation depends on. Typically, an implementation guide uses value sets, profiles etc.defined in other implementation guides." ) protected List<ImplementationGuideDependencyComponent> dependency; /** * A logical group of resources. Logical groups can be used when building pages. */ @Child(name = "package", type = {}, order=13, min=1, max=Child.MAX_UNLIMITED, modifier=false, summary=true) @Description(shortDefinition="Group of resources as used in .page.package", formalDefinition="A logical group of resources. Logical groups can be used when building pages." ) protected List<ImplementationGuidePackageComponent> package_; /** * A set of profiles that all resources covered by this implementation guide must conform to. */ @Child(name = "global", type = {}, order=14, min=0, max=Child.MAX_UNLIMITED, modifier=false, summary=true) @Description(shortDefinition="Profiles that apply globally", formalDefinition="A set of profiles that all resources covered by this implementation guide must conform to." ) protected List<ImplementationGuideGlobalComponent> global; /** * A binary file that is included in the implementation guide when it is published. */ @Child(name = "binary", type = {UriType.class}, order=15, min=0, max=Child.MAX_UNLIMITED, modifier=false, summary=false) @Description(shortDefinition="Image, css, script, etc.", formalDefinition="A binary file that is included in the implementation guide when it is published." ) protected List<UriType> binary; /** * A page / section in the implementation guide. The root page is the implementation guide home page. */ @Child(name = "page", type = {}, order=16, min=1, max=1, modifier=false, summary=true) @Description(shortDefinition="Page/Section in the Guide", formalDefinition="A page / section in the implementation guide. The root page is the implementation guide home page." ) protected ImplementationGuidePageComponent page; private static final long serialVersionUID = 1150122415L; /* * Constructor */ public ImplementationGuide() { super(); } /* * Constructor */ public ImplementationGuide(UriType url, StringType name, Enumeration<ConformanceResourceStatus> status, ImplementationGuidePageComponent page) { super(); this.url = url; this.name = name; this.status = status; this.page = page; } /** * @return {@link #url} (An absolute URL that is used to identify this implementation guide when it is referenced in a specification, model, design or an instance. This SHALL be a URL, SHOULD be globally unique, and SHOULD be an address at which this implementation guide is (or will be) published.). This is the underlying object with id, value and extensions. The accessor "getUrl" gives direct access to the value */ public UriType getUrlElement() { if (this.url == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create ImplementationGuide.url"); else if (Configuration.doAutoCreate()) this.url = new UriType(); // bb return this.url; } public boolean hasUrlElement() { return this.url != null && !this.url.isEmpty(); } public boolean hasUrl() { return this.url != null && !this.url.isEmpty(); } /** * @param value {@link #url} (An absolute URL that is used to identify this implementation guide when it is referenced in a specification, model, design or an instance. This SHALL be a URL, SHOULD be globally unique, and SHOULD be an address at which this implementation guide is (or will be) published.). This is the underlying object with id, value and extensions. The accessor "getUrl" gives direct access to the value */ public ImplementationGuide setUrlElement(UriType value) { this.url = value; return this; } /** * @return An absolute URL that is used to identify this implementation guide when it is referenced in a specification, model, design or an instance. This SHALL be a URL, SHOULD be globally unique, and SHOULD be an address at which this implementation guide is (or will be) published. */ public String getUrl() { return this.url == null ? null : this.url.getValue(); } /** * @param value An absolute URL that is used to identify this implementation guide when it is referenced in a specification, model, design or an instance. This SHALL be a URL, SHOULD be globally unique, and SHOULD be an address at which this implementation guide is (or will be) published. */ public ImplementationGuide setUrl(String value) { if (this.url == null) this.url = new UriType(); this.url.setValue(value); return this; } /** * @return {@link #version} (The identifier that is used to identify this version of the Implementation Guide when it is referenced in a specification, model, design or instance. This is an arbitrary value managed by the Implementation Guide author manually.). This is the underlying object with id, value and extensions. The accessor "getVersion" gives direct access to the value */ public StringType getVersionElement() { if (this.version == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create ImplementationGuide.version"); else if (Configuration.doAutoCreate()) this.version = new StringType(); // bb return this.version; } public boolean hasVersionElement() { return this.version != null && !this.version.isEmpty(); } public boolean hasVersion() { return this.version != null && !this.version.isEmpty(); } /** * @param value {@link #version} (The identifier that is used to identify this version of the Implementation Guide when it is referenced in a specification, model, design or instance. This is an arbitrary value managed by the Implementation Guide author manually.). This is the underlying object with id, value and extensions. The accessor "getVersion" gives direct access to the value */ public ImplementationGuide setVersionElement(StringType value) { this.version = value; return this; } /** * @return The identifier that is used to identify this version of the Implementation Guide when it is referenced in a specification, model, design or instance. This is an arbitrary value managed by the Implementation Guide author manually. */ public String getVersion() { return this.version == null ? null : this.version.getValue(); } /** * @param value The identifier that is used to identify this version of the Implementation Guide when it is referenced in a specification, model, design or instance. This is an arbitrary value managed by the Implementation Guide author manually. */ public ImplementationGuide setVersion(String value) { if (Utilities.noString(value)) this.version = null; else { if (this.version == null) this.version = new StringType(); this.version.setValue(value); } return this; } /** * @return {@link #name} (A free text natural language name identifying the Implementation Guide.). This is the underlying object with id, value and extensions. The accessor "getName" gives direct access to the value */ public StringType getNameElement() { if (this.name == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create ImplementationGuide.name"); else if (Configuration.doAutoCreate()) this.name = new StringType(); // bb return this.name; } public boolean hasNameElement() { return this.name != null && !this.name.isEmpty(); } public boolean hasName() { return this.name != null && !this.name.isEmpty(); } /** * @param value {@link #name} (A free text natural language name identifying the Implementation Guide.). This is the underlying object with id, value and extensions. The accessor "getName" gives direct access to the value */ public ImplementationGuide setNameElement(StringType value) { this.name = value; return this; } /** * @return A free text natural language name identifying the Implementation Guide. */ public String getName() { return this.name == null ? null : this.name.getValue(); } /** * @param value A free text natural language name identifying the Implementation Guide. */ public ImplementationGuide setName(String value) { if (this.name == null) this.name = new StringType(); this.name.setValue(value); return this; } /** * @return {@link #status} (The status of the Implementation Guide.). This is the underlying object with id, value and extensions. The accessor "getStatus" gives direct access to the value */ public Enumeration<ConformanceResourceStatus> getStatusElement() { if (this.status == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create ImplementationGuide.status"); else if (Configuration.doAutoCreate()) this.status = new Enumeration<ConformanceResourceStatus>(new ConformanceResourceStatusEnumFactory()); // bb return this.status; } public boolean hasStatusElement() { return this.status != null && !this.status.isEmpty(); } public boolean hasStatus() { return this.status != null && !this.status.isEmpty(); } /** * @param value {@link #status} (The status of the Implementation Guide.). This is the underlying object with id, value and extensions. The accessor "getStatus" gives direct access to the value */ public ImplementationGuide setStatusElement(Enumeration<ConformanceResourceStatus> value) { this.status = value; return this; } /** * @return The status of the Implementation Guide. */ public ConformanceResourceStatus getStatus() { return this.status == null ? null : this.status.getValue(); } /** * @param value The status of the Implementation Guide. */ public ImplementationGuide setStatus(ConformanceResourceStatus value) { if (this.status == null) this.status = new Enumeration<ConformanceResourceStatus>(new ConformanceResourceStatusEnumFactory()); this.status.setValue(value); return this; } /** * @return {@link #experimental} (This Implementation Guide was authored for testing purposes (or education/evaluation/marketing), and is not intended to be used for genuine usage.). This is the underlying object with id, value and extensions. The accessor "getExperimental" gives direct access to the value */ public BooleanType getExperimentalElement() { if (this.experimental == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create ImplementationGuide.experimental"); else if (Configuration.doAutoCreate()) this.experimental = new BooleanType(); // bb return this.experimental; } public boolean hasExperimentalElement() { return this.experimental != null && !this.experimental.isEmpty(); } public boolean hasExperimental() { return this.experimental != null && !this.experimental.isEmpty(); } /** * @param value {@link #experimental} (This Implementation Guide was authored for testing purposes (or education/evaluation/marketing), and is not intended to be used for genuine usage.). This is the underlying object with id, value and extensions. The accessor "getExperimental" gives direct access to the value */ public ImplementationGuide setExperimentalElement(BooleanType value) { this.experimental = value; return this; } /** * @return This Implementation Guide was authored for testing purposes (or education/evaluation/marketing), and is not intended to be used for genuine usage. */ public boolean getExperimental() { return this.experimental == null || this.experimental.isEmpty() ? false : this.experimental.getValue(); } /** * @param value This Implementation Guide was authored for testing purposes (or education/evaluation/marketing), and is not intended to be used for genuine usage. */ public ImplementationGuide setExperimental(boolean value) { if (this.experimental == null) this.experimental = new BooleanType(); this.experimental.setValue(value); return this; } /** * @return {@link #publisher} (The name of the individual or organization that published the implementation guide.). This is the underlying object with id, value and extensions. The accessor "getPublisher" gives direct access to the value */ public StringType getPublisherElement() { if (this.publisher == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create ImplementationGuide.publisher"); else if (Configuration.doAutoCreate()) this.publisher = new StringType(); // bb return this.publisher; } public boolean hasPublisherElement() { return this.publisher != null && !this.publisher.isEmpty(); } public boolean hasPublisher() { return this.publisher != null && !this.publisher.isEmpty(); } /** * @param value {@link #publisher} (The name of the individual or organization that published the implementation guide.). This is the underlying object with id, value and extensions. The accessor "getPublisher" gives direct access to the value */ public ImplementationGuide setPublisherElement(StringType value) { this.publisher = value; return this; } /** * @return The name of the individual or organization that published the implementation guide. */ public String getPublisher() { return this.publisher == null ? null : this.publisher.getValue(); } /** * @param value The name of the individual or organization that published the implementation guide. */ public ImplementationGuide setPublisher(String value) { if (Utilities.noString(value)) this.publisher = null; else { if (this.publisher == null) this.publisher = new StringType(); this.publisher.setValue(value); } return this; } /** * @return {@link #contact} (Contacts to assist a user in finding and communicating with the publisher.) */ public List<ImplementationGuideContactComponent> getContact() { if (this.contact == null) this.contact = new ArrayList<ImplementationGuideContactComponent>(); return this.contact; } public boolean hasContact() { if (this.contact == null) return false; for (ImplementationGuideContactComponent item : this.contact) if (!item.isEmpty()) return true; return false; } /** * @return {@link #contact} (Contacts to assist a user in finding and communicating with the publisher.) */ // syntactic sugar public ImplementationGuideContactComponent addContact() { //3 ImplementationGuideContactComponent t = new ImplementationGuideContactComponent(); if (this.contact == null) this.contact = new ArrayList<ImplementationGuideContactComponent>(); this.contact.add(t); return t; } // syntactic sugar public ImplementationGuide addContact(ImplementationGuideContactComponent t) { //3 if (t == null) return this; if (this.contact == null) this.contact = new ArrayList<ImplementationGuideContactComponent>(); this.contact.add(t); return this; } /** * @return {@link #date} (The date this version of the implementation guide was published. The date must change when the business version changes, if it does, and it must change if the status code changes. In addition, it should change when the substantive content of the implementation guide changes.). This is the underlying object with id, value and extensions. The accessor "getDate" gives direct access to the value */ public DateTimeType getDateElement() { if (this.date == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create ImplementationGuide.date"); else if (Configuration.doAutoCreate()) this.date = new DateTimeType(); // bb return this.date; } public boolean hasDateElement() { return this.date != null && !this.date.isEmpty(); } public boolean hasDate() { return this.date != null && !this.date.isEmpty(); } /** * @param value {@link #date} (The date this version of the implementation guide was published. The date must change when the business version changes, if it does, and it must change if the status code changes. In addition, it should change when the substantive content of the implementation guide changes.). This is the underlying object with id, value and extensions. The accessor "getDate" gives direct access to the value */ public ImplementationGuide setDateElement(DateTimeType value) { this.date = value; return this; } /** * @return The date this version of the implementation guide was published. The date must change when the business version changes, if it does, and it must change if the status code changes. In addition, it should change when the substantive content of the implementation guide changes. */ public Date getDate() { return this.date == null ? null : this.date.getValue(); } /** * @param value The date this version of the implementation guide was published. The date must change when the business version changes, if it does, and it must change if the status code changes. In addition, it should change when the substantive content of the implementation guide changes. */ public ImplementationGuide setDate(Date value) { if (value == null) this.date = null; else { if (this.date == null) this.date = new DateTimeType(); this.date.setValue(value); } return this; } /** * @return {@link #description} (A free text natural language description of the Implementation Guide and its use.). This is the underlying object with id, value and extensions. The accessor "getDescription" gives direct access to the value */ public StringType getDescriptionElement() { if (this.description == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create ImplementationGuide.description"); else if (Configuration.doAutoCreate()) this.description = new StringType(); // bb return this.description; } public boolean hasDescriptionElement() { return this.description != null && !this.description.isEmpty(); } public boolean hasDescription() { return this.description != null && !this.description.isEmpty(); } /** * @param value {@link #description} (A free text natural language description of the Implementation Guide and its use.). This is the underlying object with id, value and extensions. The accessor "getDescription" gives direct access to the value */ public ImplementationGuide setDescriptionElement(StringType value) { this.description = value; return this; } /** * @return A free text natural language description of the Implementation Guide and its use. */ public String getDescription() { return this.description == null ? null : this.description.getValue(); } /** * @param value A free text natural language description of the Implementation Guide and its use. */ public ImplementationGuide setDescription(String value) { if (Utilities.noString(value)) this.description = null; else { if (this.description == null) this.description = new StringType(); this.description.setValue(value); } return this; } /** * @return {@link #useContext} (The content was developed with a focus and intent of supporting the contexts that are listed. These terms may be used to assist with indexing and searching of implementation guides. The most common use of this element is to represent the country / jurisdiction for which this implementation guide was defined.) */ public List<CodeableConcept> getUseContext() { if (this.useContext == null) this.useContext = new ArrayList<CodeableConcept>(); return this.useContext; } public boolean hasUseContext() { if (this.useContext == null) return false; for (CodeableConcept item : this.useContext) if (!item.isEmpty()) return true; return false; } /** * @return {@link #useContext} (The content was developed with a focus and intent of supporting the contexts that are listed. These terms may be used to assist with indexing and searching of implementation guides. The most common use of this element is to represent the country / jurisdiction for which this implementation guide was defined.) */ // syntactic sugar public CodeableConcept addUseContext() { //3 CodeableConcept t = new CodeableConcept(); if (this.useContext == null) this.useContext = new ArrayList<CodeableConcept>(); this.useContext.add(t); return t; } // syntactic sugar public ImplementationGuide addUseContext(CodeableConcept t) { //3 if (t == null) return this; if (this.useContext == null) this.useContext = new ArrayList<CodeableConcept>(); this.useContext.add(t); return this; } /** * @return {@link #copyright} (A copyright statement relating to the implementation guide and/or its contents. Copyright statements are generally legal restrictions on the use and publishing of the details of the constraints and mappings.). This is the underlying object with id, value and extensions. The accessor "getCopyright" gives direct access to the value */ public StringType getCopyrightElement() { if (this.copyright == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create ImplementationGuide.copyright"); else if (Configuration.doAutoCreate()) this.copyright = new StringType(); // bb return this.copyright; } public boolean hasCopyrightElement() { return this.copyright != null && !this.copyright.isEmpty(); } public boolean hasCopyright() { return this.copyright != null && !this.copyright.isEmpty(); } /** * @param value {@link #copyright} (A copyright statement relating to the implementation guide and/or its contents. Copyright statements are generally legal restrictions on the use and publishing of the details of the constraints and mappings.). This is the underlying object with id, value and extensions. The accessor "getCopyright" gives direct access to the value */ public ImplementationGuide setCopyrightElement(StringType value) { this.copyright = value; return this; } /** * @return A copyright statement relating to the implementation guide and/or its contents. Copyright statements are generally legal restrictions on the use and publishing of the details of the constraints and mappings. */ public String getCopyright() { return this.copyright == null ? null : this.copyright.getValue(); } /** * @param value A copyright statement relating to the implementation guide and/or its contents. Copyright statements are generally legal restrictions on the use and publishing of the details of the constraints and mappings. */ public ImplementationGuide setCopyright(String value) { if (Utilities.noString(value)) this.copyright = null; else { if (this.copyright == null) this.copyright = new StringType(); this.copyright.setValue(value); } return this; } /** * @return {@link #fhirVersion} (The version of the FHIR specification on which this ImplementationGuide is based - this is the formal version of the specification, without the revision number, e.g. [publication].[major].[minor], which is 1.0.2 for this version.). This is the underlying object with id, value and extensions. The accessor "getFhirVersion" gives direct access to the value */ public IdType getFhirVersionElement() { if (this.fhirVersion == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create ImplementationGuide.fhirVersion"); else if (Configuration.doAutoCreate()) this.fhirVersion = new IdType(); // bb return this.fhirVersion; } public boolean hasFhirVersionElement() { return this.fhirVersion != null && !this.fhirVersion.isEmpty(); } public boolean hasFhirVersion() { return this.fhirVersion != null && !this.fhirVersion.isEmpty(); } /** * @param value {@link #fhirVersion} (The version of the FHIR specification on which this ImplementationGuide is based - this is the formal version of the specification, without the revision number, e.g. [publication].[major].[minor], which is 1.0.2 for this version.). This is the underlying object with id, value and extensions. The accessor "getFhirVersion" gives direct access to the value */ public ImplementationGuide setFhirVersionElement(IdType value) { this.fhirVersion = value; return this; } /** * @return The version of the FHIR specification on which this ImplementationGuide is based - this is the formal version of the specification, without the revision number, e.g. [publication].[major].[minor], which is 1.0.2 for this version. */ public String getFhirVersion() { return this.fhirVersion == null ? null : this.fhirVersion.getValue(); } /** * @param value The version of the FHIR specification on which this ImplementationGuide is based - this is the formal version of the specification, without the revision number, e.g. [publication].[major].[minor], which is 1.0.2 for this version. */ public ImplementationGuide setFhirVersion(String value) { if (Utilities.noString(value)) this.fhirVersion = null; else { if (this.fhirVersion == null) this.fhirVersion = new IdType(); this.fhirVersion.setValue(value); } return this; } /** * @return {@link #dependency} (Another implementation guide that this implementation depends on. Typically, an implementation guide uses value sets, profiles etc.defined in other implementation guides.) */ public List<ImplementationGuideDependencyComponent> getDependency() { if (this.dependency == null) this.dependency = new ArrayList<ImplementationGuideDependencyComponent>(); return this.dependency; } public boolean hasDependency() { if (this.dependency == null) return false; for (ImplementationGuideDependencyComponent item : this.dependency) if (!item.isEmpty()) return true; return false; } /** * @return {@link #dependency} (Another implementation guide that this implementation depends on. Typically, an implementation guide uses value sets, profiles etc.defined in other implementation guides.) */ // syntactic sugar public ImplementationGuideDependencyComponent addDependency() { //3 ImplementationGuideDependencyComponent t = new ImplementationGuideDependencyComponent(); if (this.dependency == null) this.dependency = new ArrayList<ImplementationGuideDependencyComponent>(); this.dependency.add(t); return t; } // syntactic sugar public ImplementationGuide addDependency(ImplementationGuideDependencyComponent t) { //3 if (t == null) return this; if (this.dependency == null) this.dependency = new ArrayList<ImplementationGuideDependencyComponent>(); this.dependency.add(t); return this; } /** * @return {@link #package_} (A logical group of resources. Logical groups can be used when building pages.) */ public List<ImplementationGuidePackageComponent> getPackage() { if (this.package_ == null) this.package_ = new ArrayList<ImplementationGuidePackageComponent>(); return this.package_; } public boolean hasPackage() { if (this.package_ == null) return false; for (ImplementationGuidePackageComponent item : this.package_) if (!item.isEmpty()) return true; return false; } /** * @return {@link #package_} (A logical group of resources. Logical groups can be used when building pages.) */ // syntactic sugar public ImplementationGuidePackageComponent addPackage() { //3 ImplementationGuidePackageComponent t = new ImplementationGuidePackageComponent(); if (this.package_ == null) this.package_ = new ArrayList<ImplementationGuidePackageComponent>(); this.package_.add(t); return t; } // syntactic sugar public ImplementationGuide addPackage(ImplementationGuidePackageComponent t) { //3 if (t == null) return this; if (this.package_ == null) this.package_ = new ArrayList<ImplementationGuidePackageComponent>(); this.package_.add(t); return this; } /** * @return {@link #global} (A set of profiles that all resources covered by this implementation guide must conform to.) */ public List<ImplementationGuideGlobalComponent> getGlobal() { if (this.global == null) this.global = new ArrayList<ImplementationGuideGlobalComponent>(); return this.global; } public boolean hasGlobal() { if (this.global == null) return false; for (ImplementationGuideGlobalComponent item : this.global) if (!item.isEmpty()) return true; return false; } /** * @return {@link #global} (A set of profiles that all resources covered by this implementation guide must conform to.) */ // syntactic sugar public ImplementationGuideGlobalComponent addGlobal() { //3 ImplementationGuideGlobalComponent t = new ImplementationGuideGlobalComponent(); if (this.global == null) this.global = new ArrayList<ImplementationGuideGlobalComponent>(); this.global.add(t); return t; } // syntactic sugar public ImplementationGuide addGlobal(ImplementationGuideGlobalComponent t) { //3 if (t == null) return this; if (this.global == null) this.global = new ArrayList<ImplementationGuideGlobalComponent>(); this.global.add(t); return this; } /** * @return {@link #binary} (A binary file that is included in the implementation guide when it is published.) */ public List<UriType> getBinary() { if (this.binary == null) this.binary = new ArrayList<UriType>(); return this.binary; } public boolean hasBinary() { if (this.binary == null) return false; for (UriType item : this.binary) if (!item.isEmpty()) return true; return false; } /** * @return {@link #binary} (A binary file that is included in the implementation guide when it is published.) */ // syntactic sugar public UriType addBinaryElement() {//2 UriType t = new UriType(); if (this.binary == null) this.binary = new ArrayList<UriType>(); this.binary.add(t); return t; } /** * @param value {@link #binary} (A binary file that is included in the implementation guide when it is published.) */ public ImplementationGuide addBinary(String value) { //1 UriType t = new UriType(); t.setValue(value); if (this.binary == null) this.binary = new ArrayList<UriType>(); this.binary.add(t); return this; } /** * @param value {@link #binary} (A binary file that is included in the implementation guide when it is published.) */ public boolean hasBinary(String value) { if (this.binary == null) return false; for (UriType v : this.binary) if (v.equals(value)) // uri return true; return false; } /** * @return {@link #page} (A page / section in the implementation guide. The root page is the implementation guide home page.) */ public ImplementationGuidePageComponent getPage() { if (this.page == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create ImplementationGuide.page"); else if (Configuration.doAutoCreate()) this.page = new ImplementationGuidePageComponent(); // cc return this.page; } public boolean hasPage() { return this.page != null && !this.page.isEmpty(); } /** * @param value {@link #page} (A page / section in the implementation guide. The root page is the implementation guide home page.) */ public ImplementationGuide setPage(ImplementationGuidePageComponent value) { this.page = value; return this; } protected void listChildren(List<Property> childrenList) { super.listChildren(childrenList); childrenList.add(new Property("url", "uri", "An absolute URL that is used to identify this implementation guide when it is referenced in a specification, model, design or an instance. This SHALL be a URL, SHOULD be globally unique, and SHOULD be an address at which this implementation guide is (or will be) published.", 0, java.lang.Integer.MAX_VALUE, url)); childrenList.add(new Property("version", "string", "The identifier that is used to identify this version of the Implementation Guide when it is referenced in a specification, model, design or instance. This is an arbitrary value managed by the Implementation Guide author manually.", 0, java.lang.Integer.MAX_VALUE, version)); childrenList.add(new Property("name", "string", "A free text natural language name identifying the Implementation Guide.", 0, java.lang.Integer.MAX_VALUE, name)); childrenList.add(new Property("status", "code", "The status of the Implementation Guide.", 0, java.lang.Integer.MAX_VALUE, status)); childrenList.add(new Property("experimental", "boolean", "This Implementation Guide was authored for testing purposes (or education/evaluation/marketing), and is not intended to be used for genuine usage.", 0, java.lang.Integer.MAX_VALUE, experimental)); childrenList.add(new Property("publisher", "string", "The name of the individual or organization that published the implementation guide.", 0, java.lang.Integer.MAX_VALUE, publisher)); childrenList.add(new Property("contact", "", "Contacts to assist a user in finding and communicating with the publisher.", 0, java.lang.Integer.MAX_VALUE, contact)); childrenList.add(new Property("date", "dateTime", "The date this version of the implementation guide was published. The date must change when the business version changes, if it does, and it must change if the status code changes. In addition, it should change when the substantive content of the implementation guide changes.", 0, java.lang.Integer.MAX_VALUE, date)); childrenList.add(new Property("description", "string", "A free text natural language description of the Implementation Guide and its use.", 0, java.lang.Integer.MAX_VALUE, description)); childrenList.add(new Property("useContext", "CodeableConcept", "The content was developed with a focus and intent of supporting the contexts that are listed. These terms may be used to assist with indexing and searching of implementation guides. The most common use of this element is to represent the country / jurisdiction for which this implementation guide was defined.", 0, java.lang.Integer.MAX_VALUE, useContext)); childrenList.add(new Property("copyright", "string", "A copyright statement relating to the implementation guide and/or its contents. Copyright statements are generally legal restrictions on the use and publishing of the details of the constraints and mappings.", 0, java.lang.Integer.MAX_VALUE, copyright)); childrenList.add(new Property("fhirVersion", "id", "The version of the FHIR specification on which this ImplementationGuide is based - this is the formal version of the specification, without the revision number, e.g. [publication].[major].[minor], which is 1.0.2 for this version.", 0, java.lang.Integer.MAX_VALUE, fhirVersion)); childrenList.add(new Property("dependency", "", "Another implementation guide that this implementation depends on. Typically, an implementation guide uses value sets, profiles etc.defined in other implementation guides.", 0, java.lang.Integer.MAX_VALUE, dependency)); childrenList.add(new Property("package", "", "A logical group of resources. Logical groups can be used when building pages.", 0, java.lang.Integer.MAX_VALUE, package_)); childrenList.add(new Property("global", "", "A set of profiles that all resources covered by this implementation guide must conform to.", 0, java.lang.Integer.MAX_VALUE, global)); childrenList.add(new Property("binary", "uri", "A binary file that is included in the implementation guide when it is published.", 0, java.lang.Integer.MAX_VALUE, binary)); childrenList.add(new Property("page", "", "A page / section in the implementation guide. The root page is the implementation guide home page.", 0, java.lang.Integer.MAX_VALUE, page)); } @Override public void setProperty(String name, Base value) throws FHIRException { if (name.equals("url")) this.url = castToUri(value); // UriType else if (name.equals("version")) this.version = castToString(value); // StringType else if (name.equals("name")) this.name = castToString(value); // StringType else if (name.equals("status")) this.status = new ConformanceResourceStatusEnumFactory().fromType(value); // Enumeration<ConformanceResourceStatus> else if (name.equals("experimental")) this.experimental = castToBoolean(value); // BooleanType else if (name.equals("publisher")) this.publisher = castToString(value); // StringType else if (name.equals("contact")) this.getContact().add((ImplementationGuideContactComponent) value); else if (name.equals("date")) this.date = castToDateTime(value); // DateTimeType else if (name.equals("description")) this.description = castToString(value); // StringType else if (name.equals("useContext")) this.getUseContext().add(castToCodeableConcept(value)); else if (name.equals("copyright")) this.copyright = castToString(value); // StringType else if (name.equals("fhirVersion")) this.fhirVersion = castToId(value); // IdType else if (name.equals("dependency")) this.getDependency().add((ImplementationGuideDependencyComponent) value); else if (name.equals("package")) this.getPackage().add((ImplementationGuidePackageComponent) value); else if (name.equals("global")) this.getGlobal().add((ImplementationGuideGlobalComponent) value); else if (name.equals("binary")) this.getBinary().add(castToUri(value)); else if (name.equals("page")) this.page = (ImplementationGuidePageComponent) value; // ImplementationGuidePageComponent else super.setProperty(name, value); } @Override public Base addChild(String name) throws FHIRException { if (name.equals("url")) { throw new FHIRException("Cannot call addChild on a primitive type ImplementationGuide.url"); } else if (name.equals("version")) { throw new FHIRException("Cannot call addChild on a primitive type ImplementationGuide.version"); } else if (name.equals("name")) { throw new FHIRException("Cannot call addChild on a primitive type ImplementationGuide.name"); } else if (name.equals("status")) { throw new FHIRException("Cannot call addChild on a primitive type ImplementationGuide.status"); } else if (name.equals("experimental")) { throw new FHIRException("Cannot call addChild on a primitive type ImplementationGuide.experimental"); } else if (name.equals("publisher")) { throw new FHIRException("Cannot call addChild on a primitive type ImplementationGuide.publisher"); } else if (name.equals("contact")) { return addContact(); } else if (name.equals("date")) { throw new FHIRException("Cannot call addChild on a primitive type ImplementationGuide.date"); } else if (name.equals("description")) { throw new FHIRException("Cannot call addChild on a primitive type ImplementationGuide.description"); } else if (name.equals("useContext")) { return addUseContext(); } else if (name.equals("copyright")) { throw new FHIRException("Cannot call addChild on a primitive type ImplementationGuide.copyright"); } else if (name.equals("fhirVersion")) { throw new FHIRException("Cannot call addChild on a primitive type ImplementationGuide.fhirVersion"); } else if (name.equals("dependency")) { return addDependency(); } else if (name.equals("package")) { return addPackage(); } else if (name.equals("global")) { return addGlobal(); } else if (name.equals("binary")) { throw new FHIRException("Cannot call addChild on a primitive type ImplementationGuide.binary"); } else if (name.equals("page")) { this.page = new ImplementationGuidePageComponent(); return this.page; } else return super.addChild(name); } public String fhirType() { return "ImplementationGuide"; } public ImplementationGuide copy() { ImplementationGuide dst = new ImplementationGuide(); copyValues(dst); dst.url = url == null ? null : url.copy(); dst.version = version == null ? null : version.copy(); dst.name = name == null ? null : name.copy(); dst.status = status == null ? null : status.copy(); dst.experimental = experimental == null ? null : experimental.copy(); dst.publisher = publisher == null ? null : publisher.copy(); if (contact != null) { dst.contact = new ArrayList<ImplementationGuideContactComponent>(); for (ImplementationGuideContactComponent i : contact) dst.contact.add(i.copy()); }; dst.date = date == null ? null : date.copy(); dst.description = description == null ? null : description.copy(); if (useContext != null) { dst.useContext = new ArrayList<CodeableConcept>(); for (CodeableConcept i : useContext) dst.useContext.add(i.copy()); }; dst.copyright = copyright == null ? null : copyright.copy(); dst.fhirVersion = fhirVersion == null ? null : fhirVersion.copy(); if (dependency != null) { dst.dependency = new ArrayList<ImplementationGuideDependencyComponent>(); for (ImplementationGuideDependencyComponent i : dependency) dst.dependency.add(i.copy()); }; if (package_ != null) { dst.package_ = new ArrayList<ImplementationGuidePackageComponent>(); for (ImplementationGuidePackageComponent i : package_) dst.package_.add(i.copy()); }; if (global != null) { dst.global = new ArrayList<ImplementationGuideGlobalComponent>(); for (ImplementationGuideGlobalComponent i : global) dst.global.add(i.copy()); }; if (binary != null) { dst.binary = new ArrayList<UriType>(); for (UriType i : binary) dst.binary.add(i.copy()); }; dst.page = page == null ? null : page.copy(); return dst; } protected ImplementationGuide typedCopy() { return copy(); } @Override public boolean equalsDeep(Base other) { if (!super.equalsDeep(other)) return false; if (!(other instanceof ImplementationGuide)) return false; ImplementationGuide o = (ImplementationGuide) other; return compareDeep(url, o.url, true) && compareDeep(version, o.version, true) && compareDeep(name, o.name, true) && compareDeep(status, o.status, true) && compareDeep(experimental, o.experimental, true) && compareDeep(publisher, o.publisher, true) && compareDeep(contact, o.contact, true) && compareDeep(date, o.date, true) && compareDeep(description, o.description, true) && compareDeep(useContext, o.useContext, true) && compareDeep(copyright, o.copyright, true) && compareDeep(fhirVersion, o.fhirVersion, true) && compareDeep(dependency, o.dependency, true) && compareDeep(package_, o.package_, true) && compareDeep(global, o.global, true) && compareDeep(binary, o.binary, true) && compareDeep(page, o.page, true); } @Override public boolean equalsShallow(Base other) { if (!super.equalsShallow(other)) return false; if (!(other instanceof ImplementationGuide)) return false; ImplementationGuide o = (ImplementationGuide) other; return compareValues(url, o.url, true) && compareValues(version, o.version, true) && compareValues(name, o.name, true) && compareValues(status, o.status, true) && compareValues(experimental, o.experimental, true) && compareValues(publisher, o.publisher, true) && compareValues(date, o.date, true) && compareValues(description, o.description, true) && compareValues(copyright, o.copyright, true) && compareValues(fhirVersion, o.fhirVersion, true) && compareValues(binary, o.binary, true); } public boolean isEmpty() { return super.isEmpty() && (url == null || url.isEmpty()) && (version == null || version.isEmpty()) && (name == null || name.isEmpty()) && (status == null || status.isEmpty()) && (experimental == null || experimental.isEmpty()) && (publisher == null || publisher.isEmpty()) && (contact == null || contact.isEmpty()) && (date == null || date.isEmpty()) && (description == null || description.isEmpty()) && (useContext == null || useContext.isEmpty()) && (copyright == null || copyright.isEmpty()) && (fhirVersion == null || fhirVersion.isEmpty()) && (dependency == null || dependency.isEmpty()) && (package_ == null || package_.isEmpty()) && (global == null || global.isEmpty()) && (binary == null || binary.isEmpty()) && (page == null || page.isEmpty()) ; } @Override public ResourceType getResourceType() { return ResourceType.ImplementationGuide; } @SearchParamDefinition(name="date", path="ImplementationGuide.date", description="The implementation guide publication date", type="date" ) public static final String SP_DATE = "date"; @SearchParamDefinition(name="dependency", path="ImplementationGuide.dependency.uri", description="Where to find dependency", type="uri" ) public static final String SP_DEPENDENCY = "dependency"; @SearchParamDefinition(name="name", path="ImplementationGuide.name", description="Name of the implementation guide", type="string" ) public static final String SP_NAME = "name"; @SearchParamDefinition(name="context", path="ImplementationGuide.useContext", description="A use context assigned to the structure", type="token" ) public static final String SP_CONTEXT = "context"; @SearchParamDefinition(name="publisher", path="ImplementationGuide.publisher", description="Name of the publisher of the implementation guide", type="string" ) public static final String SP_PUBLISHER = "publisher"; @SearchParamDefinition(name="description", path="ImplementationGuide.description", description="Text search in the description of the implementation guide", type="string" ) public static final String SP_DESCRIPTION = "description"; @SearchParamDefinition(name="experimental", path="ImplementationGuide.experimental", description="If for testing purposes, not real usage", type="token" ) public static final String SP_EXPERIMENTAL = "experimental"; @SearchParamDefinition(name="version", path="ImplementationGuide.version", description="The version identifier of the implementation guide", type="token" ) public static final String SP_VERSION = "version"; @SearchParamDefinition(name="url", path="ImplementationGuide.url", description="Absolute URL used to reference this Implementation Guide", type="uri" ) public static final String SP_URL = "url"; @SearchParamDefinition(name="status", path="ImplementationGuide.status", description="The current status of the implementation guide", type="token" ) public static final String SP_STATUS = "status"; }
apache-2.0
RohanHart/camel
components/camel-opentracing/src/main/java/org/apache/camel/opentracing/OpenTracingTracer.java
9162
/** * 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.opentracing; import java.net.URI; import java.util.EventObject; import java.util.HashMap; import java.util.Map; import java.util.ServiceLoader; import io.opentracing.Span; import io.opentracing.Tracer; import io.opentracing.Tracer.SpanBuilder; import io.opentracing.contrib.global.GlobalTracer; import io.opentracing.contrib.spanmanager.DefaultSpanManager; import io.opentracing.contrib.spanmanager.SpanManager; import io.opentracing.propagation.Format; import io.opentracing.tag.Tags; import org.apache.camel.CamelContext; import org.apache.camel.CamelContextAware; import org.apache.camel.Endpoint; import org.apache.camel.Exchange; import org.apache.camel.Route; import org.apache.camel.StaticService; import org.apache.camel.api.management.ManagedResource; import org.apache.camel.management.event.ExchangeSendingEvent; import org.apache.camel.management.event.ExchangeSentEvent; import org.apache.camel.model.RouteDefinition; import org.apache.camel.spi.RoutePolicy; import org.apache.camel.spi.RoutePolicyFactory; import org.apache.camel.support.EventNotifierSupport; import org.apache.camel.support.RoutePolicySupport; import org.apache.camel.support.ServiceSupport; import org.apache.camel.util.ObjectHelper; import org.apache.camel.util.ServiceHelper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * To use OpenTracing with Camel then setup this {@link OpenTracingTracer} in your Camel application. * <p/> * This class is implemented as both an {@link org.apache.camel.spi.EventNotifier} and {@link RoutePolicy} that allows * to trap when Camel starts/ends an {@link Exchange} being routed using the {@link RoutePolicy} and during the routing * if the {@link Exchange} sends messages, then we track them using the {@link org.apache.camel.spi.EventNotifier}. */ @ManagedResource(description = "OpenTracingTracer") public class OpenTracingTracer extends ServiceSupport implements RoutePolicyFactory, StaticService, CamelContextAware { private static final Logger LOG = LoggerFactory.getLogger(OpenTracingTracer.class); private static Map<String, SpanDecorator> decorators = new HashMap<>(); private final OpenTracingEventNotifier eventNotifier = new OpenTracingEventNotifier(); private final SpanManager spanManager = DefaultSpanManager.getInstance(); private Tracer tracer = GlobalTracer.get(); private CamelContext camelContext; static { ServiceLoader.load(SpanDecorator.class).forEach(d -> decorators.put(d.getComponent(), d)); } public OpenTracingTracer() { } @Override public RoutePolicy createRoutePolicy(CamelContext camelContext, String routeId, RouteDefinition route) { return new OpenTracingRoutePolicy(routeId); } /** * Registers this {@link OpenTracingTracer} on the {@link CamelContext}. */ public void init(CamelContext camelContext) { if (!camelContext.hasService(this)) { try { // start this service eager so we init before Camel is starting up camelContext.addService(this, true, true); } catch (Exception e) { throw ObjectHelper.wrapRuntimeCamelException(e); } } } @Override public CamelContext getCamelContext() { return camelContext; } @Override public void setCamelContext(CamelContext camelContext) { this.camelContext = camelContext; } public Tracer getTracer() { return tracer; } public void setTracer(Tracer tracer) { this.tracer = tracer; } @Override protected void doStart() throws Exception { ObjectHelper.notNull(camelContext, "CamelContext", this); camelContext.getManagementStrategy().addEventNotifier(eventNotifier); if (!camelContext.getRoutePolicyFactories().contains(this)) { camelContext.addRoutePolicyFactory(this); } if (tracer == null) { tracer = GlobalTracer.get(); } ServiceHelper.startServices(eventNotifier); } @Override protected void doStop() throws Exception { // stop event notifier camelContext.getManagementStrategy().removeEventNotifier(eventNotifier); ServiceHelper.stopService(eventNotifier); // remove route policy camelContext.getRoutePolicyFactories().remove(this); } protected SpanDecorator getSpanDecorator(Endpoint endpoint) { SpanDecorator sd = decorators.get(URI.create(endpoint.getEndpointUri()).getScheme()); if (sd == null) { return SpanDecorator.DEFAULT; } return sd; } private final class OpenTracingEventNotifier extends EventNotifierSupport { @Override public void notify(EventObject event) throws Exception { if (event instanceof ExchangeSendingEvent) { ExchangeSendingEvent ese = (ExchangeSendingEvent) event; SpanManager.ManagedSpan parent = spanManager.current(); SpanDecorator sd = getSpanDecorator(ese.getEndpoint()); SpanBuilder spanBuilder = tracer.buildSpan(sd.getOperationName(ese.getExchange(), ese.getEndpoint())) .withTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_CLIENT); // Temporary workaround to avoid adding 'null' span as a parent if (parent != null && parent.getSpan() != null) { spanBuilder.asChildOf(parent.getSpan()); } Span span = spanBuilder.start(); sd.pre(span, ese.getExchange(), ese.getEndpoint()); tracer.inject(span.context(), Format.Builtin.TEXT_MAP, new CamelHeadersInjectAdapter(ese.getExchange().getIn().getHeaders())); spanManager.manage(span); if (LOG.isTraceEnabled()) { LOG.trace("OpenTracing: start client span=" + span); } } else if (event instanceof ExchangeSentEvent) { SpanManager.ManagedSpan managedSpan = spanManager.current(); if (LOG.isTraceEnabled()) { LOG.trace("OpenTracing: start client span=" + managedSpan.getSpan()); } SpanDecorator sd = getSpanDecorator(((ExchangeSentEvent) event).getEndpoint()); sd.post(managedSpan.getSpan(), ((ExchangeSentEvent) event).getExchange(), ((ExchangeSentEvent) event).getEndpoint()); managedSpan.getSpan().finish(); managedSpan.release(); } } @Override public boolean isEnabled(EventObject event) { return event instanceof ExchangeSendingEvent || event instanceof ExchangeSentEvent; } @Override public String toString() { return "OpenTracingEventNotifier"; } } private final class OpenTracingRoutePolicy extends RoutePolicySupport { OpenTracingRoutePolicy(String routeId) { } @Override public void onExchangeBegin(Route route, Exchange exchange) { SpanDecorator sd = getSpanDecorator(route.getEndpoint()); Span span = tracer.buildSpan(sd.getOperationName(exchange, route.getEndpoint())) .asChildOf(tracer.extract(Format.Builtin.TEXT_MAP, new CamelHeadersExtractAdapter(exchange.getIn().getHeaders()))) .withTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_SERVER) .start(); sd.pre(span, exchange, route.getEndpoint()); spanManager.manage(span); if (LOG.isTraceEnabled()) { LOG.trace("OpenTracing: start server span=" + span); } } @Override public void onExchangeDone(Route route, Exchange exchange) { SpanManager.ManagedSpan managedSpan = spanManager.current(); if (LOG.isTraceEnabled()) { LOG.trace("OpenTracing: finish server span=" + managedSpan.getSpan()); } SpanDecorator sd = getSpanDecorator(route.getEndpoint()); sd.post(managedSpan.getSpan(), exchange, route.getEndpoint()); managedSpan.getSpan().finish(); managedSpan.release(); } } }
apache-2.0
witterk/closure-stylesheets
tests/com/google/common/css/compiler/gssfunctions/CustomGssFunctionsTest.java
2434
package com.google.common.css.compiler.gssfunctions; import junit.framework.TestCase; import com.google.common.collect.ImmutableList; import com.google.common.css.compiler.ast.GssFunctionException; public class CustomGssFunctionsTest extends TestCase { public void testLighten() throws GssFunctionException { CustomGssFunctions.Lighten funct = new CustomGssFunctions.Lighten(); assertEquals("#595959", funct.getCallResultString(ImmutableList.of("#333333", "15"))); } public void testDarken() throws GssFunctionException { CustomGssFunctions.Darken funct = new CustomGssFunctions.Darken(); assertEquals("#A1A1A1", funct.getCallResultString(ImmutableList.of("#bbb", "10"))); assertEquals("#7F7F7F", funct.getCallResultString(ImmutableList.of("#999999", "10"))); assertEquals("#00547F", funct.getCallResultString(ImmutableList.of("#0088cc", "15"))); } public void testMix() throws GssFunctionException { CustomGssFunctions.Mix funct = new CustomGssFunctions.Mix(); assertEquals("#800080", funct.getCallResultString(ImmutableList.of("#ff0000", "#0000ff", "50"))); } public void testSpin() throws GssFunctionException { CustomGssFunctions.Spin funct = new CustomGssFunctions.Spin(); assertEquals("#0044CC", funct.getCallResultString(ImmutableList.of("#0088cc", "20"))); } public void testArgb() throws GssFunctionException { CustomGssFunctions.Argb funct = new CustomGssFunctions.Argb(); assertEquals("#805A1794", funct.getCallResultString(ImmutableList.of("rgba(90, 23, 148, 0.5)"))); } public void testPercentage() throws GssFunctionException { CustomGssFunctions.Percentage funct = new CustomGssFunctions.Percentage(); assertEquals("5.0%", funct.getCallResultString(ImmutableList.of("0.05"))); } public void testConcat() throws GssFunctionException { CustomGssFunctions.Concat funct = new CustomGssFunctions.Concat(); assertEquals("5px, 2px", funct.getCallResultString(ImmutableList.of("5px", ", ", "2px"))); assertEquals("auto \\9", funct.getCallResultString(ImmutableList.of("auto", " \\9"))); } }
apache-2.0
cyberdrcarr/optaplanner
drools-planner-core/src/main/java/org/drools/planner/core/domain/common/DescriptorUtils.java
2199
/* * Copyright 2011 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.drools.planner.core.domain.common; import java.beans.PropertyDescriptor; import java.lang.reflect.InvocationTargetException; public class DescriptorUtils { public static Object executeGetter(PropertyDescriptor propertyDescriptor, Object bean) { try { return propertyDescriptor.getReadMethod().invoke(bean); } catch (IllegalAccessException e) { throw new IllegalStateException("Cannot call property (" + propertyDescriptor.getName() + ") getter on bean of class (" + bean.getClass() + ").", e); } catch (InvocationTargetException e) { throw new IllegalStateException("The property (" + propertyDescriptor.getName() + ") getter on bean of class (" + bean.getClass() + ") throws an exception.", e.getCause()); } } public static void executeSetter(PropertyDescriptor propertyDescriptor, Object bean, Object value) { try { propertyDescriptor.getWriteMethod().invoke(bean, value); } catch (IllegalAccessException e) { throw new IllegalStateException("Cannot call property (" + propertyDescriptor.getName() + ") setter on bean of class (" + bean.getClass() + ").", e); } catch (InvocationTargetException e) { throw new IllegalStateException("The property (" + propertyDescriptor.getName() + ") setter on bean of class (" + bean.getClass() + ") throws an exception.", e.getCause()); } } private DescriptorUtils() { } }
apache-2.0