repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
SimonSuster/semafor | src/main/java/edu/cmu/cs/lti/ark/fn/data/prep/formats/Sentence.java | 2184 | package edu.cmu.cs.lti.ark.fn.data.prep.formats;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import javax.annotation.concurrent.Immutable;
import java.util.List;
import static com.google.common.collect.ImmutableList.copyOf;
import static edu.cmu.cs.lti.ark.fn.data.prep.formats.AllLemmaTags.*;
import static edu.cmu.cs.lti.ark.util.IntRanges.xrange;
import static java.lang.Integer.parseInt;
/**
* Represents one sentence in conll format
* Conll sentences are one token per line. Sentences are separated by blank lines.
*
* @author sthomson@cs.cmu.edu
*/
@Immutable
public class Sentence {
private final ImmutableList<Token> tokens;
public Sentence(Iterable<Token> tokens) {
this.tokens = copyOf(tokens);
}
public List<Token> getTokens() {
return tokens;
}
public static Sentence fromAllLemmaTagsArray(String[][] parse) {
List<Token> toks = Lists.newArrayList();
for(int i : xrange(parse[0].length)) {
Integer head;
try {
head = parseInt(parse[PARSE_HEAD_ROW][i]);
} catch (NumberFormatException e) {
head = null;
}
final Token token =
new Token(i + 1,
parse[PARSE_TOKEN_ROW][i],
parse[PARSE_LEMMA_ROW][i],
parse[PARSE_POS_ROW][i].substring(0, 1),
parse[PARSE_POS_ROW][i],
null,
head,
parse[PARSE_DEPREL_ROW][i],
null,
null);
toks.add(token);
}
return new Sentence(toks);
}
public String[][] toAllLemmaTagsArray() {
final int length = tokens.size();
String[][] result = new String[NUM_PARSE_ROWS][length];
for(int id : xrange(length)) {
Token token = tokens.get(id);
result[PARSE_TOKEN_ROW][id] = token.getForm() == null ? "_": token.getForm();
result[PARSE_POS_ROW][id] = token.getPostag() == null ? "_": token.getPostag();
result[PARSE_NE_ROW][id] = "O";
result[PARSE_DEPREL_ROW][id] = token.getDeprel() == null ? "_" : token.getDeprel();
result[PARSE_HEAD_ROW][id] = token.getHead() == null ? "0" : token.getHead().toString();
result[PARSE_LEMMA_ROW][id] = token.getLemma() == null ? "_" : token.getLemma();
}
return result;
}
public int size() {
return tokens.size();
}
}
| gpl-3.0 |
mgax/czl-scrape | _commons-java/src/main/java/ro/code4/czl/scrape/client/representation/PublicationRepresentation.java | 4445 | package ro.code4.czl.scrape.client.representation;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import java.util.List;
import java.util.Map;
/**
* @author Ionut-Maxim Margelatu (ionut.margelatu@gmail.com)
*/
@JsonInclude(Include.NON_NULL)
public class PublicationRepresentation {
private String identifier;
private String title;
private String type;
private String institution;
private String date;
private String description;
private int feedback_days;
private Map<String, String> contact;
private List<DocumentRepresentation> documents;
public String getIdentifier() {
return identifier;
}
public void setIdentifier(String identifier) {
this.identifier = identifier;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getInstitution() {
return institution;
}
public void setInstitution(String institution) {
this.institution = institution;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getFeedback_days() {
return feedback_days;
}
public void setFeedback_days(int feedback_days) {
this.feedback_days = feedback_days;
}
public Map<String, String> getContact() {
return contact;
}
public void setContact(Map<String, String> contact) {
this.contact = contact;
}
public List<DocumentRepresentation> getDocuments() {
return documents;
}
public void setDocuments(List<DocumentRepresentation> documents) {
this.documents = documents;
}
public static final class PublicationRepresentationBuilder {
private String identifier;
private String title;
private String type;
private String institution;
private String date;
private String description;
private int feedback_days;
private Map<String, String> contact;
private List<DocumentRepresentation> documents;
private PublicationRepresentationBuilder() {
}
public static PublicationRepresentationBuilder aPublicationRepresentation() {
return new PublicationRepresentationBuilder();
}
public PublicationRepresentationBuilder withIdentifier(String identifier) {
this.identifier = identifier;
return this;
}
public PublicationRepresentationBuilder withTitle(String title) {
this.title = title;
return this;
}
public PublicationRepresentationBuilder withType(String type) {
this.type = type;
return this;
}
public PublicationRepresentationBuilder withInstitution(String institution) {
this.institution = institution;
return this;
}
public PublicationRepresentationBuilder withDate(String date) {
this.date = date;
return this;
}
public PublicationRepresentationBuilder withDescription(String description) {
this.description = description;
return this;
}
public PublicationRepresentationBuilder withFeedback_days(int feedback_days) {
this.feedback_days = feedback_days;
return this;
}
public PublicationRepresentationBuilder withContact(Map<String, String> contact) {
this.contact = contact;
return this;
}
public PublicationRepresentationBuilder withDocuments(List<DocumentRepresentation> documents) {
this.documents = documents;
return this;
}
public PublicationRepresentation build() {
PublicationRepresentation publicationRepresentation = new PublicationRepresentation();
publicationRepresentation.setIdentifier(identifier);
publicationRepresentation.setTitle(title);
publicationRepresentation.setType(type);
publicationRepresentation.setInstitution(institution);
publicationRepresentation.setDate(date);
publicationRepresentation.setDescription(description);
publicationRepresentation.setFeedback_days(feedback_days);
publicationRepresentation.setContact(contact);
publicationRepresentation.setDocuments(documents);
return publicationRepresentation;
}
}
}
| mpl-2.0 |
kuali/kc | coeus-impl/src/main/java/org/kuali/coeus/common/budget/framework/personnel/BudgetPersonnelCalculatedAmount.java | 3238 | /*
* Kuali Coeus, a comprehensive research administration system for higher education.
*
* Copyright 2005-2016 Kuali, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kuali.coeus.common.budget.framework.personnel;
import org.kuali.coeus.common.budget.api.personnel.BudgetPersonnelCalculatedAmountContract;
import org.kuali.coeus.common.budget.framework.nonpersonnel.AbstractBudgetCalculatedAmount;
import javax.persistence.*;
import org.kuali.rice.krad.data.jpa.PortableSequenceGenerator;
@Entity
@Table(name = "BUDGET_PERSONNEL_CAL_AMTS")
public class BudgetPersonnelCalculatedAmount extends AbstractBudgetCalculatedAmount implements BudgetPersonnelCalculatedAmountContract {
private static final long serialVersionUID = 3100896964798965084L;
@Column(name = "PERSON_NUMBER")
private Integer personNumber;
@PortableSequenceGenerator(name = "SEQ_BUDGET_PER_CAL_AMTS_ID")
@GeneratedValue(generator = "SEQ_BUDGET_PER_CAL_AMTS_ID")
@Id
@Column(name = "BUDGET_PERSONNEL_CAL_AMTS_ID")
private Long budgetPersonnelCalculatedAmountId;
@Column(name = "BUDGET_PERSONNEL_DETAILS_ID", insertable = false, updatable = false)
private Long budgetPersonnelLineItemId;
@ManyToOne(fetch = FetchType.LAZY, cascade = { CascadeType.REFRESH })
@JoinColumn(name = "BUDGET_PERSONNEL_DETAILS_ID", referencedColumnName = "BUDGET_PERSONNEL_DETAILS_ID")
private BudgetPersonnelDetails budgetPersonnelLineItem;
@Override
public Integer getPersonNumber() {
return personNumber;
}
public void setPersonNumber(Integer personNumber) {
this.personNumber = personNumber;
}
@Override
public Long getBudgetPersonnelCalculatedAmountId() {
return budgetPersonnelCalculatedAmountId;
}
public void setBudgetPersonnelCalculatedAmountId(Long budgetPersonnelCalculatedAmountId) {
this.budgetPersonnelCalculatedAmountId = budgetPersonnelCalculatedAmountId;
}
@Override
public Long getBudgetPersonnelLineItemId() {
return budgetPersonnelLineItemId;
}
public void setBudgetPersonnelLineItemId(Long budgetPersonnelLineItemId) {
this.budgetPersonnelLineItemId = budgetPersonnelLineItemId;
}
public BudgetPersonnelDetails getBudgetPersonnelLineItem() {
return budgetPersonnelLineItem;
}
public void setBudgetPersonnelLineItem(
BudgetPersonnelDetails budgetPersonnelLineItem) {
this.budgetPersonnelLineItem = budgetPersonnelLineItem;
}
public Long getBudgetLineItemId() {
return getBudgetPersonnelLineItem().getBudgetLineItemId();
}
}
| agpl-3.0 |
AsherBond/MondocosmOS | wonderland/modules/world/jmecolladaloader/src/classes/org/jdesktop/wonderland/modules/jmecolladaloader/client/JmeColladaCellComponentProperties.java | 6408 | /**
* Project Wonderland
*
* Copyright (c) 2004-2009, Sun Microsystems, Inc., All Rights Reserved
*
* Redistributions in source code form must reproduce the above
* copyright and this condition.
*
* The contents of this file are subject to the GNU General Public
* License, Version 2 (the "License"); you may not use this file
* except in compliance with the License. A copy of the License is
* available at http://www.opensource.org/licenses/gpl-license.php.
*
* Sun designates this particular file as subject to the "Classpath"
* exception as provided by Sun in the License file that accompanied
* this code.
*/
package org.jdesktop.wonderland.modules.jmecolladaloader.client;
import java.util.ResourceBundle;
import javax.swing.JPanel;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import org.jdesktop.wonderland.client.cell.properties.CellPropertiesEditor;
import org.jdesktop.wonderland.client.cell.properties.annotation.PropertiesFactory;
import org.jdesktop.wonderland.client.cell.properties.spi.PropertiesFactorySPI;
import org.jdesktop.wonderland.common.cell.state.CellComponentServerState;
import org.jdesktop.wonderland.common.cell.state.CellServerState;
import org.jdesktop.wonderland.modules.jmecolladaloader.common.cell.state.JmeColladaCellComponentServerState;
/**
*
* @author Jordan Slott <jslott@dev.java.net>
* @author Ronny Standtke <ronny.standtke@fhnw.ch>
*/
@PropertiesFactory(JmeColladaCellComponentServerState.class)
public class JmeColladaCellComponentProperties
extends JPanel implements PropertiesFactorySPI {
private static final ResourceBundle BUNDLE = ResourceBundle.getBundle(
"org/jdesktop/wonderland/modules/jmecolladaloader/client/Bundle");
private CellPropertiesEditor editor;
private String originalInfo;
/** Creates new form SampleComponentProperties */
public JmeColladaCellComponentProperties() {
// Initialize the GUI
initComponents();
// Listen for changes to the info text field
urlTF.getDocument().addDocumentListener(new InfoTextFieldListener());
}
/**
* @inheritDoc()
*/
public String getDisplayName() {
return BUNDLE.getString("Model_Info_Collada");
}
/**
* @inheritDoc()
*/
public JPanel getPropertiesJPanel() {
return this;
}
/**
* @inheritDoc()
*/
public void setCellPropertiesEditor(CellPropertiesEditor editor) {
this.editor = editor;
}
/**
* @inheritDoc()
*/
public void open() {
CellServerState state = editor.getCellServerState();
CellComponentServerState compState = state.getComponentServerState(
JmeColladaCellComponentServerState.class);
if (state != null) {
originalInfo =
((JmeColladaCellComponentServerState) compState).getModel();
urlTF.setText(originalInfo);
}
}
/**
* @inheritDoc()
*/
public void close() {
// Do nothing for now.
}
/**
* @inheritDoc()
*/
public void apply() {
// Fetch the latest from the info text field and set it.
CellServerState state = editor.getCellServerState();
CellComponentServerState compState = state.getComponentServerState(
JmeColladaCellComponentServerState.class);
// Model is read only
// ((JmeColladaCellComponentServerState)compState).setModel(urlTF.getText());
editor.addToUpdateList(compState);
}
/**
* @inheritDoc()
*/
public void restore() {
// Restore from the original state stored.
urlTF.setText(originalInfo);
}
/**
* Inner class to listen for changes to the text field and fire off dirty
* or clean indications to the cell properties editor.
*/
class InfoTextFieldListener implements DocumentListener {
public void insertUpdate(DocumentEvent e) {
checkDirty();
}
public void removeUpdate(DocumentEvent e) {
checkDirty();
}
public void changedUpdate(DocumentEvent e) {
checkDirty();
}
private void checkDirty() {
if (editor != null) {
String name = urlTF.getText();
editor.setPanelDirty(JmeColladaCellComponentProperties.class,
!name.equals(originalInfo));
}
}
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
urlTF = new javax.swing.JTextField();
jLabel1.setText("URL");
urlTF.setEditable(false);
org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.addContainerGap()
.add(jLabel1)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(urlTF, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 326, Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.addContainerGap()
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(jLabel1)
.add(urlTF, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.addContainerGap(252, Short.MAX_VALUE))
);
}// </editor-fold>//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel jLabel1;
private javax.swing.JTextField urlTF;
// End of variables declaration//GEN-END:variables
}
| agpl-3.0 |
mukadder/kc | coeus-impl/src/main/java/org/kuali/coeus/common/questionnaire/impl/print/QuestionnairePrintingServiceImpl.java | 8190 | /*
* Kuali Coeus, a comprehensive research administration system for higher education.
*
* Copyright 2005-2016 Kuali, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kuali.coeus.common.questionnaire.impl.print;
import org.kuali.coeus.common.framework.module.CoeusSubModule;
import org.kuali.coeus.common.framework.print.AbstractPrint;
import org.kuali.coeus.common.framework.print.Printable;
import org.kuali.coeus.common.framework.print.PrintingException;
import org.kuali.coeus.common.framework.print.PrintingService;
import org.kuali.coeus.common.questionnaire.framework.print.QuestionnairePrint;
import org.kuali.coeus.common.questionnaire.framework.print.QuestionnairePrintingService;
import org.kuali.coeus.sys.framework.model.KcPersistableBusinessObjectBase;
import org.kuali.kra.infrastructure.Constants;
import org.kuali.kra.irb.Protocol;
import org.kuali.kra.irb.actions.submit.ProtocolSubmission;
import org.kuali.coeus.common.framework.print.AttachmentDataSource;
import org.kuali.kra.protocol.actions.print.QuestionnairePrintOption;
import org.kuali.coeus.common.questionnaire.framework.core.Questionnaire;
import org.kuali.coeus.common.questionnaire.framework.core.QuestionnaireConstants;
import org.kuali.rice.krad.service.BusinessObjectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Component("questionnairePrintingService")
public class QuestionnairePrintingServiceImpl implements QuestionnairePrintingService {
private static final String PROTOCOL_NUMBER = "protocolNumber";
private static final String SUBMISSION_NUMBER = "submissionNumber";
@Autowired
@Qualifier("printingService")
private PrintingService printingService;
@Autowired
@Qualifier("questionnairePrint")
private QuestionnairePrint questionnairePrint;
@Autowired
@Qualifier("businessObjectService")
private BusinessObjectService businessObjectService;
public AttachmentDataSource printQuestionnaire(
KcPersistableBusinessObjectBase printableBusinessObject, Map<String, Object> reportParameters)
throws PrintingException {
AttachmentDataSource source = null;
AbstractPrint printable = getQuestionnairePrint();
if (printable != null) {
printable.setPrintableBusinessObject(printableBusinessObject);
printable.setReportParameters(reportParameters);
source = getPrintingService().print(printable);
source.setName("Questionnaire-" + reportParameters.get("documentNumber") + Constants.PDF_FILE_EXTENSION);
source.setType(Constants.PDF_REPORT_CONTENT_TYPE);
}
return source;
}
public AttachmentDataSource printQuestionnaireAnswer(KcPersistableBusinessObjectBase printableBusinessObject,
Map<String, Object> reportParameters) throws PrintingException {
AttachmentDataSource source = null;
AbstractPrint printable = getQuestionnairePrint();
if (printable != null) {
printable.setPrintableBusinessObject(printableBusinessObject);
printable.setReportParameters(reportParameters);
source = getPrintingService().print(printable);
source.setName("QuestionnaireAnswer" + reportParameters.get(QuestionnaireConstants.QUESTIONNAIRE_ID_PARAMETER_NAME) + Constants.PDF_FILE_EXTENSION);
source.setType(Constants.PDF_REPORT_CONTENT_TYPE);
}
return source;
}
private Questionnaire getQuestionnaire(Long questionnaireRefId) {
Map<String, Object> pkMap = new HashMap<>();
pkMap.put("id", questionnaireRefId);
return businessObjectService.findByPrimaryKey(Questionnaire.class, pkMap);
}
@Override
public List<Printable> getQuestionnairePrintable(KcPersistableBusinessObjectBase printableBusinessObject,
List<QuestionnairePrintOption> questionnairesToPrints) {
List<Printable> printables = new ArrayList<>();
for (QuestionnairePrintOption printOption : questionnairesToPrints) {
if (printOption.isSelected()) {
AbstractPrint printable = new QuestionnairePrint();
printable.setXmlStream(getQuestionnairePrint().getXmlStream());
Map<String, Object> reportParameters = new HashMap<>();
Questionnaire questionnaire = getQuestionnaire(printOption.getQuestionnaireId());
reportParameters.put(QuestionnaireConstants.QUESTIONNAIRE_SEQUENCE_ID_PARAMETER_NAME, questionnaire.getQuestionnaireSeqIdAsInteger());
reportParameters.put(QuestionnaireConstants.QUESTIONNAIRE_ID_PARAMETER_NAME, questionnaire.getId());
reportParameters.put("template", questionnaire.getTemplate());
// will be used by amendquestionnaire
reportParameters.put("moduleSubItemCode", printOption.getSubItemCode());
if (CoeusSubModule.PROTOCOL_SUBMISSION.equals(printOption.getSubItemCode())) {
reportParameters.put(PROTOCOL_NUMBER, printOption.getItemKey());
reportParameters.put(SUBMISSION_NUMBER, printOption.getSubItemKey());
}
printable.setPrintableBusinessObject(getProtocolPrintable(printOption));
printable.setReportParameters(reportParameters);
printables.add(printable);
}
}
return printables;
}
/*
* get the appropriate protocol as printable.
* need further work for requestion submission questionnaire printables
* which should be retrieved from protocolsubmission ?
*/
private Protocol getProtocolPrintable(QuestionnairePrintOption printOption) {
if (CoeusSubModule.PROTOCOL_SUBMISSION.equals(printOption.getSubItemCode())) {
Map<String, Object> keyValues = new HashMap<>();
keyValues.put("protocolNumber", printOption.getItemKey());
keyValues.put("submissionNumber", printOption.getSubItemKey());
return ((List<ProtocolSubmission>) businessObjectService.findMatchingOrderBy(ProtocolSubmission.class, keyValues,
"submissionId", false)).get(0).getProtocol();
}
else {
Map<String, Object> keyValues = new HashMap<>();
keyValues.put("protocolNumber", printOption.getItemKey());
keyValues.put("sequenceNumber", printOption.getSubItemKey());
return ((List<Protocol>) businessObjectService.findMatching(Protocol.class, keyValues)).get(0);
}
}
public PrintingService getPrintingService() {
return printingService;
}
public void setPrintingService(PrintingService printingService) {
this.printingService = printingService;
}
public QuestionnairePrint getQuestionnairePrint() {
return questionnairePrint;
}
public void setQuestionnairePrint(QuestionnairePrint questionnairePrint) {
this.questionnairePrint = questionnairePrint;
}
public void setBusinessObjectService(BusinessObjectService businessObjectService) {
this.businessObjectService = businessObjectService;
}
public BusinessObjectService getBusinessObjectService() {
return businessObjectService;
}
}
| agpl-3.0 |
meggermo/jackrabbit-oak | oak-segment/src/main/java/org/apache/jackrabbit/oak/plugins/segment/file/TarWriter.java | 17598 | /*
* 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.jackrabbit.oak.plugins.segment.file;
import static com.google.common.base.Charsets.UTF_8;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkPositionIndexes;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.collect.Lists.newArrayList;
import static com.google.common.collect.Lists.reverse;
import static com.google.common.collect.Maps.newHashMap;
import static com.google.common.collect.Maps.newLinkedHashMap;
import static com.google.common.collect.Maps.newTreeMap;
import static com.google.common.collect.Sets.newHashSet;
import static org.apache.jackrabbit.oak.plugins.segment.Segment.REF_COUNT_OFFSET;
import static org.apache.jackrabbit.oak.plugins.segment.SegmentId.isDataSegmentId;
import java.io.Closeable;
import java.io.File;
import java.io.FileDescriptor;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.UUID;
import java.util.zip.CRC32;
import com.google.common.collect.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A writer for tar files. It is also used to read entries while the file is
* still open.
*/
class TarWriter implements Closeable {
/** Logger instance */
private static final Logger log = LoggerFactory.getLogger(TarWriter.class);
/**
* Magic byte sequence at the end of the index block.
* <p>
* <ul>
* <li>For each segment in that file, an index entry that contains the UUID,
* the offset within the file and the size of the segment. Sorted by UUID,
* to allow using interpolation search.</li>
* <li>
* The index footer, which contains metadata of the index (the size,
* checksum).</li>
* </ul>
*/
static final int INDEX_MAGIC =
('\n' << 24) + ('0' << 16) + ('K' << 8) + '\n';
/**
* Magic byte sequence at the end of the graph block.
* <p>
* The file is read from the end (the tar file is read from the end: the
* last entry is the index, then the graph). File format:
* <ul>
* <li>0 padding to make the footer end at a 512 byte boundary</li>
* <li>The list of UUIDs (segments included the graph; this includes
* segments in this tar file, and referenced segments in tar files with a
* lower sequence number). 16 bytes each.</li>
* <li>The graph data. The index of the source segment UUID (in the above
* list, 4 bytes), then the list of referenced segments (the indexes of
* those; 4 bytes each). Then the list is terminated by -1.</li>
* <li>The last part is the footer, which contains metadata of the graph
* (size, checksum, the number of UUIDs).</li>
* </ul>
*
*/
static final int GRAPH_MAGIC =
('\n' << 24) + ('0' << 16) + ('G' << 8) + '\n';
/** The tar file block size. */
static final int BLOCK_SIZE = 512;
private static final byte[] ZERO_BYTES = new byte[BLOCK_SIZE];
static final int getPaddingSize(int size) {
int remainder = size % BLOCK_SIZE;
if (remainder > 0) {
return BLOCK_SIZE - remainder;
} else {
return 0;
}
}
/**
* The file being written. This instance is also used as an additional
* synchronization point by {@link #flush()} and {@link #close()} to
* allow {@link #flush()} to work concurrently with normal reads and
* writes, but not with a concurrent {@link #close()}.
*/
private final File file;
private final FileStoreMonitor monitor;
/**
* File handle. Initialized lazily in
* {@link #writeEntry(long, long, byte[], int, int)} to avoid creating
* an extra empty file when just reading from the repository.
* Should only be accessed from synchronized code.
*/
private RandomAccessFile access = null;
private FileChannel channel = null;
/**
* Flag to indicate a closed writer. Accessing a closed writer is illegal.
* Should only be accessed from synchronized code.
*/
private boolean closed = false;
/**
* Map of the entries that have already been written. Used by the
* {@link #containsEntry(long, long)} and {@link #readEntry(long, long)}
* methods to retrieve data from this file while it's still being written,
* and finally by the {@link #close()} method to generate the tar index.
* The map is ordered in the order that entries have been written.
* <p>
* Should only be accessed from synchronized code.
*/
private final Map<UUID, TarEntry> index = newLinkedHashMap();
private final Set<UUID> references = newHashSet();
/**
* Segment graph of the entries that have already been written.
*/
private final SortedMap<UUID, List<UUID>> graph = newTreeMap();
TarWriter(File file) {
this(file, FileStoreMonitor.DEFAULT);
}
TarWriter(File file, FileStoreMonitor monitor) {
this.file = file;
this.monitor = monitor;
}
/**
* Returns the number of segments written so far to this tar file.
*
* @return number of segments written so far
*/
synchronized int count() {
return index.size();
}
synchronized Set<UUID> getUUIDs() {
return newHashSet(index.keySet());
}
synchronized boolean containsEntry(long msb, long lsb) {
checkState(!closed);
return index.containsKey(new UUID(msb, lsb));
}
/**
* If the given segment is in this file, get the byte buffer that allows
* reading it.
*
* @param msb the most significant bits of the segment id
* @param lsb the least significant bits of the segment id
* @return the byte buffer, or null if not in this file
*/
ByteBuffer readEntry(long msb, long lsb) throws IOException {
checkState(!closed);
TarEntry entry;
synchronized (this) {
entry = index.get(new UUID(msb, lsb));
}
if (entry != null) {
checkState(channel != null); // implied by entry != null
ByteBuffer data = ByteBuffer.allocate(entry.size());
channel.read(data, entry.offset());
data.rewind();
return data;
} else {
return null;
}
}
long writeEntry(
long msb, long lsb, byte[] data, int offset, int size)
throws IOException {
checkNotNull(data);
checkPositionIndexes(offset, offset + size, data.length);
UUID uuid = new UUID(msb, lsb);
CRC32 checksum = new CRC32();
checksum.update(data, offset, size);
String entryName = String.format("%s.%08x", uuid, checksum.getValue());
byte[] header = newEntryHeader(entryName, size);
log.debug("Writing segment {} to {}", uuid, file);
return writeEntry(uuid, header, data, offset, size);
}
private synchronized long writeEntry(
UUID uuid, byte[] header, byte[] data, int offset, int size)
throws IOException {
checkState(!closed);
if (access == null) {
access = new RandomAccessFile(file, "rw");
channel = access.getChannel();
}
long initialLength = access.getFilePointer();
access.write(header);
access.write(data, offset, size);
int padding = getPaddingSize(size);
if (padding > 0) {
access.write(ZERO_BYTES, 0, padding);
}
long currentLength = access.getFilePointer();
checkState(currentLength <= Integer.MAX_VALUE);
TarEntry entry = new TarEntry(
uuid.getMostSignificantBits(), uuid.getLeastSignificantBits(),
(int) (currentLength - size - padding), size);
index.put(uuid, entry);
if (isDataSegmentId(uuid.getLeastSignificantBits())) {
ByteBuffer segment = ByteBuffer.wrap(data, offset, size);
int pos = segment.position();
int refcount = segment.get(pos + REF_COUNT_OFFSET) & 0xff;
if (refcount != 0) {
int refend = pos + 16 * (refcount + 1);
List<UUID> list = Lists.newArrayListWithCapacity(refcount);
for (int refpos = pos + 16; refpos < refend; refpos += 16) {
UUID refid = new UUID(
segment.getLong(refpos),
segment.getLong(refpos + 8));
if (!index.containsKey(refid)) {
references.add(refid);
}
list.add(refid);
}
Collections.sort(list);
graph.put(uuid, list);
}
}
monitor.written(currentLength - initialLength);
return currentLength;
}
/**
* Flushes the entries that have so far been written to the disk.
* This method is <em>not</em> synchronized to allow concurrent reads
* and writes to proceed while the file is being flushed. However,
* this method <em>is</em> carefully synchronized with {@link #close()}
* to prevent accidental flushing of an already closed file.
*
* @throws IOException if the tar file could not be flushed
*/
void flush() throws IOException {
synchronized (file) {
FileDescriptor descriptor = null;
synchronized (this) {
if (access != null && !closed) {
descriptor = access.getFD();
}
}
if (descriptor != null) {
descriptor.sync();
}
}
}
boolean isDirty() {
return access != null;
}
/**
* Closes this tar file.
*
* @throws IOException if the tar file could not be closed
*/
@Override
public void close() throws IOException {
// Mark this writer as closed. Note that we only need to synchronize
// this part, as no other synchronized methods should get invoked
// once close() has been initiated (see related checkState calls).
synchronized (this) {
checkState(!closed);
closed = true;
}
// If nothing was written to this file, then we're already done.
if (access == null) {
return;
}
// Complete the tar file by adding the graph, the index and the
// trailing two zero blocks. This code is synchronized on the file
// instance to ensure that no concurrent thread is still flushing
// the file when we close the file handle.
long initialPosition, currentPosition;
synchronized (file) {
initialPosition = access.getFilePointer();
writeGraph();
writeIndex();
access.write(ZERO_BYTES);
access.write(ZERO_BYTES);
currentPosition = access.getFilePointer();
access.close();
}
monitor.written(currentPosition - initialPosition);
}
private void writeGraph() throws IOException {
List<UUID> uuids = Lists.newArrayListWithCapacity(
index.size() + references.size());
uuids.addAll(index.keySet());
uuids.addAll(references);
Collections.sort(uuids);
int graphSize = uuids.size() * 16 + 16;
for (List<UUID> list : graph.values()) {
graphSize += 4 + list.size() * 4 + 4;
}
int padding = getPaddingSize(graphSize);
String graphName = file.getName() + ".gph";
byte[] header = newEntryHeader(graphName, graphSize + padding);
ByteBuffer buffer = ByteBuffer.allocate(graphSize);
Map<UUID, Integer> refmap = newHashMap();
int index = 0;
for (UUID uuid : uuids) {
buffer.putLong(uuid.getMostSignificantBits());
buffer.putLong(uuid.getLeastSignificantBits());
refmap.put(uuid, index++);
}
for (Map.Entry<UUID, List<UUID>> entry : graph.entrySet()) {
buffer.putInt(refmap.get(entry.getKey()));
for (UUID refid : entry.getValue()) {
buffer.putInt(refmap.get(refid));
}
buffer.putInt(-1);
}
CRC32 checksum = new CRC32();
checksum.update(buffer.array(), 0, buffer.position());
buffer.putInt((int) checksum.getValue());
buffer.putInt(uuids.size());
buffer.putInt(graphSize);
buffer.putInt(GRAPH_MAGIC);
access.write(header);
if (padding > 0) {
// padding comes *before* the graph!
access.write(ZERO_BYTES, 0, padding);
}
access.write(buffer.array());
}
private void writeIndex() throws IOException {
int indexSize = index.size() * 24 + 16;
int padding = getPaddingSize(indexSize);
String indexName = file.getName() + ".idx";
byte[] header = newEntryHeader(indexName, indexSize + padding);
ByteBuffer buffer = ByteBuffer.allocate(indexSize);
TarEntry[] sorted = index.values().toArray(new TarEntry[index.size()]);
Arrays.sort(sorted, TarEntry.IDENTIFIER_ORDER);
for (TarEntry entry : sorted) {
buffer.putLong(entry.msb());
buffer.putLong(entry.lsb());
buffer.putInt(entry.offset());
buffer.putInt(entry.size());
}
CRC32 checksum = new CRC32();
checksum.update(buffer.array(), 0, buffer.position());
buffer.putInt((int) checksum.getValue());
buffer.putInt(index.size());
buffer.putInt(padding + indexSize);
buffer.putInt(INDEX_MAGIC);
access.write(header);
if (padding > 0) {
// padding comes *before* the index!
access.write(ZERO_BYTES, 0, padding);
}
access.write(buffer.array());
}
private static byte[] newEntryHeader(String name, int size) {
byte[] header = new byte[BLOCK_SIZE];
// File name
byte[] nameBytes = name.getBytes(UTF_8);
System.arraycopy(
nameBytes, 0, header, 0, Math.min(nameBytes.length, 100));
// File mode
System.arraycopy(
String.format("%07o", 0400).getBytes(UTF_8), 0,
header, 100, 7);
// User's numeric user ID
System.arraycopy(
String.format("%07o", 0).getBytes(UTF_8), 0,
header, 108, 7);
// Group's numeric user ID
System.arraycopy(
String.format("%07o", 0).getBytes(UTF_8), 0,
header, 116, 7);
// File size in bytes (octal basis)
System.arraycopy(
String.format("%011o", size).getBytes(UTF_8), 0,
header, 124, 11);
// Last modification time in numeric Unix time format (octal)
long time = System.currentTimeMillis() / 1000;
System.arraycopy(
String.format("%011o", time).getBytes(UTF_8), 0,
header, 136, 11);
// Checksum for header record
System.arraycopy(
new byte[] {' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '}, 0,
header, 148, 8);
// Type flag
header[156] = '0';
// Compute checksum
int checksum = 0;
for (int i = 0; i < header.length; i++) {
checksum += header[i] & 0xff;
}
System.arraycopy(
String.format("%06o\0 ", checksum).getBytes(UTF_8), 0,
header, 148, 8);
return header;
}
/**
* Add all segment ids that are reachable from {@code referencedIds} via
* this writer's segment graph and subsequently remove those segment ids
* from {@code referencedIds} that are in this {@code TarWriter}. The
* latter can't be cleaned up anyway because they are not be present in
* any of the readers.
*
* @param referencedIds
* @throws IOException
*/
synchronized void collectReferences(Set<UUID> referencedIds) {
for (UUID uuid : reverse(newArrayList(index.keySet()))) {
if (referencedIds.remove(uuid)) {
List<UUID> refs = graph.get(uuid);
if (refs != null) {
referencedIds.addAll(refs);
}
}
}
}
//------------------------------------------------------------< Object >--
@Override
public String toString() {
return file.toString();
}
}
| apache-2.0 |
stoksey69/googleads-java-lib | modules/adwords_appengine/src/main/java/com/google/api/ads/adwords/jaxws/v201502/o/AttributeType.java | 5648 |
package com.google.api.ads.adwords.jaxws.v201502.o;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for AttributeType.
*
* <p>The following schema fragment specifies the expected content contained within this class.
* <p>
* <pre>
* <simpleType name="AttributeType">
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <enumeration value="UNKNOWN"/>
* <enumeration value="CATEGORY_PRODUCTS_AND_SERVICES"/>
* <enumeration value="COMPETITION"/>
* <enumeration value="CRITERION"/>
* <enumeration value="EXTRACTED_FROM_WEBPAGE"/>
* <enumeration value="IDEA_TYPE"/>
* <enumeration value="KEYWORD_TEXT"/>
* <enumeration value="SEARCH_VOLUME"/>
* <enumeration value="AVERAGE_CPC"/>
* <enumeration value="TARGETED_MONTHLY_SEARCHES"/>
* </restriction>
* </simpleType>
* </pre>
*
*/
@XmlType(name = "AttributeType")
@XmlEnum
public enum AttributeType {
/**
*
* Value substituted in when the actual value is not available in the Web API
* version being used. (Please upgrade to the latest published WSDL.)
* <p>This element is not supported directly by any {@link IdeaType}.
*
*
*/
UNKNOWN,
/**
*
* Represents a category ID in the "Products and Services" taxonomy.
*
* <p>Resulting attribute is
* {@link com.google.ads.api.services.common.optimization.attributes.IntegerSetAttribute}.
* <p>This element is supported by following {@link IdeaType}s: KEYWORD.
*
*
*/
CATEGORY_PRODUCTS_AND_SERVICES,
/**
*
* Represents the relative amount of competition associated with the given keyword idea,
* relative to other keywords. This value will be between 0 and 1 (inclusive).
*
* <p>Resulting attribute is
* {@link com.google.ads.api.services.common.optimization.attributes.DoubleAttribute}.
* <p>This element is supported by following {@link IdeaType}s: KEYWORD.
*
*
*/
COMPETITION,
/**
*
* Represents a placement, depending on request type.
* <p>This element is supported by following {@link IdeaType}s: PLACEMENT.
*
*
*/
CRITERION,
/**
*
* Represents the webpage from which this keyword idea was extracted (if applicable.)
*
* <p>Resulting attribute is
* {@link com.google.ads.api.services.common.optimization.attributes.WebpageDescriptorAttribute}.
* <p>This element is supported by following {@link IdeaType}s: KEYWORD.
*
*
*/
EXTRACTED_FROM_WEBPAGE,
/**
*
* Represents the type of the given idea.
*
* <p>Resulting attribute is
* {@link com.google.ads.api.services.common.optimization.attributes.IdeaTypeAttribute}.
* <p>This element is supported by following {@link IdeaType}s: KEYWORD, PLACEMENT.
*
*
*/
IDEA_TYPE,
/**
*
* Represents the keyword text for the given keyword idea.
*
* <p>Resulting attribute is
* {@link com.google.ads.api.services.common.optimization.attributes.StringAttribute}.
* <p>This element is supported by following {@link IdeaType}s: KEYWORD.
*
*
*/
KEYWORD_TEXT,
/**
*
* Represents either the (approximate) number of searches for the given keyword idea on google.com
* or google.com and partners, depending on the user's targeting.
*
* <p>Resulting attribute is
* {@link com.google.ads.api.services.common.optimization.attributes.LongAttribute}.
* <p>This element is supported by following {@link IdeaType}s: KEYWORD.
*
*
*/
SEARCH_VOLUME,
/**
*
* Represents the average cost per click historically paid for the keyword.
*
* <p>Resulting attribute is
* {@link com.google.ads.api.services.common.optimization.attributes.MoneyAttribute}.
* <p>This element is supported by following {@link IdeaType}s: KEYWORD.
*
*
*/
AVERAGE_CPC,
/**
*
* Represents the (approximated) number of searches on this keyword idea (as available for the
* past twelve months), targeted to the specified geographies.
*
* <p>Resulting attribute is
* {@link com.google.ads.api.services.common.optimization.attributes.MonthlySearchVolumeAttribute}.
* <p>This element is supported by following {@link IdeaType}s: KEYWORD.
*
*
*/
TARGETED_MONTHLY_SEARCHES;
public String value() {
return name();
}
public static AttributeType fromValue(String v) {
return valueOf(v);
}
}
| apache-2.0 |
AlanJager/zstack | sdk/src/main/java/org/zstack/sdk/sns/platform/dingtalk/RemoveSNSDingTalkAtPersonResult.java | 99 | package org.zstack.sdk.sns.platform.dingtalk;
public class RemoveSNSDingTalkAtPersonResult {
}
| apache-2.0 |
gordski/querydsl | querydsl-apt/src/main/java/com/querydsl/apt/SpatialSupport.java | 3805 | /*
* Copyright 2015, The Querydsl Team (http://www.querydsl.com/team)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.querydsl.apt;
import java.util.Map;
import java.util.Set;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.mysema.codegen.model.SimpleType;
import com.querydsl.codegen.AbstractModule;
import com.querydsl.codegen.CodegenModule;
import com.querydsl.codegen.TypeMappings;
final class SpatialSupport {
private static void registerTypes(TypeMappings typeMappings) {
Map<String, String> additions = Maps.newHashMap();
additions.put("Geometry", "GeometryPath");
additions.put("GeometryCollection", "GeometryCollectionPath");
additions.put("LinearRing", "LinearRingPath");
additions.put("LineString", "LineStringPath");
additions.put("MultiLineString", "MultiLineStringPath");
additions.put("MultiPoint", "MultiPointPath");
additions.put("MultiPolygon", "MultiPolygonPath");
additions.put("Point", "PointPath");
additions.put("Polygon", "PolygonPath");
additions.put("PolyHedralSurface", "PolyhedralSurfacePath");
for (Map.Entry<String, String> entry : additions.entrySet()) {
typeMappings.register(
new SimpleType("org.geolatte.geom." + entry.getKey()),
new SimpleType("com.querydsl.spatial." + entry.getValue()));
}
}
private static void registerJTSTypes(TypeMappings typeMappings) {
Map<String, String> additions = Maps.newHashMap();
additions.put("Geometry", "JTSGeometryPath");
additions.put("GeometryCollection", "JTSGeometryCollectionPath");
additions.put("LinearRing", "JTSLinearRingPath");
additions.put("LineString", "JTSLineStringPath");
additions.put("MultiLineString", "JTSMultiLineStringPath");
additions.put("MultiPoint", "JTSMultiPointPath");
additions.put("MultiPolygon", "JTSMultiPolygonPath");
additions.put("Point", "JTSPointPath");
additions.put("Polygon", "JTSPolygonPath");
for (Map.Entry<String, String> entry : additions.entrySet()) {
typeMappings.register(
new SimpleType("com.vividsolutions.jts.geom." + entry.getKey()),
new SimpleType("com.querydsl.spatial.jts." + entry.getValue()));
}
}
private static void addImports(AbstractModule module, String packageName) {
@SuppressWarnings("unchecked")
Set<String> imports = module.get(Set.class, CodegenModule.IMPORTS);
if (imports.isEmpty()) {
imports = ImmutableSet.of(packageName);
} else {
Set<String> old = imports;
imports = Sets.newHashSet();
imports.addAll(old);
imports.add(packageName);
}
module.bind(CodegenModule.IMPORTS, imports);
}
public static void addSupport(AbstractModule module) {
registerTypes(module.get(TypeMappings.class));
addImports(module,"com.querydsl.spatial.path");
registerJTSTypes(module.get(TypeMappings.class));
addImports(module,"com.querydsl.spatial.jts.path");
}
private SpatialSupport() { }
}
| apache-2.0 |
doom369/netty | testsuite/src/main/java/io/netty/testsuite/transport/socket/SocketReadPendingTest.java | 8338 | /*
* Copyright 2016 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.testsuite.transport.socket;
import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelConfig;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.RecvByteBufAllocator;
import io.netty.util.ReferenceCountUtil;
import io.netty.util.UncheckedBooleanSupplier;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInfo;
import org.junit.jupiter.api.Timeout;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class SocketReadPendingTest extends AbstractSocketTest {
@Test
@Timeout(value = 60000, unit = TimeUnit.MILLISECONDS)
public void testReadPendingIsResetAfterEachRead(TestInfo testInfo) throws Throwable {
run(testInfo, new Runner<ServerBootstrap, Bootstrap>() {
@Override
public void run(ServerBootstrap serverBootstrap, Bootstrap bootstrap) throws Throwable {
testReadPendingIsResetAfterEachRead(serverBootstrap, bootstrap);
}
});
}
public void testReadPendingIsResetAfterEachRead(ServerBootstrap sb, Bootstrap cb) throws Throwable {
Channel serverChannel = null;
Channel clientChannel = null;
try {
ReadPendingInitializer serverInitializer = new ReadPendingInitializer();
ReadPendingInitializer clientInitializer = new ReadPendingInitializer();
sb.option(ChannelOption.SO_BACKLOG, 1024)
.option(ChannelOption.AUTO_READ, true)
.childOption(ChannelOption.AUTO_READ, false)
// We intend to do 2 reads per read loop wakeup
.childOption(ChannelOption.RCVBUF_ALLOCATOR, new TestNumReadsRecvByteBufAllocator(2))
.childHandler(serverInitializer);
serverChannel = sb.bind().syncUninterruptibly().channel();
cb.option(ChannelOption.AUTO_READ, false)
// We intend to do 2 reads per read loop wakeup
.option(ChannelOption.RCVBUF_ALLOCATOR, new TestNumReadsRecvByteBufAllocator(2))
.handler(clientInitializer);
clientChannel = cb.connect(serverChannel.localAddress()).syncUninterruptibly().channel();
// 4 bytes means 2 read loops for TestNumReadsRecvByteBufAllocator
clientChannel.writeAndFlush(Unpooled.wrappedBuffer(new byte[4]));
// 4 bytes means 2 read loops for TestNumReadsRecvByteBufAllocator
assertTrue(serverInitializer.channelInitLatch.await(5, TimeUnit.SECONDS));
serverInitializer.channel.writeAndFlush(Unpooled.wrappedBuffer(new byte[4]));
serverInitializer.channel.read();
serverInitializer.readPendingHandler.assertAllRead();
clientChannel.read();
clientInitializer.readPendingHandler.assertAllRead();
} finally {
if (serverChannel != null) {
serverChannel.close().syncUninterruptibly();
}
if (clientChannel != null) {
clientChannel.close().syncUninterruptibly();
}
}
}
private static class ReadPendingInitializer extends ChannelInitializer<Channel> {
final ReadPendingReadHandler readPendingHandler = new ReadPendingReadHandler();
final CountDownLatch channelInitLatch = new CountDownLatch(1);
volatile Channel channel;
@Override
protected void initChannel(Channel ch) throws Exception {
channel = ch;
ch.pipeline().addLast(readPendingHandler);
channelInitLatch.countDown();
}
}
private static final class ReadPendingReadHandler extends ChannelInboundHandlerAdapter {
private final AtomicInteger count = new AtomicInteger();
private final CountDownLatch latch = new CountDownLatch(1);
private final CountDownLatch latch2 = new CountDownLatch(2);
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
ReferenceCountUtil.release(msg);
if (count.incrementAndGet() == 1) {
// Call read the first time, to ensure it is not reset the second time.
ctx.read();
}
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
latch.countDown();
latch2.countDown();
}
void assertAllRead() throws InterruptedException {
assertTrue(latch.await(5, TimeUnit.SECONDS));
// We should only do 1 read loop, because we only called read() on the first channelRead.
assertFalse(latch2.await(1, TimeUnit.SECONDS));
assertEquals(2, count.get());
}
}
/**
* Designed to read a single byte at a time to control the number of reads done at a fine granularity.
*/
private static final class TestNumReadsRecvByteBufAllocator implements RecvByteBufAllocator {
private final int numReads;
TestNumReadsRecvByteBufAllocator(int numReads) {
this.numReads = numReads;
}
@Override
public ExtendedHandle newHandle() {
return new ExtendedHandle() {
private int attemptedBytesRead;
private int lastBytesRead;
private int numMessagesRead;
@Override
public ByteBuf allocate(ByteBufAllocator alloc) {
return alloc.ioBuffer(guess(), guess());
}
@Override
public int guess() {
return 1; // only ever allocate buffers of size 1 to ensure the number of reads is controlled.
}
@Override
public void reset(ChannelConfig config) {
numMessagesRead = 0;
}
@Override
public void incMessagesRead(int numMessages) {
numMessagesRead += numMessages;
}
@Override
public void lastBytesRead(int bytes) {
lastBytesRead = bytes;
}
@Override
public int lastBytesRead() {
return lastBytesRead;
}
@Override
public void attemptedBytesRead(int bytes) {
attemptedBytesRead = bytes;
}
@Override
public int attemptedBytesRead() {
return attemptedBytesRead;
}
@Override
public boolean continueReading() {
return numMessagesRead < numReads;
}
@Override
public boolean continueReading(UncheckedBooleanSupplier maybeMoreDataSupplier) {
return continueReading();
}
@Override
public void readComplete() {
// Nothing needs to be done or adjusted after each read cycle is completed.
}
};
}
}
}
| apache-2.0 |
emre-aydin/hazelcast | hazelcast/src/test/java/com/hazelcast/internal/config/MergePolicyValidatorCachingProviderIntegrationTest.java | 6322 | /*
* Copyright (c) 2008-2021, Hazelcast, 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.hazelcast.internal.config;
import com.hazelcast.cache.impl.HazelcastServerCachingProvider;
import com.hazelcast.cache.jsr.JsrTestUtil;
import com.hazelcast.config.CacheConfig;
import com.hazelcast.config.Config;
import com.hazelcast.config.MergePolicyConfig;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.internal.config.mergepolicies.ComplexCustomMergePolicy;
import com.hazelcast.spi.merge.MergingCosts;
import com.hazelcast.spi.merge.MergingExpirationTime;
import com.hazelcast.spi.merge.PutIfAbsentMergePolicy;
import com.hazelcast.spi.merge.SplitBrainMergeTypes.MapMergeTypes;
import com.hazelcast.test.HazelcastSerialClassRunner;
import com.hazelcast.test.annotation.QuickTest;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import javax.cache.CacheManager;
import static com.hazelcast.cache.CacheTestSupport.createServerCachingProvider;
import static org.hamcrest.CoreMatchers.containsString;
/**
* Tests the integration of the {@link MergePolicyValidator}
* into the proxy creation of split-brain capable data structures.
*/
@RunWith(HazelcastSerialClassRunner.class)
@Category(QuickTest.class)
public class MergePolicyValidatorCachingProviderIntegrationTest
extends AbstractMergePolicyValidatorIntegrationTest {
@BeforeClass
public static void jsrSetup() {
JsrTestUtil.setup();
}
@AfterClass
public static void jsrTeardown() {
JsrTestUtil.cleanup();
}
@Override
void addConfig(Config config, String name, MergePolicyConfig mergePolicyConfig) {
}
private void getCache(String name, MergePolicyConfig mergePolicyConfig) {
HazelcastInstance hz = getHazelcastInstance(name, mergePolicyConfig);
HazelcastServerCachingProvider cachingProvider = createServerCachingProvider(hz);
CacheManager cacheManager = cachingProvider.getCacheManager();
CacheConfig cacheConfig = new CacheConfig();
cacheConfig.setName(name);
cacheConfig.setStatisticsEnabled(false);
cacheConfig.getMergePolicyConfig().setPolicy(mergePolicyConfig.getPolicy());
cacheManager.createCache(name, cacheConfig);
}
@Test
public void testCache_withPutIfAbsentMergePolicy() {
getCache("putIfAbsent", putIfAbsentMergePolicy);
}
@Test
public void testCache_withHyperLogLogMergePolicy() {
expectCardinalityEstimatorException();
getCache("cardinalityEstimator", hyperLogLogMergePolicy);
}
@Test
public void testCache_withHigherHitsMergePolicy() {
getCache("higherHits", higherHitsMergePolicy);
}
@Test
public void testCache_withInvalidMergePolicy() {
expectedInvalidMergePolicyException();
getCache("invalid", invalidMergePolicyConfig);
}
@Test
public void testCache_withExpirationTimeMergePolicy() {
getCache("expirationTime", expirationTimeMergePolicy);
}
/**
* ICache provides only the required {@link MergingExpirationTime},
* but not the required {@link MergingCosts} from the
* {@link ComplexCustomMergePolicy}.
* <p>
* The thrown exception should contain the merge policy name
* and the missing merge type.
*/
@Test
public void testCache_withComplexCustomMergePolicy() {
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage(containsString(complexCustomMergePolicy.getPolicy()));
expectedException.expectMessage(containsString(MergingCosts.class.getName()));
getCache("complexCustom", complexCustomMergePolicy);
}
/**
* ICache provides only some of the required merge types
* of {@link MapMergeTypes}.
* <p>
* The thrown exception should contain the merge policy name
* and the missing merge type.
*/
@Test
public void testCache_withCustomMapMergePolicyNoTypeVariable() {
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage(containsString(customMapMergePolicyNoTypeVariable.getPolicy()));
expectedException.expectMessage(containsString(MapMergeTypes.class.getName()));
getCache("customMapNoTypeVariable", customMapMergePolicyNoTypeVariable);
}
/**
* ICache provides only some of the required merge types
* of {@link MapMergeTypes}.
* <p>
* The thrown exception should contain the merge policy name
* and the missing merge type.
*/
@Test
public void testCache_withCustomMapMergePolicy() {
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage(containsString(customMapMergePolicy.getPolicy()));
expectedException.expectMessage(containsString(MapMergeTypes.class.getName()));
getCache("customMap", customMapMergePolicy);
}
@Test
public void testCache_withLegacyPutIfAbsentMergePolicy() {
MergePolicyConfig legacyMergePolicyConfig = new MergePolicyConfig()
.setPolicy(PutIfAbsentMergePolicy.class.getName());
getCache("legacyPutIfAbsent", legacyMergePolicyConfig);
}
@Override
void expectCardinalityEstimatorException() {
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage(containsString("CardinalityEstimator"));
}
@Override
void expectedInvalidMergePolicyException() {
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage(containsString(invalidMergePolicyConfig.getPolicy()));
}
}
| apache-2.0 |
zhujingling/akka-crawler-example | src/main/java/de/fhopf/akka/actor/IndexingActor.java | 995 | package de.fhopf.akka.actor;
import akka.actor.UntypedActor;
import de.fhopf.akka.Indexer;
import de.fhopf.akka.PageContent;
/**
* Indexes pages in Lucene.
* @author Florian Hopf, http://www.florian-hopf.de
*/
public class IndexingActor extends UntypedActor {
public static final Object COMMIT_MESSAGE = new Object();
public static final Object COMMITTED_MESSAGE = new Object();
private final Indexer indexer;
public IndexingActor(Indexer indexer) {
this.indexer = indexer;
}
@Override
public void onReceive(Object o) throws Exception {
if (o instanceof PageContent) {
PageContent content = (PageContent) o;
indexer.index(content);
getSender().tell(new IndexedMessage(content.getPath()), getSelf());
} else if (COMMIT_MESSAGE == o) {
indexer.commit();
getSender().tell(COMMITTED_MESSAGE, getSelf());
} else {
unhandled(o);
}
}
}
| apache-2.0 |
akosyakov/intellij-community | python/psi-api/src/com/jetbrains/python/psi/impl/PyPsiUtils.java | 17685 | /*
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jetbrains.python.psi.impl;
import com.intellij.lang.ASTNode;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.Condition;
import com.intellij.openapi.util.Couple;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.*;
import com.intellij.psi.stubs.StubElement;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.QualifiedName;
import com.intellij.util.containers.ContainerUtil;
import com.jetbrains.python.PyTokenTypes;
import com.jetbrains.python.psi.*;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
/**
* @author max
*/
public class PyPsiUtils {
private static final Logger LOG = Logger.getInstance(PyPsiUtils.class.getName());
private PyPsiUtils() {
}
@NotNull
protected static <T extends PyElement> T[] nodesToPsi(ASTNode[] nodes, T[] array) {
T[] psiElements = (T[])Array.newInstance(array.getClass().getComponentType(), nodes.length);
for (int i = 0; i < nodes.length; i++) {
//noinspection unchecked
psiElements[i] = (T)nodes[i].getPsi();
}
return psiElements;
}
/**
* Finds the closest comma after the element skipping any whitespaces in-between.
* @param element
*/
@Nullable
public static PsiElement getPrevComma(@NotNull PsiElement element) {
final PsiElement prevNode = getPrevNonWhitespaceSibling(element);
return prevNode != null && prevNode.getNode().getElementType() == PyTokenTypes.COMMA ? prevNode : null;
}
@Nullable
public static PsiElement getPrevNonWhitespaceSibling(@NotNull PsiElement element) {
return PsiTreeUtil.skipSiblingsBackward(element, PsiWhiteSpace.class);
}
/**
* Finds the closest comma before the element skipping any whitespaces in-between.
*/
@Nullable
public static PsiElement getNextComma(@NotNull PsiElement element) {
final PsiElement nextNode = getNextNonWhitespaceSibling(element);
return nextNode != null && nextNode.getNode().getElementType() == PyTokenTypes.COMMA ? nextNode : null;
}
@Nullable
public static PsiElement getNextNonWhitespaceSibling(@NotNull PsiElement element) {
return PsiTreeUtil.skipSiblingsForward(element, PsiWhiteSpace.class);
}
/**
* Finds the closest comma looking for the next comma first and then for the preceding one.
*/
@Nullable
public static PsiElement getAdjacentComma(@NotNull PsiElement element) {
final PsiElement nextComma = getNextComma(element);
return nextComma != null ? nextComma : getPrevComma(element);
}
public static void addBeforeInParent(@NotNull final PsiElement anchor, @NotNull final PsiElement... newElements) {
final ASTNode anchorNode = anchor.getNode();
LOG.assertTrue(anchorNode != null);
for (PsiElement newElement : newElements) {
anchorNode.getTreeParent().addChild(newElement.getNode(), anchorNode);
}
}
public static void removeElements(@NotNull final PsiElement... elements) {
final ASTNode parentNode = elements[0].getParent().getNode();
LOG.assertTrue(parentNode != null);
for (PsiElement element : elements) {
//noinspection ConstantConditions
parentNode.removeChild(element.getNode());
}
}
@Nullable
public static PsiElement getStatement(@NotNull final PsiElement element) {
final PyElement compStatement = getStatementList(element);
if (compStatement == null) {
return null;
}
return getParentRightBefore(element, compStatement);
}
public static PyElement getStatementList(final PsiElement element) {
//noinspection ConstantConditions
return element instanceof PyFile || element instanceof PyStatementList
? (PyElement)element
: PsiTreeUtil.getParentOfType(element, PyFile.class, PyStatementList.class);
}
/**
* Returns ancestor of the element that is also direct child of the given super parent.
*
* @param element element to start search from
* @param superParent direct parent of the desired ancestor
* @return described element or {@code null} if it doesn't exist
*/
@Nullable
public static PsiElement getParentRightBefore(@NotNull PsiElement element, @NotNull final PsiElement superParent) {
return PsiTreeUtil.findFirstParent(element, false, new Condition<PsiElement>() {
@Override
public boolean value(PsiElement element) {
return element.getParent() == superParent;
}
});
}
public static List<PsiElement> collectElements(final PsiElement statement1, final PsiElement statement2) {
// Process ASTNodes here to handle all the nodes
final ASTNode node1 = statement1.getNode();
final ASTNode node2 = statement2.getNode();
final ASTNode parentNode = node1.getTreeParent();
boolean insideRange = false;
final List<PsiElement> result = new ArrayList<PsiElement>();
for (ASTNode node : parentNode.getChildren(null)) {
// start
if (node1 == node) {
insideRange = true;
}
if (insideRange) {
result.add(node.getPsi());
}
// stop
if (node == node2) {
break;
}
}
return result;
}
public static int getElementIndentation(final PsiElement element) {
final PsiElement compStatement = getStatementList(element);
final PsiElement statement = getParentRightBefore(element, compStatement);
if (statement == null) {
return 0;
}
PsiElement sibling = statement.getPrevSibling();
if (sibling == null) {
sibling = compStatement.getPrevSibling();
}
final String whitespace = sibling instanceof PsiWhiteSpace ? sibling.getText() : "";
final int i = whitespace.lastIndexOf("\n");
return i != -1 ? whitespace.length() - i - 1 : 0;
}
public static void removeRedundantPass(final PyStatementList statementList) {
final PyStatement[] statements = statementList.getStatements();
if (statements.length > 1) {
for (PyStatement statement : statements) {
if (statement instanceof PyPassStatement) {
statement.delete();
}
}
}
}
public static boolean isMethodContext(final PsiElement element) {
final PsiNamedElement parent = PsiTreeUtil.getParentOfType(element, PyFile.class, PyFunction.class, PyClass.class);
// In case if element is inside method which is inside class
if (parent instanceof PyFunction && PsiTreeUtil.getParentOfType(parent, PyFile.class, PyClass.class) instanceof PyClass) {
return true;
}
return false;
}
@NotNull
public static PsiElement getRealContext(@NotNull final PsiElement element) {
if (!element.isValid()) {
if (LOG.isDebugEnabled()) {
LOG.debug("PyPsiUtil.getRealContext(" + element + ") called. Returned null. Element in invalid");
}
return element;
}
final PsiFile file = element.getContainingFile();
if (file instanceof PyExpressionCodeFragment) {
final PsiElement context = file.getContext();
if (LOG.isDebugEnabled()) {
LOG.debug("PyPsiUtil.getRealContext(" + element + ") is called. Returned " + context + ". Element inside code fragment");
}
return context != null ? context : element;
}
else {
if (LOG.isDebugEnabled()) {
LOG.debug("PyPsiUtil.getRealContext(" + element + ") is called. Returned " + element + ".");
}
return element;
}
}
/**
* Removes comma closest to the given child node along with any whitespaces around. First following comma is checked and only
* then, if it doesn't exists, preceding one.
*
* @param element parent node
* @param child child node comma should be adjacent to
* @see #getAdjacentComma(PsiElement)
*/
public static void deleteAdjacentCommaWithWhitespaces(@NotNull PsiElement element, @NotNull PsiElement child) {
final PsiElement commaNode = getAdjacentComma(child);
if (commaNode != null) {
final PsiElement nextNonWhitespace = getNextNonWhitespaceSibling(commaNode);
final PsiElement last = nextNonWhitespace == null ? element.getLastChild() : nextNonWhitespace.getPrevSibling();
final PsiElement prevNonWhitespace = getPrevNonWhitespaceSibling(commaNode);
final PsiElement first = prevNonWhitespace == null ? element.getFirstChild() : prevNonWhitespace.getNextSibling();
element.deleteChildRange(first, last);
}
}
/**
* Returns comments preceding given elements as pair of the first and the last such comments. Comments should not be
* separated by any empty line.
* @param element element comments should be adjacent to
* @return described range or {@code null} if there are no such comments
*/
@Nullable
public static Couple<PsiComment> getPrecedingComments(@NotNull PsiElement element) {
PsiComment firstComment = null, lastComment = null;
overComments:
while (true) {
int newLinesCount = 0;
for (element = element.getPrevSibling(); element instanceof PsiWhiteSpace; element = element.getPrevSibling()) {
newLinesCount += StringUtil.getLineBreakCount(element.getText());
if (newLinesCount > 1) {
break overComments;
}
}
if (element instanceof PsiComment) {
if (lastComment == null) {
lastComment = (PsiComment)element;
}
firstComment = (PsiComment)element;
}
else {
break;
}
}
return lastComment == null ? null : Couple.of(firstComment, lastComment);
}
@NotNull
static <T, U extends PsiElement> List<T> collectStubChildren(U e,
final StubElement<U> stub, final IElementType elementType,
final Class<T> itemClass) {
final List<T> result = new ArrayList<T>();
if (stub != null) {
final List<StubElement> children = stub.getChildrenStubs();
for (StubElement child : children) {
if (child.getStubType() == elementType) {
//noinspection unchecked
result.add((T)child.getPsi());
}
}
}
else {
e.acceptChildren(new TopLevelVisitor() {
@Override
protected void checkAddElement(PsiElement node) {
if (node.getNode().getElementType() == elementType) {
//noinspection unchecked
result.add((T)node);
}
}
});
}
return result;
}
static List<PsiElement> collectAllStubChildren(PsiElement e, StubElement stub) {
final List<PsiElement> result = new ArrayList<PsiElement>();
if (stub != null) {
final List<StubElement> children = stub.getChildrenStubs();
for (StubElement child : children) {
//noinspection unchecked
result.add(child.getPsi());
}
}
else {
e.acceptChildren(new TopLevelVisitor() {
@Override
protected void checkAddElement(PsiElement node) {
result.add(node);
}
});
}
return result;
}
@Nullable
public static PsiElement getSignificantToTheRight(PsiElement element, final boolean ignoreComments) {
while (element != null && StringUtil.isEmptyOrSpaces(element.getText()) || ignoreComments && element instanceof PsiComment) {
element = PsiTreeUtil.nextLeaf(element);
}
return element;
}
@Nullable
public static PsiElement getSignificantToTheLeft(PsiElement element, final boolean ignoreComments) {
while (element != null && StringUtil.isEmptyOrSpaces(element.getText()) || ignoreComments && element instanceof PsiComment) {
element = PsiTreeUtil.prevLeaf(element);
}
return element;
}
public static int findArgumentIndex(PyCallExpression call, PsiElement argument) {
final PyExpression[] args = call.getArguments();
for (int i = 0; i < args.length; i++) {
PyExpression expression = args[i];
if (expression instanceof PyKeywordArgument) {
expression = ((PyKeywordArgument)expression).getValueExpression();
}
expression = flattenParens(expression);
if (expression == argument) {
return i;
}
}
return -1;
}
@Nullable
public static PyTargetExpression getAttribute(@NotNull final PyFile file, @NotNull final String name) {
PyTargetExpression attr = file.findTopLevelAttribute(name);
if (attr == null) {
for (PyFromImportStatement element : file.getFromImports()) {
PyReferenceExpression expression = element.getImportSource();
if (expression == null) continue;
final PsiElement resolved = expression.getReference().resolve();
if (resolved instanceof PyFile && resolved != file) {
return ((PyFile)resolved).findTopLevelAttribute(name);
}
}
}
return attr;
}
public static List<PyExpression> getAttributeValuesFromFile(@NotNull PyFile file, @NotNull String name) {
List<PyExpression> result = ContainerUtil.newArrayList();
final PyTargetExpression attr = file.findTopLevelAttribute(name);
if (attr != null) {
sequenceToList(result, attr.findAssignedValue());
}
return result;
}
public static void sequenceToList(List<PyExpression> result, PyExpression value) {
value = flattenParens(value);
if (value instanceof PySequenceExpression) {
result.addAll(ContainerUtil.newArrayList(((PySequenceExpression)value).getElements()));
}
else {
result.add(value);
}
}
public static List<String> getStringValues(PyExpression[] elements) {
List<String> results = ContainerUtil.newArrayList();
for (PyExpression element : elements) {
if (element instanceof PyStringLiteralExpression) {
results.add(((PyStringLiteralExpression)element).getStringValue());
}
}
return results;
}
@Nullable
public static PyExpression flattenParens(@Nullable PyExpression expr) {
while (expr instanceof PyParenthesizedExpression) {
expr = ((PyParenthesizedExpression)expr).getContainedExpression();
}
return expr;
}
@Nullable
public static String strValue(@Nullable PyExpression expression) {
return expression instanceof PyStringLiteralExpression ? ((PyStringLiteralExpression)expression).getStringValue() : null;
}
public static boolean isBefore(@NotNull final PsiElement element, @NotNull final PsiElement element2) {
// TODO: From RubyPsiUtil, should be moved to PsiTreeUtil
return element.getTextOffset() <= element2.getTextOffset();
}
@Nullable
public static QualifiedName asQualifiedName(@Nullable PyExpression expr) {
return expr instanceof PyQualifiedExpression ? ((PyQualifiedExpression)expr).asQualifiedName() : null;
}
@Nullable
public static PyExpression getFirstQualifier(@NotNull PyQualifiedExpression expr) {
final List<PyExpression> expressions = unwindQualifiers(expr);
if (!expressions.isEmpty()) {
return expressions.get(0);
}
return null;
}
@NotNull
public static String toPath(@Nullable PyQualifiedExpression expr) {
if (expr != null) {
final QualifiedName qName = expr.asQualifiedName();
if (qName != null) {
return qName.toString();
}
final String name = expr.getName();
if (name != null) {
return name;
}
}
return "";
}
@Nullable
protected static QualifiedName asQualifiedName(@NotNull PyQualifiedExpression expr) {
return fromReferenceChain(unwindQualifiers(expr));
}
@NotNull
private static List<PyExpression> unwindQualifiers(@NotNull final PyQualifiedExpression expr) {
final List<PyExpression> path = new LinkedList<PyExpression>();
PyQualifiedExpression e = expr;
while (e != null) {
path.add(0, e);
final PyExpression q = e.getQualifier();
e = q instanceof PyQualifiedExpression ? (PyQualifiedExpression)q : null;
}
return path;
}
@Nullable
private static QualifiedName fromReferenceChain(@NotNull List<PyExpression> components) {
final List<String> componentNames = new ArrayList<String>(components.size());
for (PyExpression component : components) {
final String refName = (component instanceof PyQualifiedExpression) ? ((PyQualifiedExpression)component).getReferencedName() : null;
if (refName == null) {
return null;
}
componentNames.add(refName);
}
return QualifiedName.fromComponents(componentNames);
}
private static abstract class TopLevelVisitor extends PyRecursiveElementVisitor {
public void visitPyElement(final PyElement node) {
super.visitPyElement(node);
checkAddElement(node);
}
public void visitPyClass(final PyClass node) {
checkAddElement(node); // do not recurse into functions
}
public void visitPyFunction(final PyFunction node) {
checkAddElement(node); // do not recurse into classes
}
protected abstract void checkAddElement(PsiElement node);
}
} | apache-2.0 |
BiryukovVA/ignite | modules/core/src/main/java/org/apache/ignite/internal/LongJVMPauseDetector.java | 6708 | /*
* 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.ignite.internal;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.atomic.AtomicReference;
import org.apache.ignite.IgniteLogger;
import org.apache.ignite.internal.util.tostring.GridToStringInclude;
import org.apache.ignite.internal.util.typedef.internal.S;
import static org.apache.ignite.IgniteSystemProperties.IGNITE_JVM_PAUSE_DETECTOR_DISABLED;
import static org.apache.ignite.IgniteSystemProperties.IGNITE_JVM_PAUSE_DETECTOR_LAST_EVENTS_COUNT;
import static org.apache.ignite.IgniteSystemProperties.IGNITE_JVM_PAUSE_DETECTOR_PRECISION;
import static org.apache.ignite.IgniteSystemProperties.IGNITE_JVM_PAUSE_DETECTOR_THRESHOLD;
import static org.apache.ignite.IgniteSystemProperties.getBoolean;
import static org.apache.ignite.IgniteSystemProperties.getInteger;
/**
* Class for detection of long JVM pauses.
* It has a worker thread, which wakes up in cycle every {@code PRECISION} (default is 50) milliseconds,
* and monitors a time values between awakenings. If worker pause exceeds the expected value more than {@code THRESHOLD}
* default is 500), the difference is considered as JVM pause, most likely STW, and event of long JVM pause is registered.
* The values of {@code PRECISION}, {@code THRESHOLD} and {@code EVT_CNT} (event window size, default is 20) can be
* configured in system or environment properties IGNITE_JVM_PAUSE_DETECTOR_PRECISION,
* IGNITE_JVM_PAUSE_DETECTOR_THRESHOLD and IGNITE_JVM_PAUSE_DETECTOR_LAST_EVENTS_COUNT accordingly.
*/
class LongJVMPauseDetector {
/** Precision. */
private static final int PRECISION = getInteger(IGNITE_JVM_PAUSE_DETECTOR_PRECISION, 50);
/** Threshold. */
private static final int THRESHOLD = getInteger(IGNITE_JVM_PAUSE_DETECTOR_THRESHOLD, 500);
/** Event count. */
private static final int EVT_CNT = getInteger(IGNITE_JVM_PAUSE_DETECTOR_LAST_EVENTS_COUNT, 20);
/** Logger. */
private final IgniteLogger log;
/** Worker reference. */
private final AtomicReference<Thread> workerRef = new AtomicReference<>();
/** Long pause count. */
private long longPausesCnt;
/** Long pause total duration. */
private long longPausesTotalDuration;
/** Long pauses timestamps. */
@GridToStringInclude
private final long[] longPausesTimestamps = new long[EVT_CNT];
/** Long pauses durations. */
@GridToStringInclude
private final long[] longPausesDurations = new long[EVT_CNT];
/**
* @param log Logger.
*/
public LongJVMPauseDetector(IgniteLogger log) {
this.log = log;
}
/**
* Starts worker if not started yet.
*/
public void start() {
if (getBoolean(IGNITE_JVM_PAUSE_DETECTOR_DISABLED, false)) {
if (log.isDebugEnabled())
log.debug("JVM Pause Detector is disabled.");
return;
}
final Thread worker = new Thread("jvm-pause-detector-worker") {
private long prev = System.currentTimeMillis();
@Override public void run() {
if (log.isDebugEnabled())
log.debug(getName() + " has been started.");
while (true) {
try {
Thread.sleep(PRECISION);
final long now = System.currentTimeMillis();
final long pause = now - PRECISION - prev;
prev = now;
if (pause >= THRESHOLD) {
log.warning("Possible too long JVM pause: " + pause + " milliseconds.");
synchronized (LongJVMPauseDetector.this) {
final int next = (int)(longPausesCnt % EVT_CNT);
longPausesCnt++;
longPausesTotalDuration += pause;
longPausesTimestamps[next] = now;
longPausesDurations[next] = pause;
}
}
}
catch (InterruptedException e) {
if (workerRef.compareAndSet(this, null))
log.error(getName() + " has been interrupted.", e);
else if (log.isDebugEnabled())
log.debug(getName() + " has been stopped.");
break;
}
}
}
};
if (!workerRef.compareAndSet(null, worker)) {
log.warning(LongJVMPauseDetector.class.getSimpleName() + " already started!");
return;
}
worker.setDaemon(true);
worker.start();
if (log.isDebugEnabled())
log.debug("LongJVMPauseDetector was successfully started");
}
/**
* Stops the worker if one is created and running.
*/
public void stop() {
final Thread worker = workerRef.getAndSet(null);
if (worker != null && worker.isAlive() && !worker.isInterrupted())
worker.interrupt();
}
/**
* @return Long JVM pauses count.
*/
synchronized long longPausesCount() {
return longPausesCnt;
}
/**
* @return Long JVM pauses total duration.
*/
synchronized long longPausesTotalDuration() {
return longPausesTotalDuration;
}
/**
* @return Last long JVM pause events.
*/
synchronized Map<Long, Long> longPauseEvents() {
final Map<Long, Long> evts = new TreeMap<>();
for (int i = 0; i < longPausesTimestamps.length && longPausesTimestamps[i] != 0; i++)
evts.put(longPausesTimestamps[i], longPausesDurations[i]);
return evts;
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(LongJVMPauseDetector.class, this);
}
}
| apache-2.0 |
lincoln-lil/flink | flink-connectors/flink-connector-aws-kinesis-data-streams/src/test/java/org/apache/flink/connector/kinesis/sink/examples/SinkIntoKinesis.java | 3066 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.flink.connector.kinesis.sink.examples;
import org.apache.flink.api.common.serialization.SimpleStringSchema;
import org.apache.flink.connector.aws.config.AWSConfigConstants;
import org.apache.flink.connector.kinesis.sink.KinesisDataStreamsSink;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.ObjectMapper;
import software.amazon.awssdk.services.kinesis.KinesisAsyncClient;
import software.amazon.awssdk.utils.ImmutableMap;
import java.util.Properties;
/**
* An example application demonstrating how to use the {@link KinesisDataStreamsSink} to sink into
* KDS.
*
* <p>The {@link KinesisAsyncClient} used here may be configured in the standard way for the AWS SDK
* 2.x. e.g. the provision of {@code AWS_ACCESS_KEY_ID} and {@code AWS_SECRET_ACCESS_KEY} through
* environment variables etc.
*/
public class SinkIntoKinesis {
public static void main(String[] args) throws Exception {
ObjectMapper mapper = new ObjectMapper();
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.enableCheckpointing(10_000);
DataStream<String> fromGen =
env.fromSequence(1, 10_000_000L)
.map(Object::toString)
.returns(String.class)
.map(data -> mapper.writeValueAsString(ImmutableMap.of("data", data)));
Properties sinkProperties = new Properties();
sinkProperties.put(AWSConfigConstants.AWS_REGION, "your-region-here");
KinesisDataStreamsSink<String> kdsSink =
KinesisDataStreamsSink.<String>builder()
.setSerializationSchema(new SimpleStringSchema())
.setPartitionKeyGenerator(element -> String.valueOf(element.hashCode()))
.setStreamName("your-stream-name")
.setMaxBatchSize(20)
.setKinesisClientProperties(sinkProperties)
.build();
fromGen.sinkTo(kdsSink);
env.execute("KDS Async Sink Example Program");
}
}
| apache-2.0 |
kaviththiranga/developer-studio | common/org.wso2.developerstudio.eclipse.artifact.security/src/org/wso2/developerstudio/eclipse/artifact/security/utils/SecurityFormConstants.java | 7172 |
/*
* Copyright (c) 2015 WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wso2.developerstudio.eclipse.artifact.security.utils;
public class SecurityFormConstants {
public static final String ORG_WSO2_CARBON_SECURITY_CRYPTO_ALIAS = "org.wso2.carbon.security.crypto.alias";
public static final String ORG_WSO2_CARBON_SECURITY_CRYPTO_TRUSTSTORES = "org.wso2.carbon.security.crypto.truststores";
public static final String ORG_WSO2_STRATOS_TENANT_ID = "org.wso2.stratos.tenant.id";
public static final String ORG_WSO2_CARBON_SECURITY_CRYPTO_PRIVATESTORE = "org.wso2.carbon.security.crypto.privatestore";
// Constants for Rampart Config
public static final String XML_NS_SEC = "xmlns:sec";
public static final String XML_NS_SEC_ATTRIBUTE = "http://www.wso2.org/products/carbon/security";
public static final String WS_POLICY = "wsp:Policy";
public static final String KERBEROSSIGNANDENCRYPT = "kerberossignandencrypt";
public static final String RAMPART_CONFIG_USER = "rampart.config.user";
public static final String RAMPART_CONFIG = "rampart:RampartConfig";
public static final String RAMPART_USER = "rampart:user";
public static final String RAMPART_ENCRYPTION_USER = "rampart:encryptionUser";
public static final String RAMPART_NONCE_LIFE_TIME = "rampart:nonceLifeTime";
public static final String RAMPART_TOKEN_STORE_CLASS = "rampart:tokenStoreClass";
public static final String RAMPART_TIMESTAMP_STRICT = "rampart:timestampStrict";
public static final String RAMPART_TIMESTAMP_MAX_SKEW = "rampart:timestampMaxSkew";
public static final String RAMPART_TIMESTAMP_TTL = "rampart:timestampTTL";
public static final String RAMPART_TIMESTAMP_PRECISION_IN_MILLISECONDS = "rampart:timestampPrecisionInMilliseconds";
public static final String RAMPART_ENCRYPTION_CRYPTO = "rampart:encryptionCrypto";
public static final String RAMPART_SIGNATURE_CRYPTO = "rampart:signatureCrypto";
public static final String RAMPART_KERBEROS_CONFIG = "rampart:kerberosConfig";
public static final String RAMPART_CRYPTO = "rampart:crypto";
public static final String RAMPART_PROPERTY = "rampart:property";
public static final String PROPERTY_NAME = "name";
public static final String USER_ROLE = "User Roles";
// Rampart default values
public static final String RAMPART_ENCRYPTION_USER_VALUE = "useReqSigCert";
public static final String RAMPART_TOKEN_STORE_CLASS_VALUE = "org.wso2.carbon.security.util.SecurityTokenStore";
public static final String RAMPART_TIME_VALUE = "300";
public static final String RAMPART_TENANT_VALUE = "-1234";
// Constants for Carbon Sec Config
public static final String CARBONSEC_CONFIG = "sec:CarbonSecConfig";
public static final String CARBONSEC_AUTHORIZATION = "sec:Authorization";
public static final String CARBONSEC_TRUST = "sec:Trust";
public static final String CARBON_KEBEROS = "sec:Kerberos";
public static final String CARBONSEC_PROPERTY = "sec:property";
public static final String ORG_WSO2_CARBON_SECURITY_ALLOWEDROLES = "org.wso2.carbon.security.allowedroles";
public static final String SERVICE_PRINCIPAL_PASSWORD = "service.principal.password";
public static final String SERVICE_PRINCIPAL_NAME = "service.principal.name";
// public Store Constants
public static final String WSO2_PRIVATESTORE = "wso2carbon.jks";
public static final String WSO2_PRIVATESTORE_ALIAS = "wso2carbon";
// Category Names
public static final String BASIC_SCENARIOS = "Basic Scenarios";
public static final String ADVANCED_SCENARIOS = "Advanced Scenarios";
public static final String ADVANCE_CONFIGURATION = "Advance Configuration(Rampart)";
// Label Names
public static final String LABEL_USER = "User :";
public static final String LABEL_ENCRYPTION_USER = "encryptionUser :";
public static final String LABEL_PRECISION = "PrecisionInMilliseconds :";
public static final String LABEL_TIMESTAMP_TTL = "timestampTTL :";
public static final String LABEL_TIMESTAMP_MAX = "timestampMaxSkew :";
public static final String LABEL_TIMESTAMP_STRICT = "timestampStrict :";
public static final String LABEL_TOKEN_STORE_CLASS = "tokenStoreClass :";
public static final String LABEL_NONCELIFETIME = "nonceLifeTime :";
public static final String LABEL_SERVICE_PRINCIPAL_NAME = "Service Principal Name";
public static final String LABEL_SERVICE_PRINCIPAL_PASSWORD = "Service Principal Password";
public static final String EDITOR_TITLE = "WS-Policy for Service";
public static final String VALUE_TRUE = "true";
public static final String VALUE_FALSE = "false";
public static final String FILE_PREFIX = "scenario";
public static final String FILE_POSTFIX = "-policy.xml";
public static final String SANS = "Sans";
public static final String IMAGE_PREFIX = "scenario";
public static final String IMAGE_POSTFIX = ".png";
// Section Names
public static final String SECTION_SERVICE_INFO = "Service Info";
public static final String SECTION_SECURITY_SERVICE = "Security for the service";
public static final String SECTION_RAMPART_CONFIGURATION = "Rampart Configuration";
public static final String SECTION_ENCRYPTION_PROPERTIES = "Encryption Properties";
public static final String SECTION_SIGNATURE_PROPOERTIES = "Signature Properties";
public static final String SECTION_KERBEROS = "Kerberos Properties";
// Rampart Configs
public static final String ALIAS = ":Alias";
public static final String PRIVATESTORE = ":Privatestore";
public static final String TRUSTSTORES = ":Truststores";
public static final String TENANT_ID = ":Tenant id";
public static final String USER = ":User";
public static final String EN = "en";
public static final String SIGN = "sign";
public static final String POLICIES = "policies/";
public static final String PRIVATESTORE_LABEL = "Privatestore";
public static final String TRUSTSTORE_LABEL = "Truststores";
public static final String POLICY_OBJECT_UT = "UTOverTransport";
public static final String POLICY_UT = "UsernameToken";
public static final String POLICY_KERBEROS = "Kerberos Authentication - Sign - Sign based on a Kerberos Token";
//Security Scenario Description Constants
public static final String PLUGIN_NAME = "org.wso2.developerstudio.eclipse.artifact.security";
public static final String RELATIVE_FOLDER_PATH = "policies/images/";
public static final String BACKGROUD_IMAGE_RELAVIVE_PATH = "policies/images/background.png";
public static final String SHELL_WINDOW_TITLE_PREFIX = "Security Scenario ";
public static final String SECURITY_SCENARIO_TITLE_SEPARATOR = " : ";
public static final String SECURITY_SCENARIO_BUTTON_IMAGE_PATH = "icons/view.png";
}
| apache-2.0 |
gingerwizard/elasticsearch | x-pack/plugin/sql/qa/server/multi-node/src/test/java/org/elasticsearch/xpack/sql/qa/multi_node/CliShowIT.java | 398 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
package org.elasticsearch.xpack.sql.qa.multi_node;
import org.elasticsearch.xpack.sql.qa.cli.ShowTestCase;
public class CliShowIT extends ShowTestCase {}
| apache-2.0 |
emeroad/pinpoint | web/src/main/java/com/navercorp/pinpoint/web/filter/transaction/WasToWasFilter.java | 7094 | /*
* Copyright 2020 NAVER Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.navercorp.pinpoint.web.filter.transaction;
import com.navercorp.pinpoint.common.server.bo.SpanBo;
import com.navercorp.pinpoint.common.server.bo.SpanEventBo;
import com.navercorp.pinpoint.common.trace.ServiceType;
import com.navercorp.pinpoint.web.filter.Filter;
import com.navercorp.pinpoint.web.filter.RpcHint;
import com.navercorp.pinpoint.web.filter.RpcType;
import com.navercorp.pinpoint.web.filter.URLPatternFilter;
import com.navercorp.pinpoint.web.filter.agent.AgentFilterFactory;
import com.navercorp.pinpoint.web.filter.visitor.SpanAcceptor;
import com.navercorp.pinpoint.web.filter.visitor.SpanEventVisitor;
import com.navercorp.pinpoint.web.filter.visitor.SpanReader;
import com.navercorp.pinpoint.web.filter.visitor.SpanVisitor;
import java.util.List;
import java.util.Objects;
/**
* @author Woonduk Kang(emeroad)
*/
public class WasToWasFilter implements Filter<LinkContext> {
private final Filter<SpanBo> spanResponseConditionFilter;
private final Filter<SpanEventBo> spanEventResponseConditionFilter;
private final AgentFilterFactory agentFilterFactory;
private final URLPatternFilter acceptURLFilter;
private final URLPatternFilter rpcUrlFilter;
private final List<RpcHint> rpcHintList;
public WasToWasFilter(Filter<SpanBo> spanResponseConditionFilter,
Filter<SpanEventBo> spanEventResponseConditionFilter,
URLPatternFilter acceptURLFilter,
AgentFilterFactory agentFilterFactory,
URLPatternFilter rpcUrlFilter,
List<RpcHint> rpcHintList) {
this.spanResponseConditionFilter = Objects.requireNonNull(spanResponseConditionFilter, "spanResponseConditionFilter");
this.spanEventResponseConditionFilter = Objects.requireNonNull(spanEventResponseConditionFilter, "spanEventResponseConditionFilter");
this.acceptURLFilter = Objects.requireNonNull(acceptURLFilter, "acceptURLFilter");
this.agentFilterFactory = Objects.requireNonNull(agentFilterFactory, "agentFilterFactory");
this.rpcUrlFilter = Objects.requireNonNull(rpcUrlFilter, "rpcUrlFilter");
this.rpcHintList = Objects.requireNonNull(rpcHintList, "rpcHintList");
}
public boolean include(LinkContext transaction) {
/*
* WAS -> WAS
* if destination is a "WAS", the span of src and dest may exist. need to check if be circular or not.
* find src first. span (from, to) may exist more than one. so (spanId == parentSpanID) should be checked.
*/
final List<SpanBo> fromSpanList = transaction.findFromNode();
if (fromSpanList.isEmpty()) {
// from span not found
return Filter.REJECT;
}
final List<SpanBo> toSpanList = transaction.findToNode(acceptURLFilter);
if (!toSpanList.isEmpty()) {
// from -> to compare SpanId & pSpanId filter
final boolean exactMatch = wasToWasExactMatch(fromSpanList, toSpanList);
if (exactMatch) {
return Filter.ACCEPT;
}
}
if (this.agentFilterFactory.toAgentExist()) {
// fast skip. toAgent filtering condition exist.
// url filter not available.
return Filter.REJECT;
}
// Check for url pattern should now be done on the caller side (from spans) as to spans are missing at this point
if (!rpcUrlFilter.accept(fromSpanList)) {
return Filter.REJECT;
}
// if agent filter is FromAgentFilter or AcceptAgentFilter(agent filter is not selected), url filtering is available.
return fromBaseFilter(fromSpanList, transaction);
}
private boolean fromBaseFilter(List<SpanBo> fromSpanList, LinkContext transaction) {
// from base filter. hint base filter
// exceptional case
// 1. remote call fail
// 2. span packet lost.
if (rpcHintList.isEmpty()) {
// fast skip. There is nothing more we can do if rpcHintList is empty.
return false;
}
SpanAcceptor acceptor = new SpanReader(fromSpanList);
return acceptor.accept(new SpanEventVisitor() {
@Override
public boolean visit(SpanEventBo spanEventBo) {
return filterByRpcHints(spanEventBo, transaction);
}
});
}
private boolean filterByRpcHints(SpanEventBo spanEventBo, LinkContext transaction) {
if (filterByRpcHints(rpcHintList, spanEventBo, transaction)) {
return SpanVisitor.ACCEPT;
}
return SpanVisitor.REJECT;
}
private boolean filterByRpcHints(List<RpcHint> rpcHintList, SpanEventBo event, LinkContext transaction) {
final ServiceType eventServiceType = transaction.findServiceType(event.getServiceType());
if (!eventServiceType.isRecordStatistics()) {
return false;
}
if (eventServiceType.isRpcClient() || eventServiceType.isQueue()) {
// check rpc call fail
// There are also cases where multiple applications receiving the same request from the caller node
// but not all of them have agents installed. RpcHint is used for such cases as acceptUrlFilter will
// reject these transactions.
for (RpcHint rpcHint : rpcHintList) {
for (RpcType rpcType : rpcHint.getRpcTypeList()) {
if (rpcType.isMatched(event.getDestinationId(), eventServiceType.getCode())) {
if (spanEventResponseConditionFilter.include(event)) {
return Filter.ACCEPT;
}
}
}
}
}
return Filter.REJECT;
}
private boolean wasToWasExactMatch(List<SpanBo> fromSpanList, List<SpanBo> toSpanList) {
// from -> to compare SpanId & pSpanId filter
for (SpanBo fromSpanBo : fromSpanList) {
for (SpanBo toSpanBo : toSpanList) {
if (fromSpanBo == toSpanBo) {
// skip same object;
continue;
}
if (fromSpanBo.getSpanId() == toSpanBo.getParentSpanId()) {
if (spanResponseConditionFilter.include(toSpanBo)) {
return Filter.ACCEPT;
}
}
}
}
return Filter.REJECT;
}
}
| apache-2.0 |
jomarko/drools | drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/compiler/lang/DRLContextTest.java | 112795 | /*
* Copyright 2015 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* 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.mvel.compiler.lang;
import java.util.LinkedList;
import org.antlr.runtime.RecognitionException;
import org.antlr.runtime.Token;
import org.drools.compiler.compiler.DroolsParserException;
import org.drools.compiler.lang.DRLParser;
import org.drools.compiler.lang.DroolsEditorType;
import org.drools.compiler.lang.DroolsToken;
import org.drools.compiler.lang.Location;
import org.drools.core.base.evaluators.EvaluatorRegistry;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.kie.internal.builder.conf.LanguageLevelOption;
import static org.drools.compiler.compiler.DRLFactory.buildParser;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class DRLContextTest {
@Before
public void setUp() throws Exception {
// initializes pluggable operators
new EvaluatorRegistry();
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_OPERATORS_AND_COMPLEMENT1()
throws DroolsParserException, RecognitionException {
String input = "rule MyRule when Class ( property memberOf collection ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals( Location.LOCATION_LHS_INSIDE_CONDITION_END,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_OPERATORS_AND_COMPLEMENT2()
throws DroolsParserException, RecognitionException {
String input = "rule MyRule when Class ( property not memberOf collection";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_INSIDE_CONDITION_ARGUMENT,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_COMPOSITE_OPERATOR1()
throws DroolsParserException, RecognitionException {
String input = "rule MyRule when Class ( property in ( ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_INSIDE_CONDITION_ARGUMENT,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_BEGIN_OF_CONDITION1()
throws DroolsParserException, RecognitionException {
String input = "rule MyRule \n" + " when \n" + " ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_BEGIN_OF_CONDITION,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_BEGIN_OF_CONDITION2() {
String input = "rule MyRule \n" + " when \n"
+ " Class( condition == true ) \n" + " ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_BEGIN_OF_CONDITION,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_BEGIN_OF_CONDITION3() {
String input = "rule MyRule \n" + " when \n"
+ " class: Class( condition == true, condition2 == null ) \n"
+ " ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_BEGIN_OF_CONDITION,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_BEGIN_OF_CONDITION4() {
String input = "rule MyRule \n" + " when \n" + " Cl";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_BEGIN_OF_CONDITION,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_BEGIN_OF_CONDITION5() {
String input = "rule MyRule \n" + " when \n"
+ " Class( condition == true ) \n" + " Cl";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_BEGIN_OF_CONDITION,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_BEGIN_OF_CONDITION6() {
String input = "rule MyRule \n" + " when \n" + " class: Cl";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_BEGIN_OF_CONDITION,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_BEGIN_OF_CONDITION7() {
String input = "rule MyRule \n" + " when \n" + " class:Cl";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_BEGIN_OF_CONDITION,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
/** Inside of condition: start */
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_INSIDE_CONDITION_START1() {
String input = "rule MyRule \n" + " when \n" + " Class (";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_INSIDE_CONDITION_START,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_INSIDE_CONDITION_START2() {
String input = "rule MyRule \n" + " when \n" + " Class ( na";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_INSIDE_CONDITION_START,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_INSIDE_CONDITION_START3() {
String input = "rule MyRule \n" + " when \n"
+ " Class ( name.subProperty['test'].subsu";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_INSIDE_CONDITION_START,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_INSIDE_CONDITION_START4() {
String input = "rule MyRule \n" + " when \n"
+ " Class ( condition == true, ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_INSIDE_CONDITION_START,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_INSIDE_CONDITION_START5() {
String input = "rule MyRule \n" + " when \n"
+ " Class ( condition == true, na";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_INSIDE_CONDITION_START,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_INSIDE_CONDITION_START6() {
String input = "rule MyRule \n" + " when \n" + " Class ( \n" + " ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_INSIDE_CONDITION_START,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_INSIDE_CONDITION_START7() {
String input = "rule MyRule \n" + " when \n"
+ " Class ( condition == true, \n" + " ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_INSIDE_CONDITION_START,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_INSIDE_CONDITION_START8() {
String input = "rule MyRule \n" + " when \n"
+ " Class ( c: condition, \n" + " ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
DroolsToken token = (DroolsToken) parser.getEditorInterface().get(0)
.getContent().get(11);
assertEquals("c",
token.getText() );
assertEquals( DroolsEditorType.IDENTIFIER_VARIABLE, token
.getEditorType());
assertEquals(Location.LOCATION_LHS_INSIDE_CONDITION_START,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_INSIDE_CONDITION_START9a() {
String input = "rule MyRule \n" + " when \n" + " Class ( name:";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_INSIDE_CONDITION_START,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_INSIDE_CONDITION_START9b() {
String input = "rule MyRule \n" + " when \n" + " Class ( name: ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_INSIDE_CONDITION_START,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_INSIDE_CONDITION_START10() {
String input = "rule MyRule \n" + " when \n" + " Class ( name:";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_INSIDE_CONDITION_START,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
/** Inside of condition: Operator */
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_INSIDE_CONDITION_OPERATOR1() {
String input = "rule MyRule \n" + " when \n" + " Class ( property ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_INSIDE_CONDITION_OPERATOR,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_INSIDE_CONDITION_OPERATOR2() {
String input = "rule MyRule \n" + " when \n" + " Class(property ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_INSIDE_CONDITION_OPERATOR,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_INSIDE_CONDITION_OPERATOR3() {
String input = "rule MyRule \n" + " when \n"
+ " Class ( name : property ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_INSIDE_CONDITION_OPERATOR,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_INSIDE_CONDITION_OPERATOR4() {
String input = "rule MyRule \n" + " when \n"
+ " Class (name:property ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_INSIDE_CONDITION_OPERATOR,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_INSIDE_CONDITION_OPERATOR5() {
String input = "rule MyRule \n" + " when \n"
+ " Class (name:property ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_INSIDE_CONDITION_OPERATOR,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_INSIDE_CONDITION_OPERATOR6() {
String input = "rule MyRule \n" + " when \n"
+ " Class ( name1 : property1, name : property ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_INSIDE_CONDITION_OPERATOR,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_INSIDE_CONDITION_OPERATOR7() {
String input = "rule MyRule \n" + " when \n"
+ " Class ( name1 : property1 == \"value\", name : property ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_INSIDE_CONDITION_OPERATOR,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_INSIDE_CONDITION_OPERATOR8() {
String input = "rule MyRule \n" + " when \n"
+ " Class ( name1 : property1 == \"value\",property ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_INSIDE_CONDITION_OPERATOR,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_INSIDE_CONDITION_OPERATOR9() {
String input = "rule MyRule \n" + " when \n"
+ " Class ( name1 : property1, \n" + " name : property ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_INSIDE_CONDITION_OPERATOR,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
/** Inside of condition: argument */
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_INSIDE_CONDITION_ARGUMENT1() {
String input = "rule MyRule \n" + " when \n" + " Class ( property == ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_INSIDE_CONDITION_ARGUMENT,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_INSIDE_CONDITION_ARGUMENT2() {
String input = "rule MyRule \n" + " when \n" + " Class ( property== ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_INSIDE_CONDITION_ARGUMENT,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_INSIDE_CONDITION_ARGUMENT3() {
String input = "rule MyRule \n" + " when \n"
+ " Class ( name : property <= ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_INSIDE_CONDITION_ARGUMENT,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_INSIDE_CONDITION_ARGUMENT4() {
String input = "rule MyRule \n" + " when \n"
+ " Class ( name:property != ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_INSIDE_CONDITION_ARGUMENT,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_INSIDE_CONDITION_ARGUMENT5() {
String input = "rule MyRule \n" + " when \n"
+ " Class ( name1 : property1, property2 == ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_INSIDE_CONDITION_ARGUMENT,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_INSIDE_CONDITION_ARGUMENT6() {
String input = "rule MyRule \n" + " when \n"
+ " Class (name:property== ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_INSIDE_CONDITION_ARGUMENT,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_INSIDE_CONDITION_ARGUMENT7a() {
String input = "rule MyRule \n" + " when \n"
+ " Class ( property == otherPropertyN";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_INSIDE_CONDITION_ARGUMENT,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_INSIDE_CONDITION_ARGUMENT7b() {
String input = "rule MyRule \n" + " when \n"
+ " Class ( property == otherPropertyN ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_INSIDE_CONDITION_END,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_INSIDE_CONDITION_ARGUMENT8() {
String input = "rule MyRule \n" + " when \n"
+ " Class ( property == \"someth";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_INSIDE_CONDITION_ARGUMENT,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_INSIDE_CONDITION_ARGUMENT9a() {
String input = "rule MyRule \n" + " when \n"
+ " Class ( property contains ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_INSIDE_CONDITION_ARGUMENT,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_INSIDE_CONDITION_ARGUMENT9b() {
String input = "rule MyRule \n" + " when \n"
+ " Class ( property not contains ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_INSIDE_CONDITION_ARGUMENT,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_INSIDE_CONDITION_ARGUMENT10() {
String input = "rule MyRule \n" + " when \n"
+ " Class ( property excludes ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_INSIDE_CONDITION_ARGUMENT,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_INSIDE_CONDITION_ARGUMENT11() {
String input = "rule MyRule \n" + " when \n"
+ " Class ( property matches \"prop";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_INSIDE_CONDITION_ARGUMENT,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_INSIDE_CONDITION_ARGUMENT12() {
String input = "rule MyRule \n" + " when \n" + " Class ( property in ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_INSIDE_CONDITION_ARGUMENT,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test
public void testCheckLHSLocationDetermination_INSIDE_CONDITION_END1() {
String input = "rule MyRule \n" + " when \n"
+ " Class ( property in ('1', '2') ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_INSIDE_CONDITION_END,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_INSIDE_CONDITION_START11() {
String input = "rule MyRule \n" + " when \n"
+ " Class ( property in ('1', '2'), ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_INSIDE_CONDITION_START,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
@Ignore
public void testCheckLHSLocationDetermination_INSIDE_CONDITION_ARGUMENT13() {
String input = "rule MyRule \n" + " when \n"
+ " Class ( property not in ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_INSIDE_CONDITION_ARGUMENT,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_INSIDE_CONDITION_END2() {
String input = "rule MyRule \n" + " when \n"
+ " Class ( property not in ('1', '2') ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_INSIDE_CONDITION_END,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_INSIDE_CONDITION_START12() {
String input = "rule MyRule \n" + " when \n"
+ " Class ( property not in ('1', '2'), ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_INSIDE_CONDITION_START,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_INSIDE_CONDITION_ARGUMENT14() {
String input = "rule MyRule \n" + " when \n"
+ " Class ( property memberOf ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_INSIDE_CONDITION_ARGUMENT,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000) @Ignore
public void testCheckLHSLocationDetermination_INSIDE_CONDITION_END3() {
// FIXME for now it will be a limitation of the parser... memberOf is a
// soft-keyword and this sentence cannot be parsed correctly if
// misspelling
String input = "rule MyRule \n" + " when \n"
+ " Class ( property memberOf collection ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_INSIDE_CONDITION_END,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_INSIDE_CONDITION_START13() {
String input = "rule MyRule \n" + " when \n"
+ " Class ( property memberOf collection, ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_INSIDE_CONDITION_START,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_INSIDE_CONDITION_ARGUMENT15() {
String input = "rule MyRule \n" + " when \n"
+ " Class ( property not memberOf ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_INSIDE_CONDITION_ARGUMENT,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_INSIDE_CONDITION_END4() {
String input = "rule MyRule \n" + " when \n"
+ " Class ( property not memberOf collection ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_INSIDE_CONDITION_END,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_INSIDE_CONDITION_START14() {
String input = "rule MyRule \n" + " when \n"
+ " Class ( property not memberOf collection, ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
LinkedList list = parser.getEditorInterface().get(0).getContent();
// for (Object o: list) {
// System.out.println(o);
// }
assertEquals(Location.LOCATION_LHS_INSIDE_CONDITION_START,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
/** EXISTS */
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_BEGIN_OF_CONDITION_EXISTS1() {
String input = "rule MyRule \n" + " when \n" + " exists ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_BEGIN_OF_CONDITION_EXISTS,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_BEGIN_OF_CONDITION_EXISTS2() {
String input = "rule MyRule \n" + " when \n" + " exists ( ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_BEGIN_OF_CONDITION_EXISTS,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_BEGIN_OF_CONDITION_EXISTS3() {
String input = "rule MyRule \n" + " when \n" + " exists(";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_BEGIN_OF_CONDITION_EXISTS,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_BEGIN_OF_CONDITION_EXISTS4() {
String input = "rule MyRule \n" + " when \n" + " exists Cl";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_BEGIN_OF_CONDITION_EXISTS,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_BEGIN_OF_CONDITION_EXISTS5() {
String input = "rule MyRule \n" + " when \n" + " exists ( Cl";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_BEGIN_OF_CONDITION_EXISTS,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_BEGIN_OF_CONDITION_EXISTS6() {
String input = "rule MyRule \n" + " when \n" + " exists ( name : Cl";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_BEGIN_OF_CONDITION_EXISTS,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDeterminationINSIDE_CONDITION_START16() {
String input = "rule MyRule \n" + " when \n" + " exists Class (";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_INSIDE_CONDITION_START,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_BEGIN_OF_CONDITION() {
String input = "rule MyRule \n" + " when \n" + " exists Class ( ) \n"
+ " ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_BEGIN_OF_CONDITION,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
/** NOT */
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_BEGIN_OF_CONDITION_NOT1() {
String input = "rule MyRule \n" + " when \n" + " not ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_BEGIN_OF_CONDITION_NOT,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_BEGIN_OF_CONDITION_NOT2() {
String input = "rule MyRule \n" + " when \n" + " not Cl";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_BEGIN_OF_CONDITION_NOT,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_BEGIN_OF_CONDITION_EXISTS7() {
String input = "rule MyRule \n" + " when \n" + " not ( exists ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_BEGIN_OF_CONDITION_EXISTS,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_BEGIN_OF_CONDITION_EXISTS8() {
String input = "rule MyRule \n" + " when \n" + " not ( exists Cl";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_BEGIN_OF_CONDITION_EXISTS,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_INSIDE_CONDITION_START21() {
String input = "rule MyRule \n" + " when \n" + " not Class (";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_INSIDE_CONDITION_START,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_INSIDE_CONDITION_START22() {
String input = "rule MyRule \n" + " when \n" + " not ( exists Class (";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_INSIDE_CONDITION_START,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_INSIDE_CONDITION_START23() {
String input = "rule MyRule \n" + " when \n"
+ " not ( exists name : Class (";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_INSIDE_CONDITION_START,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_BEGIN_OF_CONDITION9() {
String input = "rule MyRule \n" + " when \n" + " not Class () \n"
+ " ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_BEGIN_OF_CONDITION,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
/** AND */
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_BEGIN_OF_CONDITION_AND_OR1() {
String input = "rule MyRule \n" + " when \n" + " Class ( ) and ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_BEGIN_OF_CONDITION_AND_OR,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_BEGIN_OF_CONDITION_AND_OR2() {
String input = "rule MyRule \n" + " when \n" + " Class ( ) and ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_BEGIN_OF_CONDITION_AND_OR,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_BEGIN_OF_CONDITION_AND_OR3() {
String input = "rule MyRule \n" + " when \n" + " Class () and ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_BEGIN_OF_CONDITION_AND_OR,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_BEGIN_OF_CONDITION_AND_OR4() {
String input = "rule MyRule \n" + " when \n"
+ " name : Class ( name: property ) and ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_BEGIN_OF_CONDITION_AND_OR,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
DroolsToken token = (DroolsToken) parser.getEditorInterface().get(0)
.getContent().get(12);
assertEquals(DroolsEditorType.IDENTIFIER_VARIABLE, token
.getEditorType());
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_BEGIN_OF_CONDITION_AND_OR5() {
String input = "rule MyRule \n" + " when \n"
+ " Class ( name: property ) \n" + " and ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_BEGIN_OF_CONDITION_AND_OR,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_BEGIN_OF_CONDITION_AND_OR6() {
String input = "rule MyRule \n" + " when \n" + " Class ( ) and Cl";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_BEGIN_OF_CONDITION_AND_OR,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_BEGIN_OF_CONDITION_AND_OR7() {
String input = "rule MyRule \n" + " when \n"
+ " Class ( ) and name : Cl";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_BEGIN_OF_CONDITION_AND_OR,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_BEGIN_OF_CONDITION_AND_OR8() {
String input = "rule MyRule \n" + " when \n"
+ " Class ( ) and name : Cl";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_BEGIN_OF_CONDITION_AND_OR,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_BEGIN_OF_CONDITION31() {
String input = "rule MyRule \n" + " when \n"
+ " Class ( ) and Class ( ) \n" + " ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_BEGIN_OF_CONDITION,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_BEGIN_OF_CONDITION32() {
String input = "rule MyRule \n" + " when \n"
+ " Class ( ) and not Class ( ) \n" + " ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_BEGIN_OF_CONDITION,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_BEGIN_OF_CONDITION33() {
String input = "rule MyRule \n" + " when \n"
+ " Class ( ) and exists Class ( ) \n" + " ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_BEGIN_OF_CONDITION,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_INSIDE_CONDITION_START20() {
String input = "rule MyRule \n" + " when \n"
+ " Class ( ) and Class ( ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_INSIDE_CONDITION_START,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_INSIDE_CONDITION_OPERATOR21() {
String input = "rule MyRule \n" + " when \n"
+ " Class ( ) and Class ( name ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_INSIDE_CONDITION_OPERATOR,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_INSIDE_CONDITION_OPERATOR22() {
String input = "rule MyRule \n" + " when \n"
+ " Class ( ) and Class ( name == ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_INSIDE_CONDITION_ARGUMENT,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_BEGIN_OF_CONDITION_NOT() {
String input = "rule MyRule \n" + " when \n"
+ " exists Class ( ) and not ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_BEGIN_OF_CONDITION_NOT,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_BEGIN_OF_CONDITION_EXISTS() {
String input = "rule MyRule \n" + " when \n"
+ " exists Class ( ) and exists ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_BEGIN_OF_CONDITION_EXISTS,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_BEGIN_OF_CONDITION30() {
String input = "rule MyRule \n" + " when \n"
+ " Class ( ) and not Class ( ) \n" + " ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_BEGIN_OF_CONDITION,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
/** OR */
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_BEGIN_OF_CONDITION_AND_OR21() {
String input = "rule MyRule \n" + " when \n" + " Class ( ) or ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_BEGIN_OF_CONDITION_AND_OR,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_BEGIN_OF_CONDITION_AND_OR22() {
String input = "rule MyRule \n" + " when \n" + " Class ( ) or ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_BEGIN_OF_CONDITION_AND_OR,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_BEGIN_OF_CONDITION_AND_OR23() {
String input = "rule MyRule \n" + " when \n" + " Class () or ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_BEGIN_OF_CONDITION_AND_OR,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_BEGIN_OF_CONDITION_AND_OR24() {
String input = "rule MyRule \n" + " when \n"
+ " name : Class ( name: property ) or ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_BEGIN_OF_CONDITION_AND_OR,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_BEGIN_OF_CONDITION_AND_OR25() {
String input = "rule MyRule \n" + " when \n"
+ " Class ( name: property ) \n" + " or ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_BEGIN_OF_CONDITION_AND_OR,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_BEGIN_OF_CONDITION_AND_OR26() {
String input = "rule MyRule \n" + " when \n" + " Class ( ) or Cl";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_BEGIN_OF_CONDITION_AND_OR,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_BEGIN_OF_CONDITION_AND_OR27() {
String input = "rule MyRule \n" + " when \n"
+ " Class ( ) or name : Cl";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_BEGIN_OF_CONDITION_AND_OR,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_BEGIN_OF_CONDITION_AND_OR28() {
String input = "rule MyRule \n" + " when \n"
+ " Class ( ) or name : Cl";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_BEGIN_OF_CONDITION_AND_OR,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_BEGIN_OF_CONDITION40() {
String input = "rule MyRule \n" + " when \n"
+ " Class ( ) or Class ( ) \n" + " ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_BEGIN_OF_CONDITION,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_INSIDE_CONDITION_START40() {
String input = "rule MyRule \n" + " when \n"
+ " Class ( ) or Class ( ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_INSIDE_CONDITION_START,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_INSIDE_CONDITION_OPERATOR() {
String input = "rule MyRule \n" + " when \n"
+ " Class ( ) or Class ( name ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_INSIDE_CONDITION_OPERATOR,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_INSIDE_CONDITION_ARGUMENT30() {
String input = "rule MyRule \n" + " when \n"
+ " Class ( ) or Class ( name == ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_INSIDE_CONDITION_ARGUMENT,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_EGIN_OF_CONDITION_NOT() {
String input = "rule MyRule \n" + " when \n"
+ " exists Class ( ) or not ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_BEGIN_OF_CONDITION_NOT,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_BEGIN_OF_CONDITION_EXISTS40() {
String input = "rule MyRule \n" + " when \n"
+ " exists Class ( ) or exists ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_BEGIN_OF_CONDITION_EXISTS,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
/** EVAL */
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_INSIDE_EVAL1() {
String input = "rule MyRule \n" + " when \n" + " eval ( ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_INSIDE_EVAL,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_INSIDE_EVAL2() {
String input = "rule MyRule \n" + " when \n" + " eval(";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_INSIDE_EVAL,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_INSIDE_EVAL3() {
String input = "rule MyRule \n" + " when \n" + " eval( myCla";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_INSIDE_EVAL,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_INSIDE_EVAL4() {
String input = "rule MyRule \n" + " when \n" + " eval( param.getMetho";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_INSIDE_EVAL,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_INSIDE_EVAL5() {
String input = "rule MyRule \n" + " when \n"
+ " eval( param.getMethod(";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_INSIDE_EVAL,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_INSIDE_EVAL6() {
String input = "rule MyRule \n" + " when \n"
+ " eval( param.getMethod().get";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_INSIDE_EVAL,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_INSIDE_EVAL7() {
String input = "rule MyRule \n" + " when \n"
+ " eval( param.getMethod(\"someStringWith)))\").get";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_INSIDE_EVAL,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_INSIDE_EVAL8() {
String input = "rule MyRule \n" + " when \n"
+ " eval( param.getMethod(\"someStringWith(((\").get";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_INSIDE_EVAL,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_INSIDE_EVAL9() {
String input = "rule MyRule \n" + " when \n" + " eval( true )";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_BEGIN_OF_CONDITION,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_BEGIN_OF_CONDITION50() {
String input = "rule MyRule \n" + " when \n"
+ " eval( param.getProperty(name).isTrue() )";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_BEGIN_OF_CONDITION,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_BEGIN_OF_CONDITION51() {
String input = "rule MyRule \n" + " when \n"
+ " eval( param.getProperty(\"someStringWith(((\").isTrue() )";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_BEGIN_OF_CONDITION,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_INSIDE_EVAL10() {
String input = "rule MyRule \n" + " when \n"
+ " eval( param.getProperty((((String) s) )";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_INSIDE_EVAL,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_BEGIN_OF_CONDITION52() {
String input = "rule MyRule \n" + " when \n"
+ " eval( param.getProperty((((String) s))))";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_BEGIN_OF_CONDITION,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_BEGIN_OF_CONDITION53() {
String input = "rule MyRule \n" + " when \n" + " eval( true ) \n"
+ " ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_BEGIN_OF_CONDITION,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
/** MULTIPLE RESTRICTIONS */
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_INSIDE_CONDITION_OPERATOR12() {
String input = "rule MyRule \n" + " when \n"
+ " Class ( property > 0 && ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_INSIDE_CONDITION_OPERATOR,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_INSIDE_CONDITION_OPERATOR13() {
String input = "rule MyRule \n" + " when \n"
+ " Class ( name : property1, property2 > 0 && ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_INSIDE_CONDITION_OPERATOR,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_INSIDE_CONDITION_OPERATOR14() {
String input = "rule MyRule \n" + " when \n"
+ " Class ( property1 < 20, property2 > 0 && ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_INSIDE_CONDITION_OPERATOR,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_INSIDE_CONDITION_ARGUMENT20() {
String input = "rule MyRule \n" + " when \n"
+ " Class ( property > 0 && < ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_INSIDE_CONDITION_ARGUMENT,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_INSIDE_CONDITION_END6() {
String input = "rule MyRule \n" + " when \n"
+ " Class ( property > 0 && < 10 ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_INSIDE_CONDITION_END,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_INSIDE_CONDITION_START41() {
String input = "rule MyRule \n" + " when \n"
+ " Class ( property > 0 && < 10, ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_INSIDE_CONDITION_START,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_INSIDE_CONDITION_OPERATOR60() {
String input = "rule MyRule \n" + " when \n"
+ " Class ( property > 0 || ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_INSIDE_CONDITION_OPERATOR,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_INSIDE_CONDITION_OPERATOR61() {
String input = "rule MyRule \n" + " when \n"
+ " Class ( property > 0 && \n" + " ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_INSIDE_CONDITION_OPERATOR,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_INSIDE_CONDITION_OPERATOR62() {
String input = "rule MyRule \n" + " when \n"
+ " Class ( name : property1, property2 > 0 || ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_INSIDE_CONDITION_OPERATOR,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_INSIDE_CONDITION_OPERATOR63() {
String input = "rule MyRule \n" + " when \n"
+ " Class ( property1 < 20, property2 > 0 || ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_INSIDE_CONDITION_OPERATOR,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_INSIDE_CONDITION_END10() {
String input = "rule MyRule \n" + " when \n"
+ " Class ( property > 0 ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_INSIDE_CONDITION_END,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_INSIDE_CONDITION_END11() {
String input = "rule MyRule \n" + " when \n"
+ " Class ( property > 0 \n" + " ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_INSIDE_CONDITION_END,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_INSIDE_CONDITION_END12() {
String input = "rule MyRule \n" + " when \n"
+ " Class ( property > 0 && < 10 ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_INSIDE_CONDITION_END,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_INSIDE_CONDITION_END13() {
String input = "rule MyRule \n" + " when \n"
+ " Class ( property > 0 || < 10 ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_INSIDE_CONDITION_END,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_INSIDE_CONDITION_END14() {
String input = "rule MyRule \n" + " when \n"
+ " Class ( property == \"test\" || == \"test2\" ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_INSIDE_CONDITION_END,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
/** FROM */
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_BEGIN_OF_CONDITION60() {
String input = "rule MyRule \n" + " when \n"
+ " Class ( property > 0 ) ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_BEGIN_OF_CONDITION,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_BEGIN_OF_CONDITION61() {
String input = "rule MyRule \n" + " when \n"
+ " Class ( property > 0 ) fr";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_BEGIN_OF_CONDITION,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_FROM1() {
String input = "rule MyRule \n" + " when \n"
+ " Class ( property > 0 ) from ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_FROM, getLastIntegerValue(parser
.getEditorInterface().get(0).getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_FROM2() {
String input = "rule MyRule \n" + " when \n"
+ " Class ( property > 0 ) from myGlob";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_FROM, getLastIntegerValue(parser
.getEditorInterface().get(0).getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_FROM3() {
String input = "rule MyRule \n" + " when \n"
+ " Class ( property > 0 ) from myGlobal.get";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_FROM, getLastIntegerValue(parser
.getEditorInterface().get(0).getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_BEGIN_OF_CONDITION75() {
String input = "rule MyRule \n" + " when \n"
+ " Class ( property > 0 ) from myGlobal.getList() \n"
+ " ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_BEGIN_OF_CONDITION,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_BEGIN_OF_CONDITION71() {
String input = "rule MyRule \n" + " when \n"
+ " Class ( property > 0 ) from getDroolsFunction() \n"
+ " ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_BEGIN_OF_CONDITION,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
/** FROM ACCUMULATE */
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_FROM_ACCUMULATE1() {
String input = "rule MyRule \n" + " when \n"
+ " Class ( property > 0 ) from accumulate ( ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_FROM_ACCUMULATE,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_FROM_ACCUMULATE2() {
String input = "rule MyRule \n" + " when \n"
+ " Class ( property > 0 ) from accumulate(";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_FROM_ACCUMULATE,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_BEGIN_OF_CONDITION73() {
String input = "rule MyRule \n" + " when \n"
+ " Class ( property > 0 ) from accumulate( \n"
+ " $cheese : Cheese( type == $likes ), \n"
+ " init( int total = 0; ), \n"
+ " action( total += $cheese.getPrice(); ), \n"
+ " result( new Integer( total ) ) \n" + " ) \n"
+ " ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_BEGIN_OF_CONDITION,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_FROM_ACCUMULATE_INIT_INSIDE() {
String input = "rule MyRule \n" + " when \n"
+ " Class ( property > 0 ) from accumulate( \n"
+ " $cheese : Cheese( type == $likes ), \n" + " init( ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_FROM_ACCUMULATE_INIT_INSIDE,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_FROM_ACCUMULATE_ACTION_INSIDE() {
String input = "rule MyRule \n" + " when \n"
+ " Class ( property > 0 ) from accumulate( \n"
+ " $cheese : Cheese( type == $likes ), \n"
+ " init( int total = 0; ), \n" + " action( ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_FROM_ACCUMULATE_ACTION_INSIDE,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_FROM_ACCUMULATE_ACTION_INSIDE3() {
String input = "rule MyRule \n" + " when \n"
+ " Class ( property > 0 ) from accumulate( \n"
+ " $cheese : Cheese( type == $likes ), \n"
+ " init( int total = 0; ), \n" + " action( ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_FROM_ACCUMULATE_ACTION_INSIDE,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_FROM_ACCUMULATE_RESULT_INSIDE() {
String input = "rule MyRule \n" + " when \n"
+ " Class ( property > 0 ) from accumulate( \n"
+ " $cheese : Cheese( type == $likes ), \n"
+ " init( int total = 0; ), \n"
+ " action( total += $cheese.getPrice(); ), \n"
+ " result( ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_FROM_ACCUMULATE_RESULT_INSIDE,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_FROM_ACCUMULATE_INIT_INSIDE2() {
String input = "rule MyRule \n" + " when \n"
+ " Class ( property > 0 ) from accumulate( \n"
+ " $cheese : Cheese( type == $likes ), \n"
+ " init( int total =";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_FROM_ACCUMULATE_INIT_INSIDE,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_FROM_ACCUMULATE_ACTION_INSIDE2() {
String input = "rule MyRule \n" + " when \n"
+ " Class ( property > 0 ) from accumulate( \n"
+ " $cheese : Cheese( type == $likes ), \n"
+ " init( int total = 0; ), \n" + " action( total += $ch";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_FROM_ACCUMULATE_ACTION_INSIDE,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_FROM_ACCUMULATE_RESULT_INSIDE2() {
String input = "rule MyRule \n" + " when \n"
+ " Class ( property > 0 ) from accumulate( \n"
+ " $cheese : Cheese( type == $likes ), \n"
+ " init( int total = 0; ), \n"
+ " action( total += $cheese.getPrice(); ), \n"
+ " result( new Integer( tot";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_FROM_ACCUMULATE_RESULT_INSIDE,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_INSIDE_CONDITION_START() {
String input = "rule MyRule \n" + " when \n"
+ " Class ( property > 0 ) from accumulate( \n"
+ " $cheese : Cheese( ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_INSIDE_CONDITION_START,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_INSIDE_CONDITION_OPERATOR40() {
String input = "rule MyRule \n" + " when \n"
+ " Class ( property > 0 ) from accumulate( \n"
+ " $cheese : Cheese( type ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_INSIDE_CONDITION_OPERATOR,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_INSIDE_CONDITION_ARGUMENT() {
String input = "rule MyRule \n" + " when \n"
+ " Class ( property > 0 ) from accumulate( \n"
+ " $cheese : Cheese( type == ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_INSIDE_CONDITION_ARGUMENT,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
/** FROM COLLECT */
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_FROM_COLLECT1() {
String input = "rule MyRule \n" + " when \n"
+ " Class ( property > 0 ) from collect ( ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_FROM_COLLECT,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_FROM_COLLECT2() {
String input = "rule MyRule \n" + " when \n"
+ " Class ( property > 0 ) from collect(";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_FROM_COLLECT,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_BEGIN_OF_CONDITION67() {
String input = "rule MyRule \n" + " when \n"
+ " Class ( property > 0 ) from collect ( \n"
+ " Cheese( type == $likes )" + " ) \n" + " ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_BEGIN_OF_CONDITION,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_INSIDE_CONDITION_START31() {
String input = "rule MyRule \n" + " when \n"
+ " Class ( property > 0 ) from collect ( \n" + " Cheese( ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_INSIDE_CONDITION_START,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_INSIDE_CONDITION_OPERATOR31() {
String input = "rule MyRule \n" + " when \n"
+ " Class ( property > 0 ) from collect ( \n"
+ " Cheese( type ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_INSIDE_CONDITION_OPERATOR,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_INSIDE_CONDITION_ARGUMENT21() {
String input = "rule MyRule \n" + " when \n"
+ " Class ( property > 0 ) from collect ( \n"
+ " Cheese( type == ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_INSIDE_CONDITION_ARGUMENT,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
/** NESTED FROM */
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_BEGIN_OF_CONDITION68() {
String input = "rule MyRule \n"
+ " when \n"
+ " ArrayList(size > 50) from collect( Person( disabled == \"yes\", income > 100000 ) ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_BEGIN_OF_CONDITION,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_FROM5() {
String input = "rule MyRule \n"
+ " when \n"
+ " ArrayList(size > 50) from collect( Person( disabled == \"yes\", income > 100000 ) from ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_FROM, getLastIntegerValue(parser
.getEditorInterface().get(0).getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_BEGIN_OF_CONDITION69() {
String input = "rule MyRule \n"
+ " when \n"
+ " ArrayList(size > 50) from collect( Person( disabled == \"yes\", income > 100000 ) from town.getPersons() )";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_BEGIN_OF_CONDITION,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_BEGIN_OF_CONDITION70() {
String input = "rule MyRule \n"
+ " when \n"
+ " ArrayList(size > 50) from accumulate( Person( disabled == \"yes\", income > 100000 ) ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_BEGIN_OF_CONDITION,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_FROM6() {
String input = "rule MyRule \n"
+ " when \n"
+ " ArrayList(size > 50) from accumulate( Person( disabled == \"yes\", income > 100000 ) from ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_FROM, getLastIntegerValue(parser
.getEditorInterface().get(0).getContent()));
}
/** FORALL */
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_BEGIN_OF_CONDITION81() {
String input = "rule MyRule \n" + " when \n" + " forall ( ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_BEGIN_OF_CONDITION,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_INSIDE_CONDITION_START32() {
String input = "rule MyRule \n" + " when \n" + " forall ( "
+ " Class ( pr";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_INSIDE_CONDITION_START,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_INSIDE_CONDITION_OPERATOR32() {
String input = "rule MyRule \n" + " when \n" + " forall ( "
+ " Class ( property ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_INSIDE_CONDITION_OPERATOR,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_INSIDE_CONDITION_ARGUMENT22() {
String input = "rule MyRule \n" + " when \n" + " forall ( "
+ " Class ( property == ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_INSIDE_CONDITION_ARGUMENT,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_BEGIN_OF_CONDITION76() {
String input = "rule MyRule \n" + " when \n" + " forall ( "
+ " Class ( property == \"test\")" + " C";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_BEGIN_OF_CONDITION,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_BEGIN_OF_CONDITION77a() {
String input = "rule MyRule \n"
+ " when \n"
+ " ArrayList(size > 50) from accumulate( Person( disabled == \"yes\", income > 100000 ) from town.getPersons() ) ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_BEGIN_OF_CONDITION,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_BEGIN_OF_CONDITION77b() {
String input = "rule MyRule \n"
+ " when \n"
+ " ArrayList(size > 50) from accumulate( Person( disabled == \"yes\", income > 100000 ) from town.getPersons() )";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_BEGIN_OF_CONDITION,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_INSIDE_CONDITION_START45a() {
String input = "rule MyRule \n" + " when \n"
+ " Class ( name :";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_INSIDE_CONDITION_START,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckLHSLocationDetermination_INSIDE_CONDITION_START45b() {
String input = "rule MyRule \n" + " when \n"
+ " Class ( name : ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_INSIDE_CONDITION_START,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckRHSLocationDetermination_firstLineOfLHS() {
String input = "rule MyRule \n" + " when\n" + " Class ( )\n"
+ " then\n" + " ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_RHS, getLastIntegerValue(parser
.getEditorInterface().get(0).getContent()));
}
@Test(timeout=10*1000)
public void testCheckRHSLocationDetermination_startOfNewlINE() {
String input = "rule MyRule \n" + " when\n" + " Class ( )\n"
+ " then\n" + " assert(null);\n" + " ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_RHS, getLastIntegerValue(parser
.getEditorInterface().get(0).getContent()));
}
@Test(timeout=10*1000)
public void testCheckRHSLocationDetermination3() {
String input = "rule MyRule \n" + " when\n" + " Class ( )\n"
+ " then\n" + " meth";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_RHS, getLastIntegerValue(parser
.getEditorInterface().get(0).getContent()));
Object lastElement = parser.getEditorInterface().get(0).getContent().getLast();
assertTrue(lastElement instanceof Token);
final Token lastToken = (Token) lastElement;
assertEquals("meth", lastToken.getText());
}
@Test(timeout=10*1000)
public void testCheckRuleHeaderLocationDetermination() {
String input = "rule MyRule ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_RULE_HEADER, getLastIntegerValue(parser
.getEditorInterface().get(0).getContent()));
}
@Test(timeout=10*1000)
public void testCheckRuleHeaderLocationDetermination2() {
String input = "rule MyRule \n" + " salience 12 activation-group \"my";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
DroolsToken token = getLastTokenOnList(parser.getEditorInterface().get(
0).getContent());
assertEquals("group", token.getText().toLowerCase());
assertEquals(DroolsEditorType.KEYWORD, token.getEditorType());
assertEquals(Location.LOCATION_RULE_HEADER_KEYWORD,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckRuleHeaderLocationDetermination3() {
String input = "rule \"Hello World\" ruleflow-group \"hello\" s";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_RULE_HEADER, getLastIntegerValue(parser
.getEditorInterface().get(0).getContent()));
}
@Test(timeout=10*1000)
public void testCheckRuleHeaderLocationDetermination_dialect1() {
String input = "rule MyRule \n" + " dialect \"java\"";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_RULE_HEADER, getLastIntegerValue(parser
.getEditorInterface().get(0).getContent()));
}
@Test(timeout=10*1000)
public void testCheckRuleHeaderLocationDetermination_dialect2() {
String input = "rule MyRule \n" + " dialect \"mvel\"";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_RULE_HEADER, getLastIntegerValue(parser
.getEditorInterface().get(0).getContent()));
}
@Test(timeout=10*1000)
public void testCheckRuleHeaderLocationDetermination_dialect3() {
String input = "rule MyRule \n" + " dialect ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
DroolsToken token = getLastTokenOnList(parser.getEditorInterface().get(
0).getContent());
assertEquals("dialect", token.getText().toLowerCase());
assertEquals(DroolsEditorType.KEYWORD, token.getEditorType());
assertEquals(Location.LOCATION_RULE_HEADER_KEYWORD,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckRuleHeaderLocationDetermination_dialect4() {
String input = "rule MyRule \n" + " dialect \"";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
DroolsToken token = getLastTokenOnList(parser.getEditorInterface().get(
0).getContent());
assertEquals("dialect", token.getText().toLowerCase());
assertEquals(DroolsEditorType.KEYWORD, token.getEditorType());
assertEquals(Location.LOCATION_RULE_HEADER_KEYWORD,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
// TODO: add tests for dialect defined at package header level
@Test(timeout=10*1000)
public void testCheckQueryLocationDetermination_RULE_HEADER1() {
String input = "query MyQuery ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_RULE_HEADER, getLastIntegerValue(parser
.getEditorInterface().get(0).getContent()));
}
@Test(timeout=10*1000)
public void testCheckQueryLocationDetermination_RULE_HEADER2() {
String input = "query \"MyQuery\" ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_RULE_HEADER, getLastIntegerValue(parser
.getEditorInterface().get(0).getContent()));
}
@Test(timeout=10*1000)
public void testCheckQueryLocationDetermination_LHS_BEGIN_OF_CONDITION() {
String input = "query MyQuery() ";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_BEGIN_OF_CONDITION,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testCheckQueryLocationDetermination_LHS_INSIDE_CONDITION_START() {
String input = "query MyQuery \n" + " Class (";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_INSIDE_CONDITION_START,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@Test(timeout=10*1000)
public void testRuleParameters_PATTERN_1() {
String input =
"rule MyRule \n" +
" when \n" +
" c: Class (";
DRLParser parser = getParser(input);
parser.enableEditorInterface();
try {
parser.compilationUnit();
} catch (Exception ex) {
}
assertEquals(Location.LOCATION_LHS_INSIDE_CONDITION_START,
getLastIntegerValue(parser.getEditorInterface().get(0)
.getContent()));
}
@SuppressWarnings("unchecked")
private int getLastIntegerValue(LinkedList list) {
//System.out.println(list.toString());
int lastIntergerValue = -1;
for (Object object : list) {
if (object instanceof Integer) {
lastIntergerValue = (Integer) object;
}
}
return lastIntergerValue;
}
@SuppressWarnings("unchecked")
private DroolsToken getLastTokenOnList(LinkedList list) {
DroolsToken lastToken = null;
for (Object object : list) {
if (object instanceof DroolsToken) {
lastToken = (DroolsToken) object;
}
}
return lastToken;
}
/**
* @return An instance of a RuleParser should you need one (most folks will
* not).
*/
private DRLParser getParser(final String text) {
return buildParser(text, LanguageLevelOption.DRL5);
}
}
| apache-2.0 |
hgschmie/presto | presto-main/src/test/java/io/prestosql/sql/planner/assertions/CorrelationMatcher.java | 3015 | /*
* 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.prestosql.sql.planner.assertions;
import io.prestosql.Session;
import io.prestosql.cost.StatsProvider;
import io.prestosql.metadata.Metadata;
import io.prestosql.sql.planner.Symbol;
import io.prestosql.sql.planner.plan.ApplyNode;
import io.prestosql.sql.planner.plan.CorrelatedJoinNode;
import io.prestosql.sql.planner.plan.PlanNode;
import java.util.List;
import static com.google.common.base.MoreObjects.toStringHelper;
import static com.google.common.base.Preconditions.checkState;
import static io.prestosql.sql.planner.assertions.MatchResult.NO_MATCH;
import static io.prestosql.sql.planner.assertions.MatchResult.match;
import static java.util.Objects.requireNonNull;
public class CorrelationMatcher
implements Matcher
{
private final List<String> correlation;
CorrelationMatcher(List<String> correlation)
{
this.correlation = requireNonNull(correlation, "correlation is null");
}
@Override
public boolean shapeMatches(PlanNode node)
{
return node instanceof ApplyNode || node instanceof CorrelatedJoinNode;
}
@Override
public MatchResult detailMatches(PlanNode node, StatsProvider stats, Session session, Metadata metadata, SymbolAliases symbolAliases)
{
checkState(
shapeMatches(node),
"Plan testing framework error: shapeMatches returned false in detailMatches in %s",
this.getClass().getName());
List<Symbol> actualCorrelation = getCorrelation(node);
if (this.correlation.size() != actualCorrelation.size()) {
return NO_MATCH;
}
int i = 0;
for (String alias : this.correlation) {
if (!symbolAliases.get(alias).equals(actualCorrelation.get(i++).toSymbolReference())) {
return NO_MATCH;
}
}
return match();
}
private List<Symbol> getCorrelation(PlanNode node)
{
if (node instanceof ApplyNode) {
return ((ApplyNode) node).getCorrelation();
}
else if (node instanceof CorrelatedJoinNode) {
return ((CorrelatedJoinNode) node).getCorrelation();
}
else {
throw new IllegalStateException("Unexpected plan node: " + node);
}
}
@Override
public String toString()
{
return toStringHelper(this)
.add("correlation", correlation)
.toString();
}
}
| apache-2.0 |
andreagenso/java2scala | test/J2s/java/openjdk-6-src-b27/jdk/src/share/classes/sun/text/resources/FormatData_fr_CA.java | 3005 | /*
* Copyright (c) 1996, 2005, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* (C) Copyright Taligent, Inc. 1996, 1997 - All Rights Reserved
* (C) Copyright IBM Corp. 1996 - 1998 - All Rights Reserved
*
* The original version of this source code and documentation
* is copyrighted and owned by Taligent, Inc., a wholly-owned
* subsidiary of IBM. These materials are provided under terms
* of a License Agreement between Taligent and Sun. This technology
* is protected by multiple US and International patents.
*
* This notice and attribution to Taligent may not be removed.
* Taligent is a registered trademark of Taligent, Inc.
*
*/
package sun.text.resources;
import java.util.ListResourceBundle;
public class FormatData_fr_CA extends ListResourceBundle {
/**
* Overrides ListResourceBundle
*/
protected final Object[][] getContents() {
return new Object[][] {
{ "NumberPatterns",
new String[] {
"#,##0.###;-#,##0.###", // decimal pattern
"#,##0.00 \u00A4;(#,##0.00\u00A4)", // currency pattern
"#,##0 %" // percent pattern
}
},
{ "DateTimePatterns",
new String[] {
"H' h 'mm z", // full time pattern
"HH:mm:ss z", // long time pattern
"HH:mm:ss", // medium time pattern
"HH:mm", // short time pattern
"EEEE d MMMM yyyy", // full date pattern
"d MMMM yyyy", // long date pattern
"yyyy-MM-dd", // medium date pattern
"yy-MM-dd", // short date pattern
"{1} {0}" // date-time pattern
}
},
{ "DateTimePatternChars", "GaMjkHmsSEDFwWxhKzZ" },
};
}
}
| apache-2.0 |
facebook/presto | presto-spark-base/src/main/java/com/facebook/presto/spark/RddAndMore.java | 2598 | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.spark;
import com.facebook.presto.spark.classloader_interface.MutablePartitionId;
import com.facebook.presto.spark.classloader_interface.PrestoSparkTaskOutput;
import com.google.common.collect.ImmutableList;
import org.apache.spark.SparkException;
import org.apache.spark.api.java.JavaPairRDD;
import scala.Tuple2;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import static com.facebook.presto.spark.util.PrestoSparkUtils.getActionResultWithTimeout;
import static com.google.common.base.Preconditions.checkState;
import static java.util.Objects.requireNonNull;
public class RddAndMore<T extends PrestoSparkTaskOutput>
{
private final JavaPairRDD<MutablePartitionId, T> rdd;
private final List<PrestoSparkBroadcastDependency<?>> broadcastDependencies;
private boolean collected;
public RddAndMore(
JavaPairRDD<MutablePartitionId, T> rdd,
List<PrestoSparkBroadcastDependency<?>> broadcastDependencies)
{
this.rdd = requireNonNull(rdd, "rdd is null");
this.broadcastDependencies = ImmutableList.copyOf(requireNonNull(broadcastDependencies, "broadcastDependencies is null"));
}
public List<Tuple2<MutablePartitionId, T>> collectAndDestroyDependenciesWithTimeout(long timeout, TimeUnit timeUnit, Set<PrestoSparkServiceWaitTimeMetrics> waitTimeMetrics)
throws SparkException, TimeoutException
{
checkState(!collected, "already collected");
collected = true;
List<Tuple2<MutablePartitionId, T>> result = getActionResultWithTimeout(rdd.collectAsync(), timeout, timeUnit, waitTimeMetrics);
broadcastDependencies.forEach(PrestoSparkBroadcastDependency::destroy);
return result;
}
public JavaPairRDD<MutablePartitionId, T> getRdd()
{
return rdd;
}
public List<PrestoSparkBroadcastDependency<?>> getBroadcastDependencies()
{
return broadcastDependencies;
}
}
| apache-2.0 |
s12345sk/paoding-rose | paoding-rose-load/src/main/java/net/paoding/rose/load/vfs/FileContent.java | 904 | /*
* Copyright 2007-2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.paoding.rose.load.vfs;
import java.io.IOException;
import java.io.InputStream;
/**
*
* @author 王志亮 [qieqie.wang@gmail.com]
*
*/
public interface FileContent {
public InputStream getInputStream() throws IOException;
}
| apache-2.0 |
afinka77/ignite | modules/core/src/main/java/org/apache/ignite/internal/processors/cache/local/GridLocalCache.java | 7998 | /*
* 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.ignite.internal.processors.cache.local;
import java.io.Externalizable;
import java.util.Collection;
import java.util.concurrent.Callable;
import org.apache.ignite.IgniteCheckedException;
import org.apache.ignite.internal.IgniteInternalFuture;
import org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion;
import org.apache.ignite.internal.processors.cache.CacheEntryPredicate;
import org.apache.ignite.internal.processors.cache.CacheObject;
import org.apache.ignite.internal.processors.cache.GridCacheAdapter;
import org.apache.ignite.internal.processors.cache.GridCacheContext;
import org.apache.ignite.internal.processors.cache.GridCacheEntryEx;
import org.apache.ignite.internal.processors.cache.GridCacheEntryRemovedException;
import org.apache.ignite.internal.processors.cache.GridCacheMapEntry;
import org.apache.ignite.internal.processors.cache.GridCacheMapEntryFactory;
import org.apache.ignite.internal.processors.cache.GridCacheMvccCandidate;
import org.apache.ignite.internal.processors.cache.GridCachePreloader;
import org.apache.ignite.internal.processors.cache.GridCachePreloaderAdapter;
import org.apache.ignite.internal.processors.cache.KeyCacheObject;
import org.apache.ignite.internal.processors.cache.transactions.IgniteTxLocalEx;
import org.apache.ignite.internal.processors.cache.version.GridCacheVersion;
import org.apache.ignite.internal.util.future.GridFinishedFuture;
import org.apache.ignite.internal.util.typedef.F;
import org.apache.ignite.internal.util.typedef.internal.CU;
import org.apache.ignite.transactions.TransactionIsolation;
import org.jetbrains.annotations.Nullable;
/**
* Local cache implementation.
*/
public class GridLocalCache<K, V> extends GridCacheAdapter<K, V> {
/** */
private static final long serialVersionUID = 0L;
/** */
private GridCachePreloader preldr;
/**
* Empty constructor required by {@link Externalizable}.
*/
public GridLocalCache() {
// No-op.
}
/**
* @param ctx Cache registry.
*/
public GridLocalCache(GridCacheContext<K, V> ctx) {
super(ctx, ctx.config().getStartSize());
preldr = new GridCachePreloaderAdapter(ctx);
}
/** {@inheritDoc} */
@Override public boolean isLocal() {
return true;
}
/** {@inheritDoc} */
@Override public GridCachePreloader preloader() {
return preldr;
}
/** {@inheritDoc} */
@Override protected GridCacheMapEntryFactory entryFactory() {
return new GridCacheMapEntryFactory() {
@Override public GridCacheMapEntry create(
GridCacheContext ctx,
AffinityTopologyVersion topVer,
KeyCacheObject key,
int hash,
CacheObject val
) {
return new GridLocalCacheEntry(ctx, key, hash, val);
}
};
}
/**
* @param key Key of entry.
* @return Cache entry.
*/
@Nullable GridLocalCacheEntry peekExx(KeyCacheObject key) {
return (GridLocalCacheEntry)peekEx(key);
}
/**
* @param key Key of entry.
* @return Cache entry.
*/
GridLocalCacheEntry entryExx(KeyCacheObject key) {
return (GridLocalCacheEntry)entryEx(key);
}
/** {@inheritDoc} */
@Override public IgniteInternalFuture<Boolean> txLockAsync(Collection<KeyCacheObject> keys,
long timeout,
IgniteTxLocalEx tx,
boolean isRead,
boolean retval,
TransactionIsolation isolation,
boolean invalidate,
long createTtl,
long accessTtl) {
return lockAllAsync(keys, timeout, tx, CU.empty0());
}
/** {@inheritDoc} */
@Override public IgniteInternalFuture<Boolean> lockAllAsync(Collection<? extends K> keys, long timeout) {
IgniteTxLocalEx tx = ctx.tm().localTx();
return lockAllAsync(ctx.cacheKeysView(keys), timeout, tx, CU.empty0());
}
/**
* @param keys Keys.
* @param timeout Timeout.
* @param tx Transaction.
* @param filter Filter.
* @return Future.
*/
public IgniteInternalFuture<Boolean> lockAllAsync(Collection<KeyCacheObject> keys,
long timeout,
@Nullable IgniteTxLocalEx tx,
CacheEntryPredicate[] filter) {
if (F.isEmpty(keys))
return new GridFinishedFuture<>(true);
GridLocalLockFuture<K, V> fut = new GridLocalLockFuture<>(ctx, keys, tx, this, timeout, filter);
try {
for (KeyCacheObject key : keys) {
while (true) {
GridLocalCacheEntry entry = null;
try {
entry = entryExx(key);
entry.unswap(false);
if (!ctx.isAll(entry, filter)) {
fut.onFailed();
return fut;
}
// Removed exception may be thrown here.
GridCacheMvccCandidate cand = fut.addEntry(entry);
if (cand == null && fut.isDone())
return fut;
break;
}
catch (GridCacheEntryRemovedException ignored) {
if (log().isDebugEnabled())
log().debug("Got removed entry in lockAsync(..) method (will retry): " + entry);
}
}
}
if (!ctx.mvcc().addFuture(fut))
fut.onError(new IgniteCheckedException("Duplicate future ID (internal error): " + fut));
// Must have future added prior to checking locks.
fut.checkLocks();
return fut;
}
catch (IgniteCheckedException e) {
fut.onError(e);
return fut;
}
}
/** {@inheritDoc} */
@Override public void unlockAll(
Collection<? extends K> keys
) throws IgniteCheckedException {
AffinityTopologyVersion topVer = ctx.affinity().affinityTopologyVersion();
for (K key : keys) {
GridLocalCacheEntry entry = peekExx(ctx.toCacheKeyObject(key));
if (entry != null && ctx.isAll(entry, CU.empty0())) {
entry.releaseLocal();
ctx.evicts().touch(entry, topVer);
}
}
}
/** {@inheritDoc} */
@Override public IgniteInternalFuture<?> removeAllAsync() {
return ctx.closures().callLocalSafe(new Callable<Void>() {
@Override public Void call() throws Exception {
removeAll();
return null;
}
});
}
/** {@inheritDoc} */
@Override public void onDeferredDelete(GridCacheEntryEx entry, GridCacheVersion ver) {
assert false : "Should not be called";
}
/**
* @param fut Clears future from cache.
*/
void onFutureDone(GridLocalLockFuture fut) {
if (ctx.mvcc().removeMvccFuture(fut)) {
if (log().isDebugEnabled())
log().debug("Explicitly removed future from map of futures: " + fut);
}
}
}
| apache-2.0 |
christophd/camel | dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/Aws2AthenaComponentBuilderFactory.java | 26377 | /*
* 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.builder.component.dsl;
import javax.annotation.Generated;
import org.apache.camel.Component;
import org.apache.camel.builder.component.AbstractComponentBuilder;
import org.apache.camel.builder.component.ComponentBuilder;
import org.apache.camel.component.aws2.athena.Athena2Component;
/**
* Access AWS Athena service using AWS SDK version 2.x.
*
* Generated by camel-package-maven-plugin - do not edit this file!
*/
@Generated("org.apache.camel.maven.packaging.ComponentDslMojo")
public interface Aws2AthenaComponentBuilderFactory {
/**
* AWS Athena (camel-aws2-athena)
* Access AWS Athena service using AWS SDK version 2.x.
*
* Category: cloud,database
* Since: 3.4
* Maven coordinates: org.apache.camel:camel-aws2-athena
*
* @return the dsl builder
*/
static Aws2AthenaComponentBuilder aws2Athena() {
return new Aws2AthenaComponentBuilderImpl();
}
/**
* Builder for the AWS Athena component.
*/
interface Aws2AthenaComponentBuilder
extends
ComponentBuilder<Athena2Component> {
/**
* Amazon AWS Access Key.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: producer
*
* @param accessKey the value to set
* @return the dsl builder
*/
default Aws2AthenaComponentBuilder accessKey(java.lang.String accessKey) {
doSetProperty("accessKey", accessKey);
return this;
}
/**
* The AmazonAthena instance to use as the client.
*
* The option is a:
* <code>software.amazon.awssdk.services.athena.AthenaClient</code> type.
*
* Group: producer
*
* @param amazonAthenaClient the value to set
* @return the dsl builder
*/
default Aws2AthenaComponentBuilder amazonAthenaClient(
software.amazon.awssdk.services.athena.AthenaClient amazonAthenaClient) {
doSetProperty("amazonAthenaClient", amazonAthenaClient);
return this;
}
/**
* The component configuration.
*
* The option is a:
* <code>org.apache.camel.component.aws2.athena.Athena2Configuration</code> type.
*
* Group: producer
*
* @param configuration the value to set
* @return the dsl builder
*/
default Aws2AthenaComponentBuilder configuration(
org.apache.camel.component.aws2.athena.Athena2Configuration configuration) {
doSetProperty("configuration", configuration);
return this;
}
/**
* The Athena database to use.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: producer
*
* @param database the value to set
* @return the dsl builder
*/
default Aws2AthenaComponentBuilder database(java.lang.String database) {
doSetProperty("database", database);
return this;
}
/**
* Milliseconds before the next poll for query execution status. See the
* section 'Waiting for Query Completion and Retrying Failed Queries' to
* learn more.
*
* The option is a: <code>long</code> type.
*
* Default: 2000
* Group: producer
*
* @param delay the value to set
* @return the dsl builder
*/
default Aws2AthenaComponentBuilder delay(long delay) {
doSetProperty("delay", delay);
return this;
}
/**
* The encryption type to use when storing query results in S3. One of
* SSE_S3, SSE_KMS, or CSE_KMS.
*
* The option is a:
* <code>software.amazon.awssdk.services.athena.model.EncryptionOption</code> type.
*
* Group: producer
*
* @param encryptionOption the value to set
* @return the dsl builder
*/
default Aws2AthenaComponentBuilder encryptionOption(
software.amazon.awssdk.services.athena.model.EncryptionOption encryptionOption) {
doSetProperty("encryptionOption", encryptionOption);
return this;
}
/**
* Include useful trace information at the beginning of queries as an
* SQL comment (prefixed with --).
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: producer
*
* @param includeTrace the value to set
* @return the dsl builder
*/
default Aws2AthenaComponentBuilder includeTrace(boolean includeTrace) {
doSetProperty("includeTrace", includeTrace);
return this;
}
/**
* Milliseconds before the first poll for query execution status. See
* the section 'Waiting for Query Completion and Retrying Failed
* Queries' to learn more.
*
* The option is a: <code>long</code> type.
*
* Default: 1000
* Group: producer
*
* @param initialDelay the value to set
* @return the dsl builder
*/
default Aws2AthenaComponentBuilder initialDelay(long initialDelay) {
doSetProperty("initialDelay", initialDelay);
return this;
}
/**
* For SSE-KMS and CSE-KMS, this is the KMS key ARN or ID.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: producer
*
* @param kmsKey the value to set
* @return the dsl builder
*/
default Aws2AthenaComponentBuilder kmsKey(java.lang.String kmsKey) {
doSetProperty("kmsKey", kmsKey);
return this;
}
/**
* Whether the producer should be started lazy (on the first message).
* By starting lazy you can use this to allow CamelContext and routes to
* startup in situations where a producer may otherwise fail during
* starting and cause the route to fail being started. By deferring this
* startup to be lazy then the startup failure can be handled during
* routing messages via Camel's routing error handlers. Beware that when
* the first message is processed then creating and starting the
* producer may take a little time and prolong the total processing time
* of the processing.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: producer
*
* @param lazyStartProducer the value to set
* @return the dsl builder
*/
default Aws2AthenaComponentBuilder lazyStartProducer(
boolean lazyStartProducer) {
doSetProperty("lazyStartProducer", lazyStartProducer);
return this;
}
/**
* Maximum number of times to attempt a query. Set to 1 to disable
* retries. See the section 'Waiting for Query Completion and Retrying
* Failed Queries' to learn more.
*
* The option is a: <code>int</code> type.
*
* Default: 1
* Group: producer
*
* @param maxAttempts the value to set
* @return the dsl builder
*/
default Aws2AthenaComponentBuilder maxAttempts(int maxAttempts) {
doSetProperty("maxAttempts", maxAttempts);
return this;
}
/**
* Max number of results to return for the given operation (if supported
* by the Athena API endpoint). If not set, will use the Athena API
* default for the given operation.
*
* The option is a: <code>java.lang.Integer</code> type.
*
* Group: producer
*
* @param maxResults the value to set
* @return the dsl builder
*/
default Aws2AthenaComponentBuilder maxResults(
java.lang.Integer maxResults) {
doSetProperty("maxResults", maxResults);
return this;
}
/**
* Pagination token to use in the case where the response from the
* previous request was truncated.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: producer
*
* @param nextToken the value to set
* @return the dsl builder
*/
default Aws2AthenaComponentBuilder nextToken(java.lang.String nextToken) {
doSetProperty("nextToken", nextToken);
return this;
}
/**
* The Athena API function to call.
*
* The option is a:
* <code>org.apache.camel.component.aws2.athena.Athena2Operations</code> type.
*
* Default: startQueryExecution
* Group: producer
*
* @param operation the value to set
* @return the dsl builder
*/
default Aws2AthenaComponentBuilder operation(
org.apache.camel.component.aws2.athena.Athena2Operations operation) {
doSetProperty("operation", operation);
return this;
}
/**
* The location in Amazon S3 where query results are stored, such as
* s3://path/to/query/bucket/. Ensure this value ends with a forward
* slash ('/').
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: producer
*
* @param outputLocation the value to set
* @return the dsl builder
*/
default Aws2AthenaComponentBuilder outputLocation(
java.lang.String outputLocation) {
doSetProperty("outputLocation", outputLocation);
return this;
}
/**
* How query results should be returned. One of StreamList (default -
* return a GetQueryResultsIterable that can page through all results),
* SelectList (returns at most 1,000 rows at a time, plus a NextToken
* value as a header than can be used for manual pagination of results),
* S3Pointer (return an S3 path pointing to the results).
*
* The option is a:
* <code>org.apache.camel.component.aws2.athena.Athena2OutputType</code> type.
*
* Default: StreamList
* Group: producer
*
* @param outputType the value to set
* @return the dsl builder
*/
default Aws2AthenaComponentBuilder outputType(
org.apache.camel.component.aws2.athena.Athena2OutputType outputType) {
doSetProperty("outputType", outputType);
return this;
}
/**
* To define a proxy host when instantiating the Athena client.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: producer
*
* @param proxyHost the value to set
* @return the dsl builder
*/
default Aws2AthenaComponentBuilder proxyHost(java.lang.String proxyHost) {
doSetProperty("proxyHost", proxyHost);
return this;
}
/**
* To define a proxy port when instantiating the Athena client.
*
* The option is a: <code>java.lang.Integer</code> type.
*
* Group: producer
*
* @param proxyPort the value to set
* @return the dsl builder
*/
default Aws2AthenaComponentBuilder proxyPort(java.lang.Integer proxyPort) {
doSetProperty("proxyPort", proxyPort);
return this;
}
/**
* To define a proxy protocol when instantiating the Athena client.
*
* The option is a:
* <code>software.amazon.awssdk.core.Protocol</code> type.
*
* Default: HTTPS
* Group: producer
*
* @param proxyProtocol the value to set
* @return the dsl builder
*/
default Aws2AthenaComponentBuilder proxyProtocol(
software.amazon.awssdk.core.Protocol proxyProtocol) {
doSetProperty("proxyProtocol", proxyProtocol);
return this;
}
/**
* The unique ID identifying the query execution.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: producer
*
* @param queryExecutionId the value to set
* @return the dsl builder
*/
default Aws2AthenaComponentBuilder queryExecutionId(
java.lang.String queryExecutionId) {
doSetProperty("queryExecutionId", queryExecutionId);
return this;
}
/**
* The SQL query to run. Except for simple queries, prefer setting this
* as the body of the Exchange or as a header using
* Athena2Constants.QUERY_STRING to avoid having to deal with URL
* encoding issues.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: producer
*
* @param queryString the value to set
* @return the dsl builder
*/
default Aws2AthenaComponentBuilder queryString(
java.lang.String queryString) {
doSetProperty("queryString", queryString);
return this;
}
/**
* The region in which Athena client needs to work. When using this
* parameter, the configuration will expect the lowercase name of the
* region (for example ap-east-1). You'll need to use the name
* Region.EU_WEST_1.id().
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: producer
*
* @param region the value to set
* @return the dsl builder
*/
default Aws2AthenaComponentBuilder region(java.lang.String region) {
doSetProperty("region", region);
return this;
}
/**
* Reset the waitTimeout countdown in the event of a query retry. If set
* to true, potential max time spent waiting for queries is equal to
* waitTimeout x maxAttempts. See the section 'Waiting for Query
* Completion and Retrying Failed Queries' to learn more.
*
* The option is a: <code>boolean</code> type.
*
* Default: true
* Group: producer
*
* @param resetWaitTimeoutOnRetry the value to set
* @return the dsl builder
*/
default Aws2AthenaComponentBuilder resetWaitTimeoutOnRetry(
boolean resetWaitTimeoutOnRetry) {
doSetProperty("resetWaitTimeoutOnRetry", resetWaitTimeoutOnRetry);
return this;
}
/**
* Optional comma separated list of error types to retry the query for.
* Use 'retryable' to retry all retryable failure conditions (e.g.
* generic errors and resources exhausted), 'generic' to retry
* 'GENERIC_INTERNAL_ERROR' failures, 'exhausted' to retry queries that
* have exhausted resource limits, 'always' to always retry regardless
* of failure condition, or 'never' or null to never retry (default).
* See the section 'Waiting for Query Completion and Retrying Failed
* Queries' to learn more.
*
* The option is a: <code>java.lang.String</code> type.
*
* Default: never
* Group: producer
*
* @param retry the value to set
* @return the dsl builder
*/
default Aws2AthenaComponentBuilder retry(java.lang.String retry) {
doSetProperty("retry", retry);
return this;
}
/**
* Amazon AWS Secret Key.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: producer
*
* @param secretKey the value to set
* @return the dsl builder
*/
default Aws2AthenaComponentBuilder secretKey(java.lang.String secretKey) {
doSetProperty("secretKey", secretKey);
return this;
}
/**
* Set whether the Athena client should expect to load credentials
* through a default credentials provider or to expect static
* credentials to be passed in.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: producer
*
* @param useDefaultCredentialsProvider the value to set
* @return the dsl builder
*/
default Aws2AthenaComponentBuilder useDefaultCredentialsProvider(
boolean useDefaultCredentialsProvider) {
doSetProperty("useDefaultCredentialsProvider", useDefaultCredentialsProvider);
return this;
}
/**
* Optional max wait time in millis to wait for a successful query
* completion. See the section 'Waiting for Query Completion and
* Retrying Failed Queries' to learn more.
*
* The option is a: <code>long</code> type.
*
* Default: 0
* Group: producer
*
* @param waitTimeout the value to set
* @return the dsl builder
*/
default Aws2AthenaComponentBuilder waitTimeout(long waitTimeout) {
doSetProperty("waitTimeout", waitTimeout);
return this;
}
/**
* The workgroup to use for running the query.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: producer
*
* @param workGroup the value to set
* @return the dsl builder
*/
default Aws2AthenaComponentBuilder workGroup(java.lang.String workGroup) {
doSetProperty("workGroup", workGroup);
return this;
}
/**
* Whether autowiring is enabled. This is used for automatic autowiring
* options (the option must be marked as autowired) by looking up in the
* registry to find if there is a single instance of matching type,
* which then gets configured on the component. This can be used for
* automatic configuring JDBC data sources, JMS connection factories,
* AWS Clients, etc.
*
* The option is a: <code>boolean</code> type.
*
* Default: true
* Group: advanced
*
* @param autowiredEnabled the value to set
* @return the dsl builder
*/
default Aws2AthenaComponentBuilder autowiredEnabled(
boolean autowiredEnabled) {
doSetProperty("autowiredEnabled", autowiredEnabled);
return this;
}
/**
* A unique string to ensure issues queries are idempotent. It is
* unlikely you will need to set this.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: advanced
*
* @param clientRequestToken the value to set
* @return the dsl builder
*/
default Aws2AthenaComponentBuilder clientRequestToken(
java.lang.String clientRequestToken) {
doSetProperty("clientRequestToken", clientRequestToken);
return this;
}
}
class Aws2AthenaComponentBuilderImpl
extends
AbstractComponentBuilder<Athena2Component>
implements
Aws2AthenaComponentBuilder {
@Override
protected Athena2Component buildConcreteComponent() {
return new Athena2Component();
}
private org.apache.camel.component.aws2.athena.Athena2Configuration getOrCreateConfiguration(
org.apache.camel.component.aws2.athena.Athena2Component component) {
if (component.getConfiguration() == null) {
component.setConfiguration(new org.apache.camel.component.aws2.athena.Athena2Configuration());
}
return component.getConfiguration();
}
@Override
protected boolean setPropertyOnComponent(
Component component,
String name,
Object value) {
switch (name) {
case "accessKey": getOrCreateConfiguration((Athena2Component) component).setAccessKey((java.lang.String) value); return true;
case "amazonAthenaClient": getOrCreateConfiguration((Athena2Component) component).setAmazonAthenaClient((software.amazon.awssdk.services.athena.AthenaClient) value); return true;
case "configuration": ((Athena2Component) component).setConfiguration((org.apache.camel.component.aws2.athena.Athena2Configuration) value); return true;
case "database": getOrCreateConfiguration((Athena2Component) component).setDatabase((java.lang.String) value); return true;
case "delay": getOrCreateConfiguration((Athena2Component) component).setDelay((long) value); return true;
case "encryptionOption": getOrCreateConfiguration((Athena2Component) component).setEncryptionOption((software.amazon.awssdk.services.athena.model.EncryptionOption) value); return true;
case "includeTrace": getOrCreateConfiguration((Athena2Component) component).setIncludeTrace((boolean) value); return true;
case "initialDelay": getOrCreateConfiguration((Athena2Component) component).setInitialDelay((long) value); return true;
case "kmsKey": getOrCreateConfiguration((Athena2Component) component).setKmsKey((java.lang.String) value); return true;
case "lazyStartProducer": ((Athena2Component) component).setLazyStartProducer((boolean) value); return true;
case "maxAttempts": getOrCreateConfiguration((Athena2Component) component).setMaxAttempts((int) value); return true;
case "maxResults": getOrCreateConfiguration((Athena2Component) component).setMaxResults((java.lang.Integer) value); return true;
case "nextToken": getOrCreateConfiguration((Athena2Component) component).setNextToken((java.lang.String) value); return true;
case "operation": getOrCreateConfiguration((Athena2Component) component).setOperation((org.apache.camel.component.aws2.athena.Athena2Operations) value); return true;
case "outputLocation": getOrCreateConfiguration((Athena2Component) component).setOutputLocation((java.lang.String) value); return true;
case "outputType": getOrCreateConfiguration((Athena2Component) component).setOutputType((org.apache.camel.component.aws2.athena.Athena2OutputType) value); return true;
case "proxyHost": getOrCreateConfiguration((Athena2Component) component).setProxyHost((java.lang.String) value); return true;
case "proxyPort": getOrCreateConfiguration((Athena2Component) component).setProxyPort((java.lang.Integer) value); return true;
case "proxyProtocol": getOrCreateConfiguration((Athena2Component) component).setProxyProtocol((software.amazon.awssdk.core.Protocol) value); return true;
case "queryExecutionId": getOrCreateConfiguration((Athena2Component) component).setQueryExecutionId((java.lang.String) value); return true;
case "queryString": getOrCreateConfiguration((Athena2Component) component).setQueryString((java.lang.String) value); return true;
case "region": getOrCreateConfiguration((Athena2Component) component).setRegion((java.lang.String) value); return true;
case "resetWaitTimeoutOnRetry": getOrCreateConfiguration((Athena2Component) component).setResetWaitTimeoutOnRetry((boolean) value); return true;
case "retry": getOrCreateConfiguration((Athena2Component) component).setRetry((java.lang.String) value); return true;
case "secretKey": getOrCreateConfiguration((Athena2Component) component).setSecretKey((java.lang.String) value); return true;
case "useDefaultCredentialsProvider": getOrCreateConfiguration((Athena2Component) component).setUseDefaultCredentialsProvider((boolean) value); return true;
case "waitTimeout": getOrCreateConfiguration((Athena2Component) component).setWaitTimeout((long) value); return true;
case "workGroup": getOrCreateConfiguration((Athena2Component) component).setWorkGroup((java.lang.String) value); return true;
case "autowiredEnabled": ((Athena2Component) component).setAutowiredEnabled((boolean) value); return true;
case "clientRequestToken": getOrCreateConfiguration((Athena2Component) component).setClientRequestToken((java.lang.String) value); return true;
default: return false;
}
}
}
} | apache-2.0 |
q474818917/solr-5.2.0 | solr/core/src/java/org/apache/solr/search/stats/StatsSource.java | 1749 | package org.apache.solr.search.stats;
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.IOException;
import org.apache.lucene.index.Term;
import org.apache.lucene.index.TermContext;
import org.apache.lucene.search.CollectionStatistics;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TermStatistics;
import org.apache.lucene.search.Weight;
import org.apache.solr.search.SolrIndexSearcher;
/**
* The purpose of this class is only to provide two pieces of information
* necessary to create {@link Weight} from a {@link Query}, that is
* {@link TermStatistics} for a term and {@link CollectionStatistics} for the
* whole collection.
*/
public abstract class StatsSource {
public abstract TermStatistics termStatistics(SolrIndexSearcher localSearcher, Term term, TermContext context)
throws IOException;
public abstract CollectionStatistics collectionStatistics(SolrIndexSearcher localSearcher, String field)
throws IOException;
}
| apache-2.0 |
AnshulJain1985/Roadcast-Tracker | src/org/traccar/protocol/MtxProtocolDecoder.java | 3420 | /*
* Copyright 2015 Anton Tananaev (anton@traccar.org)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.traccar.protocol;
import org.jboss.netty.channel.Channel;
import org.traccar.BaseProtocolDecoder;
import org.traccar.DeviceSession;
import org.traccar.helper.Parser;
import org.traccar.helper.PatternBuilder;
import org.traccar.model.Position;
import java.net.SocketAddress;
import java.util.regex.Pattern;
public class MtxProtocolDecoder extends BaseProtocolDecoder {
public MtxProtocolDecoder(MtxProtocol protocol) {
super(protocol);
}
private static final Pattern PATTERN = new PatternBuilder()
.text("#MTX,")
.number("(d+),") // imei
.number("(dddd)(dd)(dd),") // date (yyyymmdd)
.number("(dd)(dd)(dd),") // time (hhmmss)
.number("(-?d+.d+),") // latitude
.number("(-?d+.d+),") // longitude
.number("(d+.?d*),") // speed
.number("(d+),") // course
.number("(d+.?d*),") // odometer
.groupBegin()
.number("d+")
.or()
.text("X")
.groupEnd()
.text(",")
.expression("(?:[01]|X),")
.expression("([01]+),") // input
.expression("([01]+),") // output
.number("(d+),") // adc1
.number("(d+)") // adc2
.any()
.compile();
@Override
protected Object decode(
Channel channel, SocketAddress remoteAddress, Object msg) throws Exception {
if (channel != null) {
channel.write("#ACK");
}
Parser parser = new Parser(PATTERN, (String) msg);
if (!parser.matches()) {
return null;
}
Position position = new Position();
position.setProtocol(getProtocolName());
DeviceSession deviceSession = getDeviceSession(channel, remoteAddress, parser.next());
if (deviceSession == null) {
return null;
}
position.setDeviceId(deviceSession.getDeviceId());
position.setTime(parser.nextDateTime());
position.setValid(true);
position.setLatitude(parser.nextDouble(0));
position.setLongitude(parser.nextDouble(0));
position.setSpeed(parser.nextDouble(0));
position.setCourse(parser.nextDouble(0));
position.set(Position.KEY_ODOMETER, parser.nextDouble(0) * 1000);
position.set(Position.KEY_INPUT, parser.next());
position.set(Position.KEY_OUTPUT, parser.next());
position.set(Position.PREFIX_ADC + 1, parser.next());
position.set(Position.PREFIX_ADC + 2, parser.next());
return position;
}
}
| apache-2.0 |
flo/Terasology | engine/src/main/java/org/terasology/math/Roll.java | 1446 | /*
* Copyright 2013 MovingBlocks
*
* 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.terasology.math;
/**
* Enumeration for Roll.
* <br><br>
* Pitch, yaw and roll enumerations are all very similar, but separated to allow for safer usage in Rotation.
*
*/
public enum Roll {
NONE((byte) 0b00, 0, 0),
CLOCKWISE_90((byte) 0b01, (float) (0.5f * Math.PI), 1),
CLOCKWISE_180((byte) 0b10, (float) (Math.PI), 2),
CLOCKWISE_270((byte) 0b11, (float) (-0.5f * Math.PI), 3);
private byte index;
private float radians;
private int increments;
private Roll(byte index, float radians, int increments) {
this.index = index;
this.radians = radians;
this.increments = increments;
}
public float getRadians() {
return radians;
}
public int getIncrements() {
return increments;
}
public byte getIndex() {
return index;
}
}
| apache-2.0 |
speddy93/nifi | nifi-nar-bundles/nifi-standard-bundle/nifi-standard-processors/src/test/java/org/apache/nifi/processors/standard/TestEncryptContent.java | 20060 | /*
* 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.nifi.processors.standard;
import org.apache.commons.codec.binary.Hex;
import org.apache.nifi.components.ValidationResult;
import org.apache.nifi.processors.standard.util.crypto.CipherUtility;
import org.apache.nifi.processors.standard.util.crypto.PasswordBasedEncryptor;
import org.apache.nifi.security.util.EncryptionMethod;
import org.apache.nifi.security.util.KeyDerivationFunction;
import org.apache.nifi.util.MockFlowFile;
import org.apache.nifi.util.MockProcessContext;
import org.apache.nifi.util.TestRunner;
import org.apache.nifi.util.TestRunners;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.junit.Assert;
import org.junit.Assume;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import java.security.Security;
import java.util.Collection;
public class TestEncryptContent {
private static final Logger logger = LoggerFactory.getLogger(TestEncryptContent.class);
@Before
public void setUp() {
Security.addProvider(new BouncyCastleProvider());
}
@Test
public void testRoundTrip() throws IOException {
final TestRunner testRunner = TestRunners.newTestRunner(new EncryptContent());
testRunner.setProperty(EncryptContent.PASSWORD, "short");
testRunner.setProperty(EncryptContent.KEY_DERIVATION_FUNCTION, KeyDerivationFunction.NIFI_LEGACY.name());
// Must be allowed or short password will cause validation errors
testRunner.setProperty(EncryptContent.ALLOW_WEAK_CRYPTO, "allowed");
for (final EncryptionMethod encryptionMethod : EncryptionMethod.values()) {
if (encryptionMethod.isUnlimitedStrength()) {
continue; // cannot test unlimited strength in unit tests because it's not enabled by the JVM by default.
}
// KeyedCiphers tested in TestEncryptContentGroovy.groovy
if (encryptionMethod.isKeyedCipher()) {
continue;
}
logger.info("Attempting {}", encryptionMethod.name());
testRunner.setProperty(EncryptContent.ENCRYPTION_ALGORITHM, encryptionMethod.name());
testRunner.setProperty(EncryptContent.MODE, EncryptContent.ENCRYPT_MODE);
testRunner.enqueue(Paths.get("src/test/resources/hello.txt"));
testRunner.clearTransferState();
testRunner.run();
testRunner.assertAllFlowFilesTransferred(EncryptContent.REL_SUCCESS, 1);
MockFlowFile flowFile = testRunner.getFlowFilesForRelationship(EncryptContent.REL_SUCCESS).get(0);
testRunner.assertQueueEmpty();
testRunner.setProperty(EncryptContent.MODE, EncryptContent.DECRYPT_MODE);
testRunner.enqueue(flowFile);
testRunner.clearTransferState();
testRunner.run();
testRunner.assertAllFlowFilesTransferred(EncryptContent.REL_SUCCESS, 1);
logger.info("Successfully decrypted {}", encryptionMethod.name());
flowFile = testRunner.getFlowFilesForRelationship(EncryptContent.REL_SUCCESS).get(0);
flowFile.assertContentEquals(new File("src/test/resources/hello.txt"));
}
}
@Test
public void testShouldDetermineMaxKeySizeForAlgorithms() throws IOException {
// Arrange
final String AES_ALGORITHM = EncryptionMethod.MD5_256AES.getAlgorithm();
final String DES_ALGORITHM = EncryptionMethod.MD5_DES.getAlgorithm();
final int AES_MAX_LENGTH = PasswordBasedEncryptor.supportsUnlimitedStrength() ? Integer.MAX_VALUE : 128;
final int DES_MAX_LENGTH = PasswordBasedEncryptor.supportsUnlimitedStrength() ? Integer.MAX_VALUE : 64;
// Act
int determinedAESMaxLength = PasswordBasedEncryptor.getMaxAllowedKeyLength(AES_ALGORITHM);
int determinedTDESMaxLength = PasswordBasedEncryptor.getMaxAllowedKeyLength(DES_ALGORITHM);
// Assert
assert determinedAESMaxLength == AES_MAX_LENGTH;
assert determinedTDESMaxLength == DES_MAX_LENGTH;
}
@Test
public void testShouldDecryptOpenSSLRawSalted() throws IOException {
// Arrange
Assume.assumeTrue("Test is being skipped due to this JVM lacking JCE Unlimited Strength Jurisdiction Policy file.",
PasswordBasedEncryptor.supportsUnlimitedStrength());
final TestRunner testRunner = TestRunners.newTestRunner(new EncryptContent());
final String password = "thisIsABadPassword";
final EncryptionMethod method = EncryptionMethod.MD5_256AES;
final KeyDerivationFunction kdf = KeyDerivationFunction.OPENSSL_EVP_BYTES_TO_KEY;
testRunner.setProperty(EncryptContent.PASSWORD, password);
testRunner.setProperty(EncryptContent.KEY_DERIVATION_FUNCTION, kdf.name());
testRunner.setProperty(EncryptContent.ENCRYPTION_ALGORITHM, method.name());
testRunner.setProperty(EncryptContent.MODE, EncryptContent.DECRYPT_MODE);
// Act
testRunner.enqueue(Paths.get("src/test/resources/TestEncryptContent/salted_raw.enc"));
testRunner.clearTransferState();
testRunner.run();
// Assert
testRunner.assertAllFlowFilesTransferred(EncryptContent.REL_SUCCESS, 1);
testRunner.assertQueueEmpty();
MockFlowFile flowFile = testRunner.getFlowFilesForRelationship(EncryptContent.REL_SUCCESS).get(0);
logger.info("Decrypted contents (hex): {}", Hex.encodeHexString(flowFile.toByteArray()));
logger.info("Decrypted contents: {}", new String(flowFile.toByteArray(), "UTF-8"));
// Assert
flowFile.assertContentEquals(new File("src/test/resources/TestEncryptContent/plain.txt"));
}
@Test
public void testShouldDecryptOpenSSLRawUnsalted() throws IOException {
// Arrange
Assume.assumeTrue("Test is being skipped due to this JVM lacking JCE Unlimited Strength Jurisdiction Policy file.",
PasswordBasedEncryptor.supportsUnlimitedStrength());
final TestRunner testRunner = TestRunners.newTestRunner(new EncryptContent());
final String password = "thisIsABadPassword";
final EncryptionMethod method = EncryptionMethod.MD5_256AES;
final KeyDerivationFunction kdf = KeyDerivationFunction.OPENSSL_EVP_BYTES_TO_KEY;
testRunner.setProperty(EncryptContent.PASSWORD, password);
testRunner.setProperty(EncryptContent.KEY_DERIVATION_FUNCTION, kdf.name());
testRunner.setProperty(EncryptContent.ENCRYPTION_ALGORITHM, method.name());
testRunner.setProperty(EncryptContent.MODE, EncryptContent.DECRYPT_MODE);
// Act
testRunner.enqueue(Paths.get("src/test/resources/TestEncryptContent/unsalted_raw.enc"));
testRunner.clearTransferState();
testRunner.run();
// Assert
testRunner.assertAllFlowFilesTransferred(EncryptContent.REL_SUCCESS, 1);
testRunner.assertQueueEmpty();
MockFlowFile flowFile = testRunner.getFlowFilesForRelationship(EncryptContent.REL_SUCCESS).get(0);
logger.info("Decrypted contents (hex): {}", Hex.encodeHexString(flowFile.toByteArray()));
logger.info("Decrypted contents: {}", new String(flowFile.toByteArray(), "UTF-8"));
// Assert
flowFile.assertContentEquals(new File("src/test/resources/TestEncryptContent/plain.txt"));
}
@Test
public void testDecryptShouldDefaultToBcrypt() throws IOException {
// Arrange
final TestRunner testRunner = TestRunners.newTestRunner(new EncryptContent());
// Assert
Assert.assertEquals("Decrypt should default to Legacy KDF", testRunner.getProcessor().getPropertyDescriptor(EncryptContent.KEY_DERIVATION_FUNCTION
.getName()).getDefaultValue(), KeyDerivationFunction.BCRYPT.name());
}
@Test
public void testDecryptSmallerThanSaltSize() {
final TestRunner runner = TestRunners.newTestRunner(EncryptContent.class);
runner.setProperty(EncryptContent.PASSWORD, "Hello, World!");
runner.setProperty(EncryptContent.MODE, EncryptContent.DECRYPT_MODE);
runner.setProperty(EncryptContent.KEY_DERIVATION_FUNCTION, KeyDerivationFunction.NIFI_LEGACY.name());
runner.enqueue(new byte[4]);
runner.run();
runner.assertAllFlowFilesTransferred(EncryptContent.REL_FAILURE, 1);
}
@Test
public void testPGPDecrypt() throws IOException {
final TestRunner runner = TestRunners.newTestRunner(EncryptContent.class);
runner.setProperty(EncryptContent.MODE, EncryptContent.DECRYPT_MODE);
runner.setProperty(EncryptContent.ENCRYPTION_ALGORITHM, EncryptionMethod.PGP_ASCII_ARMOR.name());
runner.setProperty(EncryptContent.PASSWORD, "Hello, World!");
runner.enqueue(Paths.get("src/test/resources/TestEncryptContent/text.txt.asc"));
runner.run();
runner.assertAllFlowFilesTransferred(EncryptContent.REL_SUCCESS, 1);
final MockFlowFile flowFile = runner.getFlowFilesForRelationship(EncryptContent.REL_SUCCESS).get(0);
flowFile.assertContentEquals(Paths.get("src/test/resources/TestEncryptContent/text.txt"));
}
@Test
public void testShouldValidatePGPPublicKeyringRequiresUserId() {
// Arrange
final TestRunner runner = TestRunners.newTestRunner(EncryptContent.class);
Collection<ValidationResult> results;
MockProcessContext pc;
runner.setProperty(EncryptContent.MODE, EncryptContent.ENCRYPT_MODE);
runner.setProperty(EncryptContent.ENCRYPTION_ALGORITHM, EncryptionMethod.PGP.name());
runner.setProperty(EncryptContent.PUBLIC_KEYRING, "src/test/resources/TestEncryptContent/pubring.gpg");
runner.enqueue(new byte[0]);
pc = (MockProcessContext) runner.getProcessContext();
// Act
results = pc.validate();
// Assert
Assert.assertEquals(1, results.size());
ValidationResult vr = (ValidationResult) results.toArray()[0];
String expectedResult = " encryption without a " + EncryptContent.PASSWORD.getDisplayName() + " requires both "
+ EncryptContent.PUBLIC_KEYRING.getDisplayName() + " and "
+ EncryptContent.PUBLIC_KEY_USERID.getDisplayName();
String message = "'" + vr.toString() + "' contains '" + expectedResult + "'";
Assert.assertTrue(message, vr.toString().contains(expectedResult));
}
@Test
public void testShouldValidatePGPPublicKeyringExists() {
// Arrange
final TestRunner runner = TestRunners.newTestRunner(EncryptContent.class);
Collection<ValidationResult> results;
MockProcessContext pc;
runner.setProperty(EncryptContent.MODE, EncryptContent.ENCRYPT_MODE);
runner.setProperty(EncryptContent.ENCRYPTION_ALGORITHM, EncryptionMethod.PGP.name());
runner.setProperty(EncryptContent.PUBLIC_KEYRING, "src/test/resources/TestEncryptContent/pubring.gpg.missing");
runner.setProperty(EncryptContent.PUBLIC_KEY_USERID, "USERID");
runner.enqueue(new byte[0]);
pc = (MockProcessContext) runner.getProcessContext();
// Act
results = pc.validate();
// Assert
Assert.assertEquals(1, results.size());
ValidationResult vr = (ValidationResult) results.toArray()[0];
String expectedResult = "java.io.FileNotFoundException";
String message = "'" + vr.toString() + "' contains '" + expectedResult + "'";
Assert.assertTrue(message, vr.toString().contains(expectedResult));
}
@Test
public void testShouldValidatePGPPublicKeyringIsProperFormat() {
// Arrange
final TestRunner runner = TestRunners.newTestRunner(EncryptContent.class);
Collection<ValidationResult> results;
MockProcessContext pc;
runner.setProperty(EncryptContent.MODE, EncryptContent.ENCRYPT_MODE);
runner.setProperty(EncryptContent.ENCRYPTION_ALGORITHM, EncryptionMethod.PGP.name());
runner.setProperty(EncryptContent.PUBLIC_KEYRING, "src/test/resources/TestEncryptContent/text.txt");
runner.setProperty(EncryptContent.PUBLIC_KEY_USERID, "USERID");
runner.enqueue(new byte[0]);
pc = (MockProcessContext) runner.getProcessContext();
// Act
results = pc.validate();
// Assert
Assert.assertEquals(1, results.size());
ValidationResult vr = (ValidationResult) results.toArray()[0];
String expectedResult = " java.io.IOException: invalid header encountered";
String message = "'" + vr.toString() + "' contains '" + expectedResult + "'";
Assert.assertTrue(message, vr.toString().contains(expectedResult));
}
@Test
public void testShouldValidatePGPPublicKeyringContainsUserId() {
// Arrange
final TestRunner runner = TestRunners.newTestRunner(EncryptContent.class);
Collection<ValidationResult> results;
MockProcessContext pc;
runner.setProperty(EncryptContent.MODE, EncryptContent.ENCRYPT_MODE);
runner.setProperty(EncryptContent.ENCRYPTION_ALGORITHM, EncryptionMethod.PGP.name());
runner.setProperty(EncryptContent.PUBLIC_KEYRING, "src/test/resources/TestEncryptContent/pubring.gpg");
runner.setProperty(EncryptContent.PUBLIC_KEY_USERID, "USERID");
runner.enqueue(new byte[0]);
pc = (MockProcessContext) runner.getProcessContext();
// Act
results = pc.validate();
// Assert
Assert.assertEquals(1, results.size());
ValidationResult vr = (ValidationResult) results.toArray()[0];
String expectedResult = "PGPException: Could not find a public key with the given userId";
String message = "'" + vr.toString() + "' contains '" + expectedResult + "'";
Assert.assertTrue(message, vr.toString().contains(expectedResult));
}
@Test
public void testShouldExtractPGPPublicKeyFromKeyring() {
// Arrange
final TestRunner runner = TestRunners.newTestRunner(EncryptContent.class);
Collection<ValidationResult> results;
MockProcessContext pc;
runner.setProperty(EncryptContent.MODE, EncryptContent.ENCRYPT_MODE);
runner.setProperty(EncryptContent.ENCRYPTION_ALGORITHM, EncryptionMethod.PGP.name());
runner.setProperty(EncryptContent.PUBLIC_KEYRING, "src/test/resources/TestEncryptContent/pubring.gpg");
runner.setProperty(EncryptContent.PUBLIC_KEY_USERID, "NiFi PGP Test Key (Short test key for NiFi PGP unit tests) <alopresto.apache+test@gmail.com>");
runner.enqueue(new byte[0]);
pc = (MockProcessContext) runner.getProcessContext();
// Act
results = pc.validate();
// Assert
Assert.assertEquals(0, results.size());
}
@Test
public void testValidation() {
final TestRunner runner = TestRunners.newTestRunner(EncryptContent.class);
Collection<ValidationResult> results;
MockProcessContext pc;
runner.enqueue(new byte[0]);
pc = (MockProcessContext) runner.getProcessContext();
results = pc.validate();
Assert.assertEquals(results.toString(), 1, results.size());
for (final ValidationResult vr : results) {
Assert.assertTrue(vr.toString()
.contains(EncryptContent.PASSWORD.getDisplayName() + " is required when using algorithm"));
}
runner.enqueue(new byte[0]);
final EncryptionMethod encryptionMethod = EncryptionMethod.MD5_128AES;
runner.setProperty(EncryptContent.ENCRYPTION_ALGORITHM, encryptionMethod.name());
runner.setProperty(EncryptContent.KEY_DERIVATION_FUNCTION, KeyDerivationFunction.NIFI_LEGACY.name());
runner.setProperty(EncryptContent.PASSWORD, "ThisIsAPasswordThatIsLongerThanSixteenCharacters");
pc = (MockProcessContext) runner.getProcessContext();
results = pc.validate();
if (!PasswordBasedEncryptor.supportsUnlimitedStrength()) {
logger.info(results.toString());
Assert.assertEquals(1, results.size());
for (final ValidationResult vr : results) {
Assert.assertTrue(
"Did not successfully catch validation error of a long password in a non-JCE Unlimited Strength environment",
vr.toString().contains("Password length greater than " + CipherUtility.getMaximumPasswordLengthForAlgorithmOnLimitedStrengthCrypto(encryptionMethod)
+ " characters is not supported by this JVM due to lacking JCE Unlimited Strength Jurisdiction Policy files."));
}
} else {
Assert.assertEquals(results.toString(), 0, results.size());
}
runner.removeProperty(EncryptContent.PASSWORD);
runner.setProperty(EncryptContent.ENCRYPTION_ALGORITHM, EncryptionMethod.PGP.name());
runner.setProperty(EncryptContent.PUBLIC_KEYRING, "src/test/resources/TestEncryptContent/text.txt");
runner.enqueue(new byte[0]);
pc = (MockProcessContext) runner.getProcessContext();
results = pc.validate();
Assert.assertEquals(1, results.size());
for (final ValidationResult vr : results) {
Assert.assertTrue(vr.toString().contains(
" encryption without a " + EncryptContent.PASSWORD.getDisplayName() + " requires both "
+ EncryptContent.PUBLIC_KEYRING.getDisplayName() + " and "
+ EncryptContent.PUBLIC_KEY_USERID.getDisplayName()));
}
// Legacy tests moved to individual tests to comply with new library
// TODO: Move secring tests out to individual as well
runner.removeProperty(EncryptContent.PUBLIC_KEYRING);
runner.removeProperty(EncryptContent.PUBLIC_KEY_USERID);
runner.setProperty(EncryptContent.MODE, EncryptContent.DECRYPT_MODE);
runner.setProperty(EncryptContent.PRIVATE_KEYRING, "src/test/resources/TestEncryptContent/secring.gpg");
runner.enqueue(new byte[0]);
pc = (MockProcessContext) runner.getProcessContext();
results = pc.validate();
Assert.assertEquals(1, results.size());
for (final ValidationResult vr : results) {
Assert.assertTrue(vr.toString().contains(
" decryption without a " + EncryptContent.PASSWORD.getDisplayName() + " requires both "
+ EncryptContent.PRIVATE_KEYRING.getDisplayName() + " and "
+ EncryptContent.PRIVATE_KEYRING_PASSPHRASE.getDisplayName()));
}
runner.setProperty(EncryptContent.PRIVATE_KEYRING_PASSPHRASE, "PASSWORD");
runner.enqueue(new byte[0]);
pc = (MockProcessContext) runner.getProcessContext();
results = pc.validate();
Assert.assertEquals(1, results.size());
for (final ValidationResult vr : results) {
Assert.assertTrue(vr.toString().contains(
" could not be opened with the provided " + EncryptContent.PRIVATE_KEYRING_PASSPHRASE.getDisplayName()));
}
}
}
| apache-2.0 |
zstackorg/zstack | sdk/src/main/java/org/zstack/sdk/ChangeIPSecConnectionStateResult.java | 371 | package org.zstack.sdk;
import org.zstack.sdk.IPsecConnectionInventory;
public class ChangeIPSecConnectionStateResult {
public IPsecConnectionInventory inventory;
public void setInventory(IPsecConnectionInventory inventory) {
this.inventory = inventory;
}
public IPsecConnectionInventory getInventory() {
return this.inventory;
}
}
| apache-2.0 |
thinker0/bigqueue | src/main/java/com/leansoft/bigqueue/utils/Calculator.java | 540 | package com.leansoft.bigqueue.utils;
public class Calculator {
/**
* mod by shift
*
* @param val
* @param bits
* @return
*/
public static long mod(long val, int bits) {
return val - ((val >> bits) << bits);
}
/**
* multiply by shift
*
* @param val
* @param bits
* @return
*/
public static long mul(long val, int bits) {
return val << bits;
}
/**
* divide by shift
*
* @param val
* @param bits
* @return
*/
public static long div(long val, int bits) {
return val >> bits;
}
}
| apache-2.0 |
upthewaterspout/incubator-geode | gemfire-core/src/main/java/com/gemstone/gemfire/internal/cache/RegionTTLExpiryTask.java | 2142 | /*=========================================================================
* Copyright (c) 2002-2014 Pivotal Software, Inc. All Rights Reserved.
* This product is protected by U.S. and international copyright
* and intellectual property laws. Pivotal products are covered by
* more patents listed at http://www.pivotal.io/patents.
*=========================================================================
*/
package com.gemstone.gemfire.internal.cache;
import com.gemstone.gemfire.cache.*;
/**
*
* @author Eric Zoerner
*/
class RegionTTLExpiryTask extends RegionExpiryTask {
/** Creates a new instance of RegionTTLExpiryTask */
RegionTTLExpiryTask(LocalRegion reg) {
super(reg);
}
/**
* @return the absolute time (ms since Jan 1, 1970) at which this
* region expires, due to either time-to-live or idle-timeout (whichever
* will occur first), or 0 if neither are used.
*/
@Override
long getExpirationTime() throws EntryNotFoundException {
// if this is an invalidate action and region has already been invalidated,
// then don't expire again until the full timeout from now.
ExpirationAction action = getAction();
if (action == ExpirationAction.INVALIDATE ||
action == ExpirationAction.LOCAL_INVALIDATE) {
if (getLocalRegion().regionInvalid) {
int timeout = getTTLAttributes().getTimeout();
if (timeout == 0) return 0L;
if (!getLocalRegion().EXPIRY_UNITS_MS) {
timeout *= 1000;
}
// Sometimes region expiration depends on lastModifiedTime which in turn
// depends on entry modification time. To make it consistent always use
// cache time here.
return timeout + getLocalRegion().cacheTimeMillis();
}
}
// otherwise, expire at timeout plus last modified time
return getTTLExpirationTime();
}
@Override
protected ExpirationAction getAction() {
return getTTLAttributes().getAction();
}
@Override
protected final void addExpiryTask() {
getLocalRegion().addTTLExpiryTask(this);
}
@Override
public boolean isPending() {
return false;
}
}
| apache-2.0 |
joelmap/omnidroid | omnidroid/src/edu/nyu/cs/omnidroid/app/controller/events/ServiceAvailableEvent.java | 1958 | /*******************************************************************************
* Copyright 2010 Omnidroid - http://code.google.com/p/omnidroid
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package edu.nyu.cs.omnidroid.app.controller.events;
import edu.nyu.cs.omnidroid.app.controller.Event;
import android.content.Intent;
/**
* This class encapsulates an ServiceAvailable event. It wraps the intent that triggered this event
* and provides access to any attribute data associated with it.
*/
public class ServiceAvailableEvent extends Event {
/** Event name (to match record in database) */
public static final String APPLICATION_NAME = "Omnidroid";
public static final String EVENT_NAME = "Service Available";
public static final String ACTION_NAME = "SERVICE_AVAILABLE";
/**
* Constructs a new ServiceAvailable object with intent that holds the data
* needed to check the event against user defined rules.
*
* @param intent
* the intent received when the ServiceAvailable event was fired
*/
public ServiceAvailableEvent(Intent intent) {
super(APPLICATION_NAME, EVENT_NAME, intent);
}
/**
* @throws IllegalArgumentException
*/
@Override
public String getAttribute(String attributeName) throws IllegalArgumentException {
throw new IllegalArgumentException();
}
}
| apache-2.0 |
benbenw/jmeter | src/components/src/main/java/org/apache/jmeter/timers/UniformRandomTimer.java | 1497 | /*
* 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.jmeter.timers;
import java.io.Serializable;
import org.apache.jmeter.util.JMeterUtils;
/**
* This class implements those methods needed by RandomTimer to be instantiable
* and implements a random delay with an average value and a uniformly
* distributed variation.
*
*/
public class UniformRandomTimer extends RandomTimer implements Serializable {
private static final long serialVersionUID = 241L;
@Override
public long delay() {
return (long) Math.abs((getRandom().nextDouble() * getRange()) + super.delay());
}
@Override
public String toString() {
return JMeterUtils.getResString("uniform_timer_memo"); //$NON-NLS-1$
}
}
| apache-2.0 |
emre-aydin/hazelcast | hazelcast/src/main/java/com/hazelcast/query/impl/predicates/TruePredicate.java | 2288 | /*
* Copyright (c) 2008-2021, Hazelcast, 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.hazelcast.query.impl.predicates;
import com.hazelcast.nio.ObjectDataInput;
import com.hazelcast.nio.ObjectDataOutput;
import com.hazelcast.internal.serialization.BinaryInterface;
import com.hazelcast.nio.serialization.IdentifiedDataSerializable;
import com.hazelcast.query.Predicate;
import java.io.IOException;
import java.util.Map;
/**
* A {@link com.hazelcast.query.Predicate} which always returns true.
*
* @param <K> map key type
* @param <V> map value type
*/
@BinaryInterface
public class TruePredicate<K, V> implements IdentifiedDataSerializable, Predicate<K, V> {
/**
* An instance of the TruePredicate.
*/
public static final TruePredicate INSTANCE = new TruePredicate();
private static final long serialVersionUID = 1L;
@SuppressWarnings("unchecked")
public static <K, V> TruePredicate<K, V> truePredicate() {
return INSTANCE;
}
@Override
public void writeData(ObjectDataOutput out) throws IOException {
}
@Override
public void readData(ObjectDataInput in) throws IOException {
}
@Override
public boolean apply(Map.Entry mapEntry) {
return true;
}
@Override
public String toString() {
return "TruePredicate{}";
}
@Override
public int getFactoryId() {
return PredicateDataSerializerHook.F_ID;
}
@Override
public int getClassId() {
return PredicateDataSerializerHook.TRUE_PREDICATE;
}
@Override
public boolean equals(Object o) {
return o instanceof TruePredicate;
}
@Override
public int hashCode() {
return getClass().hashCode();
}
}
| apache-2.0 |
intel-hadoop/hadoop | hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/ipc/RPC.java | 34991 | /**
* 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.ipc;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import java.net.ConnectException;
import java.net.InetSocketAddress;
import java.net.NoRouteToHostException;
import java.net.SocketTimeoutException;
import java.io.*;
import java.io.Closeable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.net.SocketFactory;
import org.apache.commons.logging.*;
import org.apache.hadoop.HadoopIllegalArgumentException;
import org.apache.hadoop.io.*;
import org.apache.hadoop.io.retry.RetryPolicy;
import org.apache.hadoop.ipc.Client.ConnectionId;
import org.apache.hadoop.ipc.protobuf.ProtocolInfoProtos.ProtocolInfoService;
import org.apache.hadoop.ipc.protobuf.RpcHeaderProtos.RpcResponseHeaderProto.RpcErrorCodeProto;
import org.apache.hadoop.ipc.protobuf.RpcHeaderProtos.RpcResponseHeaderProto.RpcStatusProto;
import org.apache.hadoop.net.NetUtils;
import org.apache.hadoop.security.SaslRpcServer;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.security.token.SecretManager;
import org.apache.hadoop.security.token.TokenIdentifier;
import org.apache.hadoop.conf.*;
import org.apache.hadoop.util.ReflectionUtils;
import org.apache.hadoop.util.Time;
import com.google.protobuf.BlockingService;
/** A simple RPC mechanism.
*
* A <i>protocol</i> is a Java interface. All parameters and return types must
* be one of:
*
* <ul> <li>a primitive type, <code>boolean</code>, <code>byte</code>,
* <code>char</code>, <code>short</code>, <code>int</code>, <code>long</code>,
* <code>float</code>, <code>double</code>, or <code>void</code>; or</li>
*
* <li>a {@link String}; or</li>
*
* <li>a {@link Writable}; or</li>
*
* <li>an array of the above types</li> </ul>
*
* All methods in the protocol should throw only IOException. No field data of
* the protocol instance is transmitted.
*/
public class RPC {
final static int RPC_SERVICE_CLASS_DEFAULT = 0;
public enum RpcKind {
RPC_BUILTIN ((short) 1), // Used for built in calls by tests
RPC_WRITABLE ((short) 2), // Use WritableRpcEngine
RPC_PROTOCOL_BUFFER ((short) 3); // Use ProtobufRpcEngine
final static short MAX_INDEX = RPC_PROTOCOL_BUFFER.value; // used for array size
public final short value; //TODO make it private
RpcKind(short val) {
this.value = val;
}
}
interface RpcInvoker {
/**
* Process a client call on the server side
* @param server the server within whose context this rpc call is made
* @param protocol - the protocol name (the class of the client proxy
* used to make calls to the rpc server.
* @param rpcRequest - deserialized
* @param receiveTime time at which the call received (for metrics)
* @return the call's return
* @throws IOException
**/
public Writable call(Server server, String protocol,
Writable rpcRequest, long receiveTime) throws Exception ;
}
static final Log LOG = LogFactory.getLog(RPC.class);
/**
* Get all superInterfaces that extend VersionedProtocol
* @param childInterfaces
* @return the super interfaces that extend VersionedProtocol
*/
static Class<?>[] getSuperInterfaces(Class<?>[] childInterfaces) {
List<Class<?>> allInterfaces = new ArrayList<Class<?>>();
for (Class<?> childInterface : childInterfaces) {
if (VersionedProtocol.class.isAssignableFrom(childInterface)) {
allInterfaces.add(childInterface);
allInterfaces.addAll(
Arrays.asList(
getSuperInterfaces(childInterface.getInterfaces())));
} else {
LOG.warn("Interface " + childInterface +
" ignored because it does not extend VersionedProtocol");
}
}
return allInterfaces.toArray(new Class[allInterfaces.size()]);
}
/**
* Get all interfaces that the given protocol implements or extends
* which are assignable from VersionedProtocol.
*/
static Class<?>[] getProtocolInterfaces(Class<?> protocol) {
Class<?>[] interfaces = protocol.getInterfaces();
return getSuperInterfaces(interfaces);
}
/**
* Get the protocol name.
* If the protocol class has a ProtocolAnnotation, then get the protocol
* name from the annotation; otherwise the class name is the protocol name.
*/
static public String getProtocolName(Class<?> protocol) {
if (protocol == null) {
return null;
}
ProtocolInfo anno = protocol.getAnnotation(ProtocolInfo.class);
return (anno == null) ? protocol.getName() : anno.protocolName();
}
/**
* Get the protocol version from protocol class.
* If the protocol class has a ProtocolAnnotation, then get the protocol
* name from the annotation; otherwise the class name is the protocol name.
*/
static public long getProtocolVersion(Class<?> protocol) {
if (protocol == null) {
throw new IllegalArgumentException("Null protocol");
}
long version;
ProtocolInfo anno = protocol.getAnnotation(ProtocolInfo.class);
if (anno != null) {
version = anno.protocolVersion();
if (version != -1)
return version;
}
try {
Field versionField = protocol.getField("versionID");
versionField.setAccessible(true);
return versionField.getLong(protocol);
} catch (NoSuchFieldException ex) {
throw new RuntimeException(ex);
} catch (IllegalAccessException ex) {
throw new RuntimeException(ex);
}
}
private RPC() {} // no public ctor
// cache of RpcEngines by protocol
private static final Map<Class<?>,RpcEngine> PROTOCOL_ENGINES
= new HashMap<Class<?>,RpcEngine>();
private static final String ENGINE_PROP = "rpc.engine";
/**
* Set a protocol to use a non-default RpcEngine.
* @param conf configuration to use
* @param protocol the protocol interface
* @param engine the RpcEngine impl
*/
public static void setProtocolEngine(Configuration conf,
Class<?> protocol, Class<?> engine) {
conf.setClass(ENGINE_PROP+"."+protocol.getName(), engine, RpcEngine.class);
}
// return the RpcEngine configured to handle a protocol
static synchronized RpcEngine getProtocolEngine(Class<?> protocol,
Configuration conf) {
RpcEngine engine = PROTOCOL_ENGINES.get(protocol);
if (engine == null) {
Class<?> impl = conf.getClass(ENGINE_PROP+"."+protocol.getName(),
WritableRpcEngine.class);
engine = (RpcEngine)ReflectionUtils.newInstance(impl, conf);
PROTOCOL_ENGINES.put(protocol, engine);
}
return engine;
}
/**
* A version mismatch for the RPC protocol.
*/
public static class VersionMismatch extends RpcServerException {
private static final long serialVersionUID = 0;
private String interfaceName;
private long clientVersion;
private long serverVersion;
/**
* Create a version mismatch exception
* @param interfaceName the name of the protocol mismatch
* @param clientVersion the client's version of the protocol
* @param serverVersion the server's version of the protocol
*/
public VersionMismatch(String interfaceName, long clientVersion,
long serverVersion) {
super("Protocol " + interfaceName + " version mismatch. (client = " +
clientVersion + ", server = " + serverVersion + ")");
this.interfaceName = interfaceName;
this.clientVersion = clientVersion;
this.serverVersion = serverVersion;
}
/**
* Get the interface name
* @return the java class name
* (eg. org.apache.hadoop.mapred.InterTrackerProtocol)
*/
public String getInterfaceName() {
return interfaceName;
}
/**
* Get the client's preferred version
*/
public long getClientVersion() {
return clientVersion;
}
/**
* Get the server's agreed to version.
*/
public long getServerVersion() {
return serverVersion;
}
/**
* get the rpc status corresponding to this exception
*/
public RpcStatusProto getRpcStatusProto() {
return RpcStatusProto.ERROR;
}
/**
* get the detailed rpc status corresponding to this exception
*/
public RpcErrorCodeProto getRpcErrorCodeProto() {
return RpcErrorCodeProto.ERROR_RPC_VERSION_MISMATCH;
}
}
/**
* Get a proxy connection to a remote server
*
* @param protocol protocol class
* @param clientVersion client version
* @param addr remote address
* @param conf configuration to use
* @return the proxy
* @throws IOException if the far end through a RemoteException
*/
public static <T> T waitForProxy(
Class<T> protocol,
long clientVersion,
InetSocketAddress addr,
Configuration conf
) throws IOException {
return waitForProtocolProxy(protocol, clientVersion, addr, conf).getProxy();
}
/**
* Get a protocol proxy that contains a proxy connection to a remote server
* and a set of methods that are supported by the server
*
* @param protocol protocol class
* @param clientVersion client version
* @param addr remote address
* @param conf configuration to use
* @return the protocol proxy
* @throws IOException if the far end through a RemoteException
*/
public static <T> ProtocolProxy<T> waitForProtocolProxy(Class<T> protocol,
long clientVersion,
InetSocketAddress addr,
Configuration conf) throws IOException {
return waitForProtocolProxy(
protocol, clientVersion, addr, conf, Long.MAX_VALUE);
}
/**
* Get a proxy connection to a remote server
*
* @param protocol protocol class
* @param clientVersion client version
* @param addr remote address
* @param conf configuration to use
* @param connTimeout time in milliseconds before giving up
* @return the proxy
* @throws IOException if the far end through a RemoteException
*/
public static <T> T waitForProxy(Class<T> protocol, long clientVersion,
InetSocketAddress addr, Configuration conf,
long connTimeout) throws IOException {
return waitForProtocolProxy(protocol, clientVersion, addr,
conf, connTimeout).getProxy();
}
/**
* Get a protocol proxy that contains a proxy connection to a remote server
* and a set of methods that are supported by the server
*
* @param protocol protocol class
* @param clientVersion client version
* @param addr remote address
* @param conf configuration to use
* @param connTimeout time in milliseconds before giving up
* @return the protocol proxy
* @throws IOException if the far end through a RemoteException
*/
public static <T> ProtocolProxy<T> waitForProtocolProxy(Class<T> protocol,
long clientVersion,
InetSocketAddress addr, Configuration conf,
long connTimeout) throws IOException {
return waitForProtocolProxy(protocol, clientVersion, addr, conf, 0, null, connTimeout);
}
/**
* Get a proxy connection to a remote server
*
* @param protocol protocol class
* @param clientVersion client version
* @param addr remote address
* @param conf configuration to use
* @param rpcTimeout timeout for each RPC
* @param timeout time in milliseconds before giving up
* @return the proxy
* @throws IOException if the far end through a RemoteException
*/
public static <T> T waitForProxy(Class<T> protocol,
long clientVersion,
InetSocketAddress addr, Configuration conf,
int rpcTimeout,
long timeout) throws IOException {
return waitForProtocolProxy(protocol, clientVersion, addr,
conf, rpcTimeout, null, timeout).getProxy();
}
/**
* Get a protocol proxy that contains a proxy connection to a remote server
* and a set of methods that are supported by the server
*
* @param protocol protocol class
* @param clientVersion client version
* @param addr remote address
* @param conf configuration to use
* @param rpcTimeout timeout for each RPC
* @param timeout time in milliseconds before giving up
* @return the proxy
* @throws IOException if the far end through a RemoteException
*/
public static <T> ProtocolProxy<T> waitForProtocolProxy(Class<T> protocol,
long clientVersion,
InetSocketAddress addr, Configuration conf,
int rpcTimeout,
RetryPolicy connectionRetryPolicy,
long timeout) throws IOException {
long startTime = Time.now();
IOException ioe;
while (true) {
try {
return getProtocolProxy(protocol, clientVersion, addr,
UserGroupInformation.getCurrentUser(), conf, NetUtils
.getDefaultSocketFactory(conf), rpcTimeout, connectionRetryPolicy);
} catch(ConnectException se) { // namenode has not been started
LOG.info("Server at " + addr + " not available yet, Zzzzz...");
ioe = se;
} catch(SocketTimeoutException te) { // namenode is busy
LOG.info("Problem connecting to server: " + addr);
ioe = te;
} catch(NoRouteToHostException nrthe) { // perhaps a VIP is failing over
LOG.info("No route to host for server: " + addr);
ioe = nrthe;
}
// check if timed out
if (Time.now()-timeout >= startTime) {
throw ioe;
}
if (Thread.currentThread().isInterrupted()) {
// interrupted during some IO; this may not have been caught
throw new InterruptedIOException("Interrupted waiting for the proxy");
}
// wait for retry
try {
Thread.sleep(1000);
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
throw (IOException) new InterruptedIOException(
"Interrupted waiting for the proxy").initCause(ioe);
}
}
}
/** Construct a client-side proxy object that implements the named protocol,
* talking to a server at the named address.
* @param <T>*/
public static <T> T getProxy(Class<T> protocol,
long clientVersion,
InetSocketAddress addr, Configuration conf,
SocketFactory factory) throws IOException {
return getProtocolProxy(
protocol, clientVersion, addr, conf, factory).getProxy();
}
/**
* Get a protocol proxy that contains a proxy connection to a remote server
* and a set of methods that are supported by the server
*
* @param protocol protocol class
* @param clientVersion client version
* @param addr remote address
* @param conf configuration to use
* @param factory socket factory
* @return the protocol proxy
* @throws IOException if the far end through a RemoteException
*/
public static <T> ProtocolProxy<T> getProtocolProxy(Class<T> protocol,
long clientVersion,
InetSocketAddress addr, Configuration conf,
SocketFactory factory) throws IOException {
UserGroupInformation ugi = UserGroupInformation.getCurrentUser();
return getProtocolProxy(protocol, clientVersion, addr, ugi, conf, factory);
}
/** Construct a client-side proxy object that implements the named protocol,
* talking to a server at the named address.
* @param <T>*/
public static <T> T getProxy(Class<T> protocol,
long clientVersion,
InetSocketAddress addr,
UserGroupInformation ticket,
Configuration conf,
SocketFactory factory) throws IOException {
return getProtocolProxy(
protocol, clientVersion, addr, ticket, conf, factory).getProxy();
}
/**
* Get a protocol proxy that contains a proxy connection to a remote server
* and a set of methods that are supported by the server
*
* @param protocol protocol class
* @param clientVersion client version
* @param addr remote address
* @param ticket user group information
* @param conf configuration to use
* @param factory socket factory
* @return the protocol proxy
* @throws IOException if the far end through a RemoteException
*/
public static <T> ProtocolProxy<T> getProtocolProxy(Class<T> protocol,
long clientVersion,
InetSocketAddress addr,
UserGroupInformation ticket,
Configuration conf,
SocketFactory factory) throws IOException {
return getProtocolProxy(
protocol, clientVersion, addr, ticket, conf, factory, 0, null);
}
/**
* Construct a client-side proxy that implements the named protocol,
* talking to a server at the named address.
* @param <T>
*
* @param protocol protocol
* @param clientVersion client's version
* @param addr server address
* @param ticket security ticket
* @param conf configuration
* @param factory socket factory
* @param rpcTimeout max time for each rpc; 0 means no timeout
* @return the proxy
* @throws IOException if any error occurs
*/
public static <T> T getProxy(Class<T> protocol,
long clientVersion,
InetSocketAddress addr,
UserGroupInformation ticket,
Configuration conf,
SocketFactory factory,
int rpcTimeout) throws IOException {
return getProtocolProxy(protocol, clientVersion, addr, ticket,
conf, factory, rpcTimeout, null).getProxy();
}
/**
* Get a protocol proxy that contains a proxy connection to a remote server
* and a set of methods that are supported by the server
*
* @param protocol protocol
* @param clientVersion client's version
* @param addr server address
* @param ticket security ticket
* @param conf configuration
* @param factory socket factory
* @param rpcTimeout max time for each rpc; 0 means no timeout
* @param connectionRetryPolicy retry policy
* @return the proxy
* @throws IOException if any error occurs
*/
public static <T> ProtocolProxy<T> getProtocolProxy(Class<T> protocol,
long clientVersion,
InetSocketAddress addr,
UserGroupInformation ticket,
Configuration conf,
SocketFactory factory,
int rpcTimeout,
RetryPolicy connectionRetryPolicy) throws IOException {
return getProtocolProxy(protocol, clientVersion, addr, ticket,
conf, factory, rpcTimeout, connectionRetryPolicy, null);
}
/**
* Get a protocol proxy that contains a proxy connection to a remote server
* and a set of methods that are supported by the server
*
* @param protocol protocol
* @param clientVersion client's version
* @param addr server address
* @param ticket security ticket
* @param conf configuration
* @param factory socket factory
* @param rpcTimeout max time for each rpc; 0 means no timeout
* @param connectionRetryPolicy retry policy
* @param fallbackToSimpleAuth set to true or false during calls to indicate if
* a secure client falls back to simple auth
* @return the proxy
* @throws IOException if any error occurs
*/
public static <T> ProtocolProxy<T> getProtocolProxy(Class<T> protocol,
long clientVersion,
InetSocketAddress addr,
UserGroupInformation ticket,
Configuration conf,
SocketFactory factory,
int rpcTimeout,
RetryPolicy connectionRetryPolicy,
AtomicBoolean fallbackToSimpleAuth)
throws IOException {
if (UserGroupInformation.isSecurityEnabled()) {
SaslRpcServer.init(conf);
}
return getProtocolEngine(protocol, conf).getProxy(protocol, clientVersion,
addr, ticket, conf, factory, rpcTimeout, connectionRetryPolicy,
fallbackToSimpleAuth);
}
/**
* Construct a client-side proxy object with the default SocketFactory
* @param <T>
*
* @param protocol
* @param clientVersion
* @param addr
* @param conf
* @return a proxy instance
* @throws IOException
*/
public static <T> T getProxy(Class<T> protocol,
long clientVersion,
InetSocketAddress addr, Configuration conf)
throws IOException {
return getProtocolProxy(protocol, clientVersion, addr, conf).getProxy();
}
/**
* Returns the server address for a given proxy.
*/
public static InetSocketAddress getServerAddress(Object proxy) {
return getConnectionIdForProxy(proxy).getAddress();
}
/**
* Return the connection ID of the given object. If the provided object is in
* fact a protocol translator, we'll get the connection ID of the underlying
* proxy object.
*
* @param proxy the proxy object to get the connection ID of.
* @return the connection ID for the provided proxy object.
*/
public static ConnectionId getConnectionIdForProxy(Object proxy) {
if (proxy instanceof ProtocolTranslator) {
proxy = ((ProtocolTranslator)proxy).getUnderlyingProxyObject();
}
RpcInvocationHandler inv = (RpcInvocationHandler) Proxy
.getInvocationHandler(proxy);
return inv.getConnectionId();
}
/**
* Get a protocol proxy that contains a proxy connection to a remote server
* and a set of methods that are supported by the server
*
* @param protocol
* @param clientVersion
* @param addr
* @param conf
* @return a protocol proxy
* @throws IOException
*/
public static <T> ProtocolProxy<T> getProtocolProxy(Class<T> protocol,
long clientVersion,
InetSocketAddress addr, Configuration conf)
throws IOException {
return getProtocolProxy(protocol, clientVersion, addr, conf, NetUtils
.getDefaultSocketFactory(conf));
}
/**
* Stop the proxy. Proxy must either implement {@link Closeable} or must have
* associated {@link RpcInvocationHandler}.
*
* @param proxy
* the RPC proxy object to be stopped
* @throws HadoopIllegalArgumentException
* if the proxy does not implement {@link Closeable} interface or
* does not have closeable {@link InvocationHandler}
*/
public static void stopProxy(Object proxy) {
if (proxy == null) {
throw new HadoopIllegalArgumentException(
"Cannot close proxy since it is null");
}
try {
if (proxy instanceof Closeable) {
((Closeable) proxy).close();
return;
} else {
InvocationHandler handler = Proxy.getInvocationHandler(proxy);
if (handler instanceof Closeable) {
((Closeable) handler).close();
return;
}
}
} catch (IOException e) {
LOG.error("Closing proxy or invocation handler caused exception", e);
} catch (IllegalArgumentException e) {
LOG.error("RPC.stopProxy called on non proxy: class=" + proxy.getClass().getName(), e);
}
// If you see this error on a mock object in a unit test you're
// developing, make sure to use MockitoUtil.mockProtocol() to
// create your mock.
throw new HadoopIllegalArgumentException(
"Cannot close proxy - is not Closeable or "
+ "does not provide closeable invocation handler "
+ proxy.getClass());
}
/**
* Class to construct instances of RPC server with specific options.
*/
public static class Builder {
private Class<?> protocol = null;
private Object instance = null;
private String bindAddress = "0.0.0.0";
private int port = 0;
private int numHandlers = 1;
private int numReaders = -1;
private int queueSizePerHandler = -1;
private boolean verbose = false;
private final Configuration conf;
private SecretManager<? extends TokenIdentifier> secretManager = null;
private String portRangeConfig = null;
public Builder(Configuration conf) {
this.conf = conf;
}
/** Mandatory field */
public Builder setProtocol(Class<?> protocol) {
this.protocol = protocol;
return this;
}
/** Mandatory field */
public Builder setInstance(Object instance) {
this.instance = instance;
return this;
}
/** Default: 0.0.0.0 */
public Builder setBindAddress(String bindAddress) {
this.bindAddress = bindAddress;
return this;
}
/** Default: 0 */
public Builder setPort(int port) {
this.port = port;
return this;
}
/** Default: 1 */
public Builder setNumHandlers(int numHandlers) {
this.numHandlers = numHandlers;
return this;
}
/** Default: -1 */
public Builder setnumReaders(int numReaders) {
this.numReaders = numReaders;
return this;
}
/** Default: -1 */
public Builder setQueueSizePerHandler(int queueSizePerHandler) {
this.queueSizePerHandler = queueSizePerHandler;
return this;
}
/** Default: false */
public Builder setVerbose(boolean verbose) {
this.verbose = verbose;
return this;
}
/** Default: null */
public Builder setSecretManager(
SecretManager<? extends TokenIdentifier> secretManager) {
this.secretManager = secretManager;
return this;
}
/** Default: null */
public Builder setPortRangeConfig(String portRangeConfig) {
this.portRangeConfig = portRangeConfig;
return this;
}
/**
* Build the RPC Server.
* @throws IOException on error
* @throws HadoopIllegalArgumentException when mandatory fields are not set
*/
public Server build() throws IOException, HadoopIllegalArgumentException {
if (this.conf == null) {
throw new HadoopIllegalArgumentException("conf is not set");
}
if (this.protocol == null) {
throw new HadoopIllegalArgumentException("protocol is not set");
}
if (this.instance == null) {
throw new HadoopIllegalArgumentException("instance is not set");
}
return getProtocolEngine(this.protocol, this.conf).getServer(
this.protocol, this.instance, this.bindAddress, this.port,
this.numHandlers, this.numReaders, this.queueSizePerHandler,
this.verbose, this.conf, this.secretManager, this.portRangeConfig);
}
}
/** An RPC Server. */
public abstract static class Server extends org.apache.hadoop.ipc.Server {
boolean verbose;
static String classNameBase(String className) {
String[] names = className.split("\\.", -1);
if (names == null || names.length == 0) {
return className;
}
return names[names.length-1];
}
/**
* Store a map of protocol and version to its implementation
*/
/**
* The key in Map
*/
static class ProtoNameVer {
final String protocol;
final long version;
ProtoNameVer(String protocol, long ver) {
this.protocol = protocol;
this.version = ver;
}
@Override
public boolean equals(Object o) {
if (o == null)
return false;
if (this == o)
return true;
if (! (o instanceof ProtoNameVer))
return false;
ProtoNameVer pv = (ProtoNameVer) o;
return ((pv.protocol.equals(this.protocol)) &&
(pv.version == this.version));
}
@Override
public int hashCode() {
return protocol.hashCode() * 37 + (int) version;
}
}
/**
* The value in map
*/
static class ProtoClassProtoImpl {
final Class<?> protocolClass;
final Object protocolImpl;
ProtoClassProtoImpl(Class<?> protocolClass, Object protocolImpl) {
this.protocolClass = protocolClass;
this.protocolImpl = protocolImpl;
}
}
ArrayList<Map<ProtoNameVer, ProtoClassProtoImpl>> protocolImplMapArray =
new ArrayList<Map<ProtoNameVer, ProtoClassProtoImpl>>(RpcKind.MAX_INDEX);
Map<ProtoNameVer, ProtoClassProtoImpl> getProtocolImplMap(RPC.RpcKind rpcKind) {
if (protocolImplMapArray.size() == 0) {// initialize for all rpc kinds
for (int i=0; i <= RpcKind.MAX_INDEX; ++i) {
protocolImplMapArray.add(
new HashMap<ProtoNameVer, ProtoClassProtoImpl>(10));
}
}
return protocolImplMapArray.get(rpcKind.ordinal());
}
// Register protocol and its impl for rpc calls
void registerProtocolAndImpl(RpcKind rpcKind, Class<?> protocolClass,
Object protocolImpl) {
String protocolName = RPC.getProtocolName(protocolClass);
long version;
try {
version = RPC.getProtocolVersion(protocolClass);
} catch (Exception ex) {
LOG.warn("Protocol " + protocolClass +
" NOT registered as cannot get protocol version ");
return;
}
getProtocolImplMap(rpcKind).put(new ProtoNameVer(protocolName, version),
new ProtoClassProtoImpl(protocolClass, protocolImpl));
if (LOG.isDebugEnabled()) {
LOG.debug("RpcKind = " + rpcKind + " Protocol Name = " + protocolName +
" version=" + version +
" ProtocolImpl=" + protocolImpl.getClass().getName() +
" protocolClass=" + protocolClass.getName());
}
}
static class VerProtocolImpl {
final long version;
final ProtoClassProtoImpl protocolTarget;
VerProtocolImpl(long ver, ProtoClassProtoImpl protocolTarget) {
this.version = ver;
this.protocolTarget = protocolTarget;
}
}
VerProtocolImpl[] getSupportedProtocolVersions(RPC.RpcKind rpcKind,
String protocolName) {
VerProtocolImpl[] resultk =
new VerProtocolImpl[getProtocolImplMap(rpcKind).size()];
int i = 0;
for (Map.Entry<ProtoNameVer, ProtoClassProtoImpl> pv :
getProtocolImplMap(rpcKind).entrySet()) {
if (pv.getKey().protocol.equals(protocolName)) {
resultk[i++] =
new VerProtocolImpl(pv.getKey().version, pv.getValue());
}
}
if (i == 0) {
return null;
}
VerProtocolImpl[] result = new VerProtocolImpl[i];
System.arraycopy(resultk, 0, result, 0, i);
return result;
}
VerProtocolImpl getHighestSupportedProtocol(RpcKind rpcKind,
String protocolName) {
Long highestVersion = 0L;
ProtoClassProtoImpl highest = null;
if (LOG.isDebugEnabled()) {
LOG.debug("Size of protoMap for " + rpcKind + " ="
+ getProtocolImplMap(rpcKind).size());
}
for (Map.Entry<ProtoNameVer, ProtoClassProtoImpl> pv :
getProtocolImplMap(rpcKind).entrySet()) {
if (pv.getKey().protocol.equals(protocolName)) {
if ((highest == null) || (pv.getKey().version > highestVersion)) {
highest = pv.getValue();
highestVersion = pv.getKey().version;
}
}
}
if (highest == null) {
return null;
}
return new VerProtocolImpl(highestVersion, highest);
}
protected Server(String bindAddress, int port,
Class<? extends Writable> paramClass, int handlerCount,
int numReaders, int queueSizePerHandler,
Configuration conf, String serverName,
SecretManager<? extends TokenIdentifier> secretManager,
String portRangeConfig) throws IOException {
super(bindAddress, port, paramClass, handlerCount, numReaders, queueSizePerHandler,
conf, serverName, secretManager, portRangeConfig);
initProtocolMetaInfo(conf);
}
private void initProtocolMetaInfo(Configuration conf) {
RPC.setProtocolEngine(conf, ProtocolMetaInfoPB.class,
ProtobufRpcEngine.class);
ProtocolMetaInfoServerSideTranslatorPB xlator =
new ProtocolMetaInfoServerSideTranslatorPB(this);
BlockingService protocolInfoBlockingService = ProtocolInfoService
.newReflectiveBlockingService(xlator);
addProtocol(RpcKind.RPC_PROTOCOL_BUFFER, ProtocolMetaInfoPB.class,
protocolInfoBlockingService);
}
/**
* Add a protocol to the existing server.
* @param protocolClass - the protocol class
* @param protocolImpl - the impl of the protocol that will be called
* @return the server (for convenience)
*/
public Server addProtocol(RpcKind rpcKind, Class<?> protocolClass,
Object protocolImpl) {
registerProtocolAndImpl(rpcKind, protocolClass, protocolImpl);
return this;
}
@Override
public Writable call(RPC.RpcKind rpcKind, String protocol,
Writable rpcRequest, long receiveTime) throws Exception {
return getRpcInvoker(rpcKind).call(this, protocol, rpcRequest,
receiveTime);
}
}
}
| apache-2.0 |
andreagenso/java2scala | test/J2s/java/openjdk-6-src-b27/jdk/src/share/classes/javax/swing/LookAndFeel.java | 30437 | /*
* Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing;
import java.awt.Font;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.awt.Color;
import java.awt.Component;
import java.awt.SystemColor;
import java.awt.Toolkit;
import javax.swing.text.*;
import javax.swing.border.*;
import javax.swing.plaf.*;
import java.net.URL;
import sun.swing.SwingUtilities2;
import sun.swing.DefaultLayoutStyle;
import sun.swing.ImageIconUIResource;
import java.util.StringTokenizer;
/**
* {@code LookAndFeel}, as the name implies, encapsulates a look and
* feel. Beyond installing a look and feel most developers never need to
* interact directly with {@code LookAndFeel}. In general only developers
* creating a custom look and feel need to concern themselves with this class.
* <p>
* Swing is built upon the foundation that each {@code JComponent}
* subclass has an implementation of a specific {@code ComponentUI}
* subclass. The {@code ComponentUI} is often referred to as "the ui",
* "component ui", or "look and feel delegate". The {@code ComponentUI}
* subclass is responsible for providing the look and feel specific
* functionality of the component. For example, {@code JTree} requires
* an implementation of the {@code ComponentUI} subclass {@code
* TreeUI}. The implementation of the specific {@code
* ComponentUI} subclass is provided by the {@code LookAndFeel}. Each
* {@code JComponent} subclass identifies the {@code ComponentUI}
* subclass it requires by way of the {@code JComponent} method {@code
* getUIClassID}.
* <p>
* Each {@code LookAndFeel} implementation must provide
* an implementation of the appropriate {@code ComponentUI} subclass by
* specifying a value for each of Swing's ui class ids in the {@code
* UIDefaults} object returned from {@code getDefaults}. For example,
* {@code BasicLookAndFeel} uses {@code BasicTreeUI} as the concrete
* implementation for {@code TreeUI}. This is accomplished by {@code
* BasicLookAndFeel} providing the key-value pair {@code
* "TreeUI"-"javax.swing.plaf.basic.BasicTreeUI"}, in the
* {@code UIDefaults} returned from {@code getDefaults}. Refer to
* {@link UIDefaults#getUI(JComponent)} for defails on how the implementation
* of the {@code ComponentUI} subclass is obtained.
* <p>
* When a {@code LookAndFeel} is installed the {@code UIManager} does
* not check that an entry exists for all ui class ids. As such,
* random exceptions will occur if the current look and feel has not
* provided a value for a particular ui class id and an instance of
* the {@code JComponent} subclass is created.
*
* <h2>Recommendations for Look and Feels</h2>
*
* As noted in {@code UIManager} each {@code LookAndFeel} has the opportunity
* to provide a set of defaults that are layered in with developer and
* system defaults. Some of Swing's components require the look and feel
* to provide a specific set of defaults. These are documented in the
* classes that require the specific default.
*
* <h3><a name="#defaultRecommendation">ComponentUIs and defaults</a></h2>
*
* All {@code ComponentUIs} typically need to set various properties
* on the {@code JComponent} the {@code ComponentUI} is providing the
* look and feel for. This is typically done when the {@code
* ComponentUI} is installed on the {@code JComponent}. Setting a
* property should only be done if the developer has not set the
* property. For non-primitive values it is recommended that the
* {@code ComponentUI} only change the property on the {@code
* JComponent} if the current value is {@code null} or implements
* {@code UIResource}. If the current value is {@code null} or
* implements {@code UIResource} it indicates the property has not
* been set by the developer, and the ui is free to change it. For
* example, {@code BasicButtonUI.installDefaults} only changes the
* font on the {@code JButton} if the return value from {@code
* button.getFont()} is {@code null} or implements {@code
* UIResource}. On the other hand if {@code button.getFont()} returned
* a {@code non-null} value that did not implement {@code UIResource}
* then {@code BasicButtonUI.installDefaults} would not change the
* {@code JButton}'s font.
* <p>
* For primitive values, such as {@code opaque}, the method {@code
* installProperty} should be invoked. {@code installProperty} only changes
* the correspoding property if the value has not been changed by the
* developer.
* <p>
* {@code ComponentUI} implementations should use the various install methods
* provided by this class as they handle the necessary checking and install
* the property using the recommended guidelines.
* <p>
* <h3><a name="exceptions"></a>Exceptions</h3>
*
* All of the install methods provided by {@code LookAndFeel} need to
* access the defaults if the value of the property being changed is
* {@code null} or a {@code UIResource}. For example, installing the
* font does the following:
* <pre>
* JComponent c;
* Font font = c.getFont();
* if (font == null || (font instanceof UIResource)) {
* c.setFont(UIManager.getFont("fontKey"));
* }
* </pre>
* If the font is {@code null} or a {@code UIResource}, the
* defaults table is queried with the key {@code fontKey}. All of
* {@code UIDefault's} get methods throw a {@code
* NullPointerException} if passed in {@code null}. As such, unless
* otherwise noted each of the various install methods of {@code
* LookAndFeel} throw a {@code NullPointerException} if the current
* value is {@code null} or a {@code UIResource} and the supplied
* defaults key is {@code null}. In addition, unless otherwise specified
* all of the {@code install} methods throw a {@code NullPointerException} if
* a {@code null} component is passed in.
*
* @author Tom Ball
* @author Hans Muller
*/
public abstract class LookAndFeel
{
/**
* Convenience method for setting a component's foreground
* and background color properties with values from the
* defaults. The properties are only set if the current
* value is either {@code null} or a {@code UIResource}.
*
* @param c component to set the colors on
* @param defaultBgName key for the background
* @param defaultFgName key for the foreground
*
* @see #installColorsAndFont
* @see UIManager#getColor
* @throws NullPointerException as described in
* <a href="#exceptions">exceptions</a>
*/
public static void installColors(JComponent c,
String defaultBgName,
String defaultFgName)
{
Color bg = c.getBackground();
if (bg == null || bg instanceof UIResource) {
c.setBackground(UIManager.getColor(defaultBgName));
}
Color fg = c.getForeground();
if (fg == null || fg instanceof UIResource) {
c.setForeground(UIManager.getColor(defaultFgName));
}
}
/**
* Convenience method for setting a component's foreground,
* background and font properties with values from the
* defaults. The properties are only set if the current
* value is either {@code null} or a {@code UIResource}.
*
* @param c component set to the colors and font on
* @param defaultBgName key for the background
* @param defaultFgName key for the foreground
* @param defaultFontName key for the font
* @throws NullPointerException as described in
* <a href="#exceptions">exceptions</a>
*
* @see #installColors
* @see UIManager#getColor
* @see UIManager#getFont
*/
public static void installColorsAndFont(JComponent c,
String defaultBgName,
String defaultFgName,
String defaultFontName) {
Font f = c.getFont();
if (f == null || f instanceof UIResource) {
c.setFont(UIManager.getFont(defaultFontName));
}
installColors(c, defaultBgName, defaultFgName);
}
/**
* Convenience method for setting a component's border property with
* a value from the defaults. The border is only set if the border is
* {@code null} or an instance of {@code UIResource}.
*
* @param c component to set the border on
* @param defaultBorderName key specifying the border
* @throws NullPointerException as described in
* <a href="#exceptions">exceptions</a>
*/
public static void installBorder(JComponent c, String defaultBorderName) {
Border b = c.getBorder();
if (b == null || b instanceof UIResource) {
c.setBorder(UIManager.getBorder(defaultBorderName));
}
}
/**
* Convenience method for uninstalling a border. If the border of
* the component is a {@code UIResource}, it is set to {@code
* null}.
*
* @param c component to uninstall the border on
* @throws NullPointerException if {@code c} is {@code null}
*/
public static void uninstallBorder(JComponent c) {
if (c.getBorder() instanceof UIResource) {
c.setBorder(null);
}
}
/**
* Convenience method for installing a property with the specified name
* and value on a component if that property has not already been set
* by the developer. This method is intended to be used by
* ui delegate instances that need to specify a default value for a
* property of primitive type (boolean, int, ..), but do not wish
* to override a value set by the client. Since primitive property
* values cannot be wrapped with the {@code UIResource} marker, this method
* uses private state to determine whether the property has been set
* by the client.
*
* @throws IllegalArgumentException if the specified property is not
* one which can be set using this method
* @throws ClassCastException if the property value has not been set
* by the developer and the type does not match the property's type
* @throws NullPointerException if {@code c} is {@code null}, or the
* named property has not been set by the developer and
* {@code propertyValue} is {@code null}
* @param c target component to set the property on
* @param propertyName name of the property to set
* @param propertyValue value of the property
* @since 1.5
*/
public static void installProperty(JComponent c,
String propertyName, Object propertyValue) {
// this is a special case because the JPasswordField's ancestor heirarchy
// includes a class outside of javax.swing, thus we cannot call setUIProperty
// directly.
if (c instanceof JPasswordField) {
if (!((JPasswordField)c).customSetUIProperty(propertyName, propertyValue)) {
c.setUIProperty(propertyName, propertyValue);
}
} else {
c.setUIProperty(propertyName, propertyValue);
}
}
/**
* Convenience method for building an array of {@code
* KeyBindings}. While this method is not deprecated, developers
* should instead use {@code ActionMap} and {@code InputMap} for
* supplying key bindings.
* <p>
* This method returns an array of {@code KeyBindings}, one for each
* alternating {@code key-action} pair in {@code keyBindingList}.
* A {@code key} can either be a {@code String} in the format
* specified by the <code>KeyStroke.getKeyStroke</code> method, or
* a {@code KeyStroke}. The {@code action} part of the pair is a
* {@code String} that corresponds to the name of the {@code
* Action}.
* <p>
* The following example illustrates creating a {@code KeyBinding} array
* from six alternating {@code key-action} pairs:
* <pre>
* JTextComponent.KeyBinding[] multilineBindings = makeKeyBindings( new Object[] {
* "UP", DefaultEditorKit.upAction,
* "DOWN", DefaultEditorKit.downAction,
* "PAGE_UP", DefaultEditorKit.pageUpAction,
* "PAGE_DOWN", DefaultEditorKit.pageDownAction,
* "ENTER", DefaultEditorKit.insertBreakAction,
* "TAB", DefaultEditorKit.insertTabAction
* });
* </pre>
* If {@code keyBindingList's} length is odd, the last element is
* ignored.
* <p>
* Supplying a {@code null} value for either the {@code key} or
* {@code action} part of the {@code key-action} pair results in
* creating a {@code KeyBinding} with the corresponding value
* {@code null}. As other parts of Swing's expect {@code non-null} values
* in a {@code KeyBinding}, you should avoid supplying {@code null} as
* either the {@code key} or {@code action} part of the {@code key-action}
* pair.
*
* @param keyBindingList an array of {@code key-action} pairs
* @return an array of {@code KeyBindings}
* @throws NullPointerException if {@code keyBindingList} is {@code null}
* @throws ClassCastException if the {@code key} part of the pair is
* not a {@code KeyStroke} or {@code String}, or the
* {@code action} part of the pair is not a {@code String}
* @see ActionMap
* @see InputMap
* @see KeyStroke#getKeyStroke
*/
public static JTextComponent.KeyBinding[] makeKeyBindings(Object[] keyBindingList)
{
JTextComponent.KeyBinding[] rv = new JTextComponent.KeyBinding[keyBindingList.length / 2];
for(int i = 0; i < keyBindingList.length; i += 2) {
KeyStroke keystroke = (keyBindingList[i] instanceof KeyStroke)
? (KeyStroke)keyBindingList[i]
: KeyStroke.getKeyStroke((String)keyBindingList[i]);
String action = (String)keyBindingList[i+1];
rv[i / 2] = new JTextComponent.KeyBinding(keystroke, action);
}
return rv;
}
/**
* Creates a {@code InputMapUIResource} from <code>keys</code>. This is
* a convenience method for creating a new {@code InputMapUIResource},
* invoking {@code loadKeyBindings(map, keys)}, and returning the
* {@code InputMapUIResource}.
*
* @param keys alternating pairs of {@code keystroke-action key}
* pairs as described in {@link #loadKeyBindings}
* @return newly created and populated {@code InputMapUIResource}
* @see #loadKeyBindings
*
* @since 1.3
*/
public static InputMap makeInputMap(Object[] keys) {
InputMap retMap = new InputMapUIResource();
loadKeyBindings(retMap, keys);
return retMap;
}
/**
* Creates a {@code ComponentInputMapUIResource} from
* <code>keys</code>. This is a convenience method for creating a
* new {@code ComponentInputMapUIResource}, invoking {@code
* loadKeyBindings(map, keys)}, and returning the {@code
* ComponentInputMapUIResource}.
*
* @param c component to create the {@code ComponentInputMapUIResource}
* with
* @param keys alternating pairs of {@code keystroke-action key}
* pairs as described in {@link #loadKeyBindings}
* @return newly created and populated {@code InputMapUIResource}
* @throws IllegalArgumentException if {@code c} is {@code null}
*
* @see #loadKeyBindings
* @see ComponentInputMapUIResource
*
* @since 1.3
*/
public static ComponentInputMap makeComponentInputMap(JComponent c,
Object[] keys) {
ComponentInputMap retMap = new ComponentInputMapUIResource(c);
loadKeyBindings(retMap, keys);
return retMap;
}
/**
* Populates an {@code InputMap} with the specified bindings.
* The bindings are supplied as a list of alternating
* {@code keystroke-action key} pairs. The {@code keystroke} is either
* an instance of {@code KeyStroke}, or a {@code String}
* that identifies the {@code KeyStroke} for the binding. Refer
* to {@code KeyStroke.getKeyStroke(String)} for the specific
* format. The {@code action key} part of the pair is the key
* registered in the {@code InputMap} for the {@code KeyStroke}.
* <p>
* The following illustrates loading an {@code InputMap} with two
* {@code key-action} pairs:
* <pre>
* LookAndFeel.loadKeyBindings(inputMap, new Object[] {
* "control X", "cut",
* "control V", "paste"
* });
* </pre>
* <p>
* Supplying a {@code null} list of bindings ({@code keys}) does not
* change {@code retMap} in any way.
* <p>
* Specifying a {@code null} {@code action key} results in
* removing the {@code keystroke's} entry from the {@code InputMap}.
* A {@code null} {@code keystroke} is ignored.
*
* @param retMap {@code InputMap} to add the {@code key-action}
* pairs to
* @param keys bindings to add to {@code retMap}
* @throws NullPointerException if {@code keys} is
* {@code non-null}, not empty, and {@code retMap} is
* {@code null}
*
* @see KeyStroke#getKeyStroke(String)
* @see InputMap
*
* @since 1.3
*/
public static void loadKeyBindings(InputMap retMap, Object[] keys) {
if (keys != null) {
for (int counter = 0, maxCounter = keys.length;
counter < maxCounter; counter++) {
Object keyStrokeO = keys[counter++];
KeyStroke ks = (keyStrokeO instanceof KeyStroke) ?
(KeyStroke)keyStrokeO :
KeyStroke.getKeyStroke((String)keyStrokeO);
retMap.put(ks, keys[counter]);
}
}
}
/**
* Creates and returns a {@code UIDefault.LazyValue} that loads an
* image. The returned value is an implementation of {@code
* UIDefaults.LazyValue}. When {@code createValue} is invoked on
* the returned object, the image is loaded. If the image is {@code
* non-null}, it is then wrapped in an {@code Icon} that implements {@code
* UIResource}. The image is loaded using {@code
* Class.getResourceAsStream(gifFile)}.
* <p>
* This method does not check the arguments in any way. It is
* strongly recommended that {@code non-null} values are supplied else
* exceptions may occur when {@code createValue} is invoked on the
* returned object.
*
* @param baseClass {@code Class} used to load the resource
* @param gifFile path to the image to load
* @return a {@code UIDefaults.LazyValue}; when resolved the
* {@code LazyValue} loads the specified image
* @see UIDefaults.LazyValue
* @see Icon
* @see Class#getResourceAsStream(String)
*/
public static Object makeIcon(final Class<?> baseClass, final String gifFile) {
return SwingUtilities2.makeIcon(baseClass, baseClass, gifFile);
}
/**
* Returns the <code>LayoutStyle</code> for this look
* and feel. This never returns {@code null}.
* <p>
* You generally don't use the <code>LayoutStyle</code> from
* the look and feel, instead use the <code>LayoutStyle</code>
* method <code>getInstance</code>.
*
* @see LayoutStyle#getInstance
* @return the <code>LayoutStyle</code> for this look and feel
* @since 1.6
*/
public LayoutStyle getLayoutStyle() {
return DefaultLayoutStyle.getInstance();
}
/**
* Invoked when the user attempts an invalid operation,
* such as pasting into an uneditable <code>JTextField</code>
* that has focus. The default implementation beeps. Subclasses
* that wish different behavior should override this and provide
* the additional feedback.
*
* @param component the <code>Component</code> the error occurred in,
* may be <code>null</code>
* indicating the error condition is not directly
* associated with a <code>Component</code>
* @since 1.4
*/
public void provideErrorFeedback(Component component) {
Toolkit toolkit = null;
if (component != null) {
toolkit = component.getToolkit();
} else {
toolkit = Toolkit.getDefaultToolkit();
}
toolkit.beep();
} // provideErrorFeedback()
/**
* Returns the value of the specified system desktop property by
* invoking <code>Toolkit.getDefaultToolkit().getDesktopProperty()</code>.
* If the value of the specified property is {@code null},
* {@code fallbackValue} is returned.
*
* @param systemPropertyName the name of the system desktop property being queried
* @param fallbackValue the object to be returned as the value if the system value is null
* @return the current value of the desktop property
*
* @see java.awt.Toolkit#getDesktopProperty
*
* @since 1.4
*/
public static Object getDesktopPropertyValue(String systemPropertyName, Object fallbackValue) {
Object value = Toolkit.getDefaultToolkit().getDesktopProperty(systemPropertyName);
if (value == null) {
return fallbackValue;
} else if (value instanceof Color) {
return new ColorUIResource((Color)value);
} else if (value instanceof Font) {
return new FontUIResource((Font)value);
}
return value;
}
/**
* Returns an <code>Icon</code> with a disabled appearance.
* This method is used to generate a disabled <code>Icon</code> when
* one has not been specified. For example, if you create a
* <code>JButton</code> and only specify an <code>Icon</code> via
* <code>setIcon</code> this method will be called to generate the
* disabled <code>Icon</code>. If {@code null} is passed as
* <code>icon</code> this method returns {@code null}.
* <p>
* Some look and feels might not render the disabled {@code Icon}, in which
* case they will ignore this.
*
* @param component {@code JComponent} that will display the {@code Icon},
* may be {@code null}
* @param icon {@code Icon} to generate the disabled icon from
* @return disabled {@code Icon}, or {@code null} if a suitable
* {@code Icon} can not be generated
* @since 1.5
*/
public Icon getDisabledIcon(JComponent component, Icon icon) {
if (icon instanceof ImageIcon) {
return new ImageIconUIResource(GrayFilter.
createDisabledImage(((ImageIcon)icon).getImage()));
}
return null;
}
/**
* Returns an <code>Icon</code> for use by disabled
* components that are also selected. This method is used to generate an
* <code>Icon</code> for components that are in both the disabled and
* selected states but do not have a specific <code>Icon</code> for this
* state. For example, if you create a <code>JButton</code> and only
* specify an <code>Icon</code> via <code>setIcon</code> this method
* will be called to generate the disabled and selected
* <code>Icon</code>. If {@code null} is passed as <code>icon</code> this
* methods returns {@code null}.
* <p>
* Some look and feels might not render the disabled and selected
* {@code Icon}, in which case they will ignore this.
*
* @param component {@code JComponent} that will display the {@code Icon},
* may be {@code null}
* @param icon {@code Icon} to generate disabled and selected icon from
* @return disabled and selected icon, or {@code null} if a suitable
* {@code Icon} can not be generated.
* @since 1.5
*/
public Icon getDisabledSelectedIcon(JComponent component, Icon icon) {
return getDisabledIcon(component, icon);
}
/**
* Return a short string that identifies this look and feel, e.g.
* "CDE/Motif". This string should be appropriate for a menu item.
* Distinct look and feels should have different names, e.g.
* a subclass of MotifLookAndFeel that changes the way a few components
* are rendered should be called "CDE/Motif My Way"; something
* that would be useful to a user trying to select a L&F from a list
* of names.
*
* @return short identifier for the look and feel
*/
public abstract String getName();
/**
* Return a string that identifies this look and feel. This string
* will be used by applications/services that want to recognize
* well known look and feel implementations. Presently
* the well known names are "Motif", "Windows", "Mac", "Metal". Note
* that a LookAndFeel derived from a well known superclass
* that doesn't make any fundamental changes to the look or feel
* shouldn't override this method.
*
* @return identifier for the look and feel
*/
public abstract String getID();
/**
* Return a one line description of this look and feel implementation,
* e.g. "The CDE/Motif Look and Feel". This string is intended for
* the user, e.g. in the title of a window or in a ToolTip message.
*
* @return short description for the look and feel
*/
public abstract String getDescription();
/**
* Returns {@code true} if the <code>LookAndFeel</code> returned
* <code>RootPaneUI</code> instances support providing {@code Window}
* decorations in a <code>JRootPane</code>.
* <p>
* The default implementation returns {@code false}, subclasses that
* support {@code Window} decorations should override this and return
* {@code true}.
*
* @return {@code true} if the {@code RootPaneUI} instances created by
* this look and feel support client side decorations
* @see JDialog#setDefaultLookAndFeelDecorated
* @see JFrame#setDefaultLookAndFeelDecorated
* @see JRootPane#setWindowDecorationStyle
* @since 1.4
*/
public boolean getSupportsWindowDecorations() {
return false;
}
/**
* If the underlying platform has a "native" look and feel, and
* this is an implementation of it, return {@code true}. For
* example, when the underlying platform is Solaris running CDE
* a CDE/Motif look and feel implementation would return {@code
* true}.
*
* @return {@code true} if this look and feel represents the underlying
* platform look and feel
*/
public abstract boolean isNativeLookAndFeel();
/**
* Return {@code true} if the underlying platform supports and or permits
* this look and feel. This method returns {@code false} if the look
* and feel depends on special resources or legal agreements that
* aren't defined for the current platform.
*
*
* @return {@code true} if this is a supported look and feel
* @see UIManager#setLookAndFeel
*/
public abstract boolean isSupportedLookAndFeel();
/**
* Initializes the look and feel. While this method is public,
* it should only be invoked by the {@code UIManager} when a
* look and feel is installed as the current look and feel. This
* method is invoked before the {@code UIManager} invokes
* {@code getDefaults}. This method is intended to perform any
* initialization for the look and feel. Subclasses
* should do any one-time setup they need here, rather than
* in a static initializer, because look and feel class objects
* may be loaded just to discover that {@code isSupportedLookAndFeel()}
* returns {@code false}.
*
* @see #uninitialize
* @see UIManager#setLookAndFeel
*/
public void initialize() {
}
/**
* Uninitializes the look and feel. While this method is public,
* it should only be invoked by the {@code UIManager} when
* the look and feel is uninstalled. For example,
* {@code UIManager.setLookAndFeel} invokes this when the look and
* feel is changed.
* <p>
* Subclasses may choose to free up some resources here.
*
* @see #initialize
* @see UIManager#setLookAndFeel
*/
public void uninitialize() {
}
/**
* Returns the look and feel defaults. While this method is public,
* it should only be invoked by the {@code UIManager} when the
* look and feel is set as the current look and feel and after
* {@code initialize} has been invoked.
*
* @return the look and feel defaults
* @see #initialize
* @see #uninitialize
* @see UIManager#setLookAndFeel
*/
public UIDefaults getDefaults() {
return null;
}
/**
* Returns a string that displays and identifies this
* object's properties.
*
* @return a String representation of this object
*/
public String toString() {
return "[" + getDescription() + " - " + getClass().getName() + "]";
}
}
| apache-2.0 |
stillalex/jackrabbit-oak | oak-auth-external/src/test/java/org/apache/jackrabbit/oak/spi/security/authentication/external/basic/RepExternalIdTest.java | 5771 | /*
* 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.jackrabbit.oak.spi.security.authentication.external.basic;
import org.apache.jackrabbit.api.security.user.Authorizable;
import org.apache.jackrabbit.api.security.user.UserManager;
import org.apache.jackrabbit.oak.api.CommitFailedException;
import org.apache.jackrabbit.oak.api.PropertyState;
import org.apache.jackrabbit.oak.api.Root;
import org.apache.jackrabbit.oak.api.Tree;
import org.apache.jackrabbit.oak.api.Type;
import org.apache.jackrabbit.oak.spi.security.authentication.external.AbstractExternalAuthTest;
import org.apache.jackrabbit.oak.spi.security.authentication.external.ExternalIdentityRef;
import org.apache.jackrabbit.oak.spi.security.authentication.external.SyncResult;
import org.apache.jackrabbit.oak.spi.security.authentication.external.SyncedIdentity;
import org.jetbrains.annotations.NotNull;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class RepExternalIdTest extends AbstractExternalAuthTest {
private Root r;
private UserManager userManager;
private DefaultSyncContext syncCtx;
@Before
public void before() throws Exception {
super.before();
r = getSystemRoot();
userManager = getUserManager(r);
syncCtx = new DefaultSyncContext(syncConfig, idp, getUserManager(r), getValueFactory(r));
}
@Override
public void after() throws Exception {
try {
syncCtx.close();
} finally {
super.after();
}
}
private void assertRepExternalId(@NotNull SyncResult result) throws Exception {
assertSame(SyncResult.Status.ADD, result.getStatus());
SyncedIdentity si = result.getIdentity();
assertNotNull(si);
Authorizable authorizable = userManager.getAuthorizable(si.getId());
assertNotNull(authorizable);
Tree userTree = r.getTree(authorizable.getPath());
assertTrue(userTree.hasProperty(DefaultSyncContext.REP_EXTERNAL_ID));
PropertyState ps = userTree.getProperty(DefaultSyncContext.REP_EXTERNAL_ID);
assertNotNull(ps);
assertFalse(ps.isArray());
assertSame(Type.STRING, ps.getType());
assertEquals(si.getExternalIdRef(), ExternalIdentityRef.fromString(ps.getValue(Type.STRING)));
}
@Test
public void syncExternalUser() throws Exception {
SyncResult res = syncCtx.sync(idp.getUser(USER_ID));
assertRepExternalId(res);
}
@Test
public void syncExternalGroup() throws Exception {
SyncResult res = syncCtx.sync(idp.listGroups().next());
assertRepExternalId(res);
}
@Test
public void testUniqueConstraint() throws Exception {
SyncResult res = syncCtx.sync(idp.getUser(USER_ID));
try {
Tree t = r.getTree(getTestUser().getPath());
t.setProperty(DefaultSyncContext.REP_EXTERNAL_ID, res.getIdentity().getExternalIdRef().getString());
r.commit();
fail("Duplicate value for rep:externalId must be detected in the default setup.");
} catch (CommitFailedException e) {
// success: verify nature of the exception
assertTrue(e.isConstraintViolation());
assertEquals(30, e.getCode());
} finally {
r.refresh();
}
}
@Test
public void testUniqueConstraintSubsequentCommit() throws Exception {
SyncResult res = syncCtx.sync(idp.getUser(USER_ID));
r.commit();
try {
Tree t = r.getTree(getTestUser().getPath());
t.setProperty(DefaultSyncContext.REP_EXTERNAL_ID, res.getIdentity().getExternalIdRef().getString());
r.commit();
fail("Duplicate value for rep:externalId must be detected in the default setup.");
} catch (CommitFailedException e) {
// success: verify nature of the exception
assertTrue(e.isConstraintViolation());
assertEquals(30, e.getCode());
} finally {
r.refresh();
}
}
@Test
public void testUniqueConstraintNonUserNode() throws Exception {
try {
SyncResult res = syncCtx.sync(idp.getUser(USER_ID));
Tree nonUserTree = r.getTree("/");
nonUserTree.setProperty(DefaultSyncContext.REP_EXTERNAL_ID, res.getIdentity().getExternalIdRef().getString());
r.commit();
fail("Duplicate value for rep:externalId must be detected in the default setup.");
} catch (CommitFailedException e) {
// success: verify nature of the exception
assertTrue(e.isConstraintViolation());
assertEquals(30, e.getCode());
} finally {
r.refresh();
}
}
}
| apache-2.0 |
dmaidaniuk/ozark | test/groovy/src/test/java/org/mvcspec/ozark/test/groovy/GroovyIT.java | 1639 | /*
* Copyright © 2017 Ivar Grimstad (ivar.grimstad@gmail.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.mvcspec.ozark.test.groovy;
import static org.junit.Assert.assertEquals;
import java.util.Iterator;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlElement;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
/**
* Unit test for simple App.
*/
public class GroovyIT {
private String webUrl;
private WebClient webClient;
@Before
public void setUp() {
webUrl = System.getProperty("integration.url");
webClient = new WebClient();
}
@After
public void tearDown() {
webClient.closeAllWindows();
}
@Test
public void testView1() throws Exception {
final HtmlPage page = webClient.getPage(webUrl + "resources/hello?user=mvc");
final Iterator<HtmlElement> it = page.getDocumentElement().getHtmlElementsByTagName("h1").iterator();
assertEquals("Hello mvc", it.next().asText().trim());
}
}
| apache-2.0 |
mcculls/guice | core/src/com/google/inject/multibindings/MapKey.java | 2381 | /*
* Copyright (C) 2015 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.inject.multibindings;
import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/**
* Allows users define customized key type annotations for map bindings by annotating an annotation
* of a {@code Map}'s key type. The custom key annotation can be applied to methods also annotated
* with {@literal @}{@link ProvidesIntoMap}.
*
* <p>A {@link StringMapKey} and {@link ClassMapKey} are provided for convenience with maps whose
* keys are strings or classes. For maps with enums or primitive types as keys, you must provide
* your own MapKey annotation, such as this one for an enum:
*
* <pre>
* {@literal @}MapKey(unwrapValue = true)
* {@literal @}Retention(RUNTIME)
* public {@literal @}interface MyCustomEnumKey {
* MyCustomEnum value();
* }
* </pre>
*
* You can also use the whole annotation as the key, if {@code unwrapValue=false}. When unwrapValue
* is false, the annotation type will be the key type for the injected map and the annotation
* instances will be the key values. If {@code unwrapValue=true}, the value() type will be the key
* type for injected map and the value() instances will be the keys values.
*
* @since 4.0
*/
@Documented
@Target(ANNOTATION_TYPE)
@Retention(RUNTIME)
public @interface MapKey {
/**
* if {@code unwrapValue} is false, then the whole annotation will be the type and annotation
* instances will be the keys. If {@code unwrapValue} is true, the value() type of key type
* annotation will be the key type for injected map and the value instances will be the keys.
*/
boolean unwrapValue() default true;
}
| apache-2.0 |
Nextpeer/Nextpeer-libgdx-Sample | starter/superjumper/src/com/badlogicgames/superjumper/HelpScreen3.java | 3065 | /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* 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.badlogicgames.superjumper;
import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.GLCommon;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector3;
public class HelpScreen3 implements Screen {
Game game;
OrthographicCamera guiCam;
SpriteBatch batcher;
Rectangle nextBounds;
Vector3 touchPoint;
Texture helpImage;
TextureRegion helpRegion;
public HelpScreen3 (Game game) {
this.game = game;
guiCam = new OrthographicCamera(320, 480);
guiCam.position.set(320 / 2, 480 / 2, 0);
nextBounds = new Rectangle(320 - 64, 0, 64, 64);
touchPoint = new Vector3();
batcher = new SpriteBatch();
helpImage = Assets.loadTexture("data/help3.png");
helpRegion = new TextureRegion(helpImage, 0, 0, 320, 480);
}
public void update (float deltaTime) {
if (Gdx.input.justTouched()) {
guiCam.unproject(touchPoint.set(Gdx.input.getX(), Gdx.input.getY(), 0));
if (OverlapTester.pointInRectangle(nextBounds, touchPoint.x, touchPoint.y)) {
Assets.playSound(Assets.clickSound);
game.setScreen(new HelpScreen4(game));
return;
}
}
}
public void draw (float deltaTime) {
GLCommon gl = Gdx.gl;
gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
guiCam.update();
batcher.setProjectionMatrix(guiCam.combined);
batcher.disableBlending();
batcher.begin();
batcher.draw(helpRegion, 0, 0, 320, 480);
batcher.end();
batcher.enableBlending();
batcher.begin();
batcher.draw(Assets.arrow, 320, 0, -64, 64);
batcher.end();
gl.glDisable(GL10.GL_BLEND);
}
@Override
public void render (float delta) {
update(delta);
draw(delta);
}
@Override
public void resize (int width, int height) {
}
@Override
public void show () {
}
@Override
public void hide () {
}
@Override
public void pause () {
helpImage.dispose();
}
@Override
public void resume () {
}
@Override
public void dispose () {
}
}
| apache-2.0 |
shawijayasekera/component-dep | components/reporting-service/src/main/java/com/wso2telco/dep/reportingservice/BillingHostObject.java | 77339 | /*******************************************************************************
* Copyright (c) 2015-2016, WSO2.Telco Inc. (http://www.wso2telco.com) All Rights Reserved.
*
* WSO2.Telco Inc. licences this file to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.wso2telco.dep.reportingservice;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.stream.XMLStreamException;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.util.AXIOMUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.Function;
import org.mozilla.javascript.NativeArray;
import org.mozilla.javascript.NativeObject;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.ScriptableObject;
import org.wso2.carbon.apimgt.api.APIConsumer;
import org.wso2.carbon.apimgt.api.APIManagementException;
import org.wso2.carbon.apimgt.api.model.Application;
import org.wso2.carbon.apimgt.api.model.Tier;
import org.wso2.carbon.apimgt.impl.APIConstants;
import org.wso2.carbon.apimgt.impl.APIManagerFactory;
import org.wso2.carbon.apimgt.impl.dao.ApiMgtDAO;
import org.wso2.carbon.apimgt.impl.utils.APIUtil;
import org.wso2.carbon.apimgt.usage.client.dto.APIVersionUserUsageDTO;
import com.wso2telco.core.dbutils.exception.BusinessException;
import com.wso2telco.dep.reportingservice.dao.Approval;
import com.wso2telco.dep.reportingservice.dao.BillingDAO;
import com.wso2telco.dep.reportingservice.dao.OperatorDAO;
import com.wso2telco.dep.reportingservice.exception.ReportingServiceError;
import com.wso2telco.dep.reportingservice.northbound.NbHostObjectUtils;
import com.wso2telco.dep.reportingservice.southbound.SbHostObjectUtils;
import com.wso2telco.dep.reportingservice.util.ChargeRate;
import com.wso2telco.dep.reportingservice.util.RateKey;
import com.wso2telco.dep.reportingservice.exception.ReportingServiceError;
// TODO: Auto-generated Javadoc
/**
* The Class BillingHostObject.
*/
public class BillingHostObject extends ScriptableObject {
/** The Constant log. */
private static final Log log = LogFactory.getLog(BillingHostObject.class);
/** The hostobject name. */
private String hostobjectName = "BillingHostObject";
/** The api consumer. */
private APIConsumer apiConsumer;
/** The tier pricing. */
private static Map<String, Float> tierPricing = new HashMap<String, Float>();
/** The tier maximum count. */
private static Map<String, Integer> tierMaximumCount = new HashMap<String, Integer>();
/** The tier unit time. */
private static Map<String, Integer> tierUnitTime = new HashMap<String, Integer>();
/**
* Gets the tier pricing.
*
* @return the tier pricing
*/
public static Map<String, Float> getTierPricing() {
return tierPricing;
}
/**
* Gets the tier maximum count.
*
* @return the tier maximum count
*/
public static Map<String, Integer> getTierMaximumCount() {
return tierMaximumCount;
}
/**
* Gets the tier unit time.
*
* @return the tier unit time
*/
public static Map<String, Integer> getTierUnitTime() {
return tierUnitTime;
}
/**
* Gets the username.
*
* @return the username
*/
public String getUsername() {
return username;
}
/** The username. */
private String username;
/* (non-Javadoc)
* @see org.mozilla.javascript.ScriptableObject#getClassName()
*/
@Override
public String getClassName() {
return hostobjectName;
}
/**
* Instantiates a new billing host object.
*
* @param username the username
* @throws BusinessException
* @throws APIManagementException the API management exception
*/
public BillingHostObject(String username) throws BusinessException{
if (log.isDebugEnabled()) {
log.debug("Initialized HostObject BillingHostObject for : " + username);
}
try {
if (username != null) {
this.username = username;
apiConsumer = APIManagerFactory.getInstance().getAPIConsumer(username);
} else {
apiConsumer = APIManagerFactory.getInstance().getAPIConsumer();
}
} catch (Exception e) {
log.error("BillingHostObject error",e);
throw new BusinessException(ReportingServiceError.INTERNAL_SERVER_ERROR);
}
}
/**
* Instantiates a new billing host object.
*/
public BillingHostObject() {
if (log.isDebugEnabled()) {
log.debug("Initialized HostObject BillingHostObject");
}
}
/**
* Gets the api consumer.
*
* @return the api consumer
*/
public APIConsumer getApiConsumer() {
return apiConsumer;
}
/**
* Gets the API consumer.
*
* @param thisObj the this obj
* @return the API consumer
*/
private static APIConsumer getAPIConsumer(Scriptable thisObj) {
return ((BillingHostObject) thisObj).getApiConsumer();
}
/**
* Js function_get report file content.
*
* @param cx the cx
* @param thisObj the this obj
* @param args the args
* @param funObj the fun obj
* @return the string
* @throws Exception
*/
public static String jsFunction_getReportFileContent(Context cx, Scriptable thisObj,
Object[] args, Function funObj)
throws BusinessException {
if (args == null || args.length == 0) {
log.error("jsFunction_getReportFileContent null or empty arguments");
throw new BusinessException(ReportingServiceError.INPUT_ERROR);
}
String subscriberName = (String) args[0];
String period = (String) args[1];
boolean isNorthbound = (Boolean) args[2];
try {
generateReport(subscriberName, period, true, isNorthbound, "__ALL__");
} catch (Exception e) {
log.error("jsFunction_getReportFileContent",e);
throw new BusinessException(ReportingServiceError.INTERNAL_SERVER_ERROR);
}
String fileContent = (isNorthbound) ? NbHostObjectUtils.getReport(subscriberName, period) : SbHostObjectUtils.getReport(subscriberName, period);
return fileContent;
}
/**
* Js function_get custom care data report.
*
* @param cx the cx
* @param thisObj the this obj
* @param args the args
* @param funObj the fun obj
* @return the native array
* @throws APIManagementException the API management exception
* @throws BusinessException
*/
public static NativeArray jsFunction_getCustomCareDataReport(Context cx, Scriptable thisObj,
Object[] args, Function funObj)
throws BusinessException {
if (args == null || args.length == 0) {
log.error("jsFunction_getCustomCareDataReport Invalid number of parameters");
throw new BusinessException(ReportingServiceError.INPUT_ERROR);
}
String fromDate = (String) args[0];
String toDate = (String) args[1];
String msisdn = (String) args[2];
String subscriberName = (String) args[3];
String operator = (String) args[4];
String app = (String) args[5];
String api = (String) args[6];
String limitStart = (String) args[7];
String limitEnd = (String) args[8];
String timeOffset = (String) args[9];
NativeArray dataArray = new NativeArray(0);
dataArray = getCustomCareDataReport(fromDate, toDate, msisdn, subscriberName, operator, app, api, limitStart,
limitEnd, timeOffset);
return dataArray;
}
/**
* Js function_get custom care data records count.
*
* @param cx the cx
* @param thisObj the this obj
* @param args the args
* @param funObj the fun obj
* @return the string
* @throws APIManagementException the API management exception
*/
public static String jsFunction_getCustomCareDataRecordsCount(Context cx, Scriptable thisObj,
Object[] args, Function funObj)
throws BusinessException {
if (args == null || args.length == 0) {
log.error("jsFunction_getCustomCareDataRecordsCount Invalid number of parameters");
throw new BusinessException(ReportingServiceError.INPUT_ERROR);
}
String fromDate = (String) args[0];
String toDate = (String) args[1];
String msisdn = (String) args[2];
String subscriberName = (String) args[3];
String operator = (String) args[4];
String app = (String) args[5];
String api = (String) args[6];
String dataString;
dataString = getCustomCareDataRecordCount(fromDate, toDate, msisdn, subscriberName, operator, app, api);
return dataString;
}
/**
* Js function_get custom api traffic report file content.
*
* @param cx the cx
* @param thisObj the this obj
* @param args the args
* @param funObj the fun obj
* @return the string
* @throws APIManagementException the API management exception
*/
public static String jsFunction_getCustomApiTrafficReportFileContent(Context cx, Scriptable thisObj,
Object[] args, Function funObj)
throws BusinessException {
if (args == null || args.length == 0) {
log.error("jsFunction_getCustomApiTrafficReportFileContent Invalid number of parameters");
throw new BusinessException(ReportingServiceError.INPUT_ERROR);
}
String fromDate = (String) args[0];
String toDate = (String) args[1];
String subscriberName = (String) args[2];
String operator = (String) args[3];
String api = (String) args[4];
String isError = (String) args[5];
int applicationId = Integer.parseInt(args[6].toString());
String timeOffset = (String) args[7];
String responseType = (String) args[8];
boolean isNorthbound = (Boolean) args[9];
generateCustomApiTrafficReport(fromDate, toDate, subscriberName, operator, api, (isError.equalsIgnoreCase("true") ? true : false), applicationId, timeOffset, responseType, isNorthbound);
String fileContent = SbHostObjectUtils.getCustomReport(fromDate, toDate, subscriberName, operator, api);
return fileContent;
}
/**
* Js function_get api usagefor subscriber.
*
* @param cx the cx
* @param thisObj the this obj
* @param args the args
* @param funObj the fun obj
* @return the native array
* @throws APIManagementException the API management exception
*/
public static NativeArray jsFunction_getAPIUsageforSubscriber(Context cx, Scriptable thisObj,
Object[] args, Function funObj)
throws BusinessException {
List<APIVersionUserUsageDTO> list = null;
if (args == null || args.length == 0) {
log.error("jsFunction_getAPIUsageforSubscriber Invalid number of parameters");
throw new BusinessException(ReportingServiceError.INPUT_ERROR);
}
NativeArray ret = null;
try {
NativeArray myn = new NativeArray(0);
if (!SbHostObjectUtils.checkDataPublishingEnabled()) {
return myn;
}
String subscriberName = (String) args[0];
String period = (String) args[1];
boolean isNorthbound = (Boolean) args[2];
String operatorName = (String) args[3];
ret = generateReport(subscriberName, period, false, isNorthbound, operatorName);
} catch (Exception e) {
log.error(e.getMessage(), e);
ret = new NativeArray(0);
NativeObject row = new NativeObject();
row.put("error", row, true);
row.put("message", row, e.getMessage());
ret.put(ret.size(), ret, row);
}
return ret;
}
/**
* Js function_get cost per api.
*
* @param cx the cx
* @param thisObj the this obj
* @param args the args
* @param funObj the fun obj
* @return the native array
* @throws Exception
*/
public static NativeArray jsFunction_getCostPerAPI(Context cx, Scriptable thisObj,
Object[] args, Function funObj)
throws BusinessException {
List<APIVersionUserUsageDTO> list = null;
if (args == null || args.length == 0) {
log.error("jsFunction_getCostPerAPI Invalid number of parameters");
throw new BusinessException(ReportingServiceError.INPUT_ERROR);
}
NativeArray myn = new NativeArray(0);
if (!SbHostObjectUtils.checkDataPublishingEnabled()) {
return myn;
}
String subscriberName = (String) args[0];
String period = (String) args[1];
String opcode = (String) args[2];
String application = (String) args[3];
if ((application == null) || (application.equalsIgnoreCase("0"))) {
application = "__All__";
}
boolean isNorthbound = (Boolean) args[4];
NativeArray ret = generateReport(subscriberName, period, false, isNorthbound, opcode);
NativeArray arr = (NativeArray) ret;
Map<String, Double> apiPriceMap = new HashMap<String, Double>();
apiPriceMap.clear();
NativeArray apiPriceResponse = new NativeArray(0);
for (Object o : arr.getIds()) {
int i = (Integer) o;
NativeObject subs = (NativeObject) arr.get(i);
String subscriber = subs.get("subscriber").toString();
log.info(subscriber);
NativeArray applicatons = (NativeArray) subs.get("applications");
for (Object o2 : applicatons.getIds()) {
int j = (Integer) o2;
NativeObject app = (NativeObject) applicatons.get(j);
String appname = app.get("applicationname").toString();
if (application.equalsIgnoreCase("__All__")) {
NativeArray subscriptions = (NativeArray) app.get("subscriptions");
for (Object o3 : subscriptions.getIds()) {
int k = (Integer) o3;
NativeObject apis = (NativeObject) subscriptions.get(k);
String api = apis.get("subscriptionapi").toString();
Double price = 0.0;
NativeArray operators = (NativeArray) apis.get("operators");
for (Object o4 : operators.getIds()) {
int l = (Integer) o4;
NativeObject opis = (NativeObject) operators.get(l);
String operator = opis.get("operator").toString();
if ((opcode.equalsIgnoreCase("__All__")) || (operator.equalsIgnoreCase(opcode))) {
price = price + Double.valueOf(opis.get("price").toString());
}
}
if (apiPriceMap.containsKey(api)) {
apiPriceMap.put(api, (apiPriceMap.get(api) + Double.valueOf(price)));
} else {
apiPriceMap.put(api, Double.valueOf(price));
}
}
} else {
try {
String applicationName = SbHostObjectUtils.getApplicationNameById(application);
if (appname.equalsIgnoreCase(applicationName)) {
NativeArray subscriptions = (NativeArray) app.get("subscriptions");
for (Object o3 : subscriptions.getIds()) {
int k = (Integer) o3;
NativeObject apis = (NativeObject) subscriptions.get(k);
String api = apis.get("subscriptionapi").toString();
Double price = 0.0;
NativeArray operators = (NativeArray) apis.get("operators");
for (Object o4 : operators.getIds()) {
int l = (Integer) o4;
NativeObject opis = (NativeObject) operators.get(l);
String operator = opis.get("operator").toString();
if ((opcode.equalsIgnoreCase("__All__")) || (operator.equalsIgnoreCase(opcode))) {
price = price + Double.valueOf(opis.get("price").toString());
}
}
if (apiPriceMap.containsKey(api)) {
apiPriceMap.put(api, (apiPriceMap.get(api) + Double.valueOf(price)));
} else {
apiPriceMap.put(api, Double.valueOf(price));
}
}
}
} catch (Exception e) {
log.error("jsFunction_getCostPerAPI",e);
throw new BusinessException(ReportingServiceError.INTERNAL_SERVER_ERROR);
}
}
}
}
short i = 0;
for (Map.Entry pairs : apiPriceMap.entrySet()) {
NativeObject row = new NativeObject();
String apiName = pairs.getKey().toString();
row.put(apiName, row, pairs.getValue().toString());
apiPriceResponse.put(i, apiPriceResponse, row);
i++;
}
return apiPriceResponse;
}
/**
* Generate report.
*
* @param subscriberName the subscriber name
* @param period the period
* @param persistReport the persist report
* @param isNorthbound the is northbound
* @param operatorName the operator name
* @return the native array
* @throws Exception
*/
private static NativeArray generateReport(String subscriberName, String period, boolean persistReport, boolean isNorthbound, String operatorName) throws BusinessException {
//createTierPricingMap();
Map<RateKey, ChargeRate> rateCard;
try {
rateCard = (isNorthbound) ? NbHostObjectUtils.getRateCard() : SbHostObjectUtils.getRateCard();
} catch (Exception e) {
log.error("generateReport",e);
throw new BusinessException(ReportingServiceError.INTERNAL_SERVER_ERROR);
}
NativeArray ret = null;
try {
ret = (isNorthbound) ? NbHostObjectUtils.generateReportofSubscriber(persistReport, subscriberName, period, rateCard) : SbHostObjectUtils.generateReportofSubscriber(persistReport, subscriberName, period, rateCard, operatorName);
} catch (Exception e) {
log.error("generateReport",e);
throw new BusinessException(ReportingServiceError.INTERNAL_SERVER_ERROR);
}
return ret;
}
/**
* Generate custom api traffic report.
*
* @param fromDate the from date
* @param toDate the to date
* @param subscriberName the subscriber name
* @param operator the operator
* @param api the api
* @param timeOffset the time offset
* @param resType the res type
* @param isNorthbound the is northbound
* @return the native array
* @throws APIManagementException the API management exception
*/
private static NativeArray generateCustomApiTrafficReport(String fromDate, String toDate, String subscriberName, String operator, String api,boolean isError, int applicationId, String timeOffset, String resType, boolean isNorthbound) throws BusinessException {
NativeArray ret = null;
try {
if (isNorthbound) {
try {
ret = NbHostObjectUtils.generateCustomTrafficReport(true, fromDate, toDate, subscriberName, operator, api, isError, applicationId, timeOffset, resType);
} catch (Exception e) {
e.printStackTrace();
}
} else {
ret = SbHostObjectUtils.generateCustomTrafficReport(true, fromDate, toDate, subscriberName, operator, api, isError, applicationId, timeOffset, resType);
}
} catch (Exception e) {
log.error("generateCustomApiTrafficReport",e);
throw new BusinessException(ReportingServiceError.INTERNAL_SERVER_ERROR);
}
return ret;
}
/**
* Gets the custom care data report.
*
* @param fromDate the from date
* @param toDate the to date
* @param msisdn the msisdn
* @param subscriberName the subscriber name
* @param operator the operator
* @param app the app
* @param api the api
* @param stLimit the st limit
* @param endLimit the end limit
* @param timeOffset the time offset
* @return the custom care data report
* @throws APIManagementException the API management exception
*/
private static NativeArray getCustomCareDataReport(String fromDate, String toDate, String msisdn, String subscriberName, String operator, String app, String api, String stLimit, String endLimit, String timeOffset) throws BusinessException {
NativeArray ret = null;
try {
ret = SbHostObjectUtils.generateCustomrCareDataReport(true, fromDate, toDate, msisdn, subscriberName,
operator, app, api, stLimit, endLimit, timeOffset);
} catch (Exception e) {
log.error("getCustomCareDataReport Error occurred while retrieving data.", e);
throw new BusinessException(ReportingServiceError.INPUT_ERROR);
}
return ret;
}
/**
* Gets the custom care data record count.
*
* @param fromDate the from date
* @param toDate the to date
* @param msisdn the msisdn
* @param subscriberName the subscriber name
* @param operator the operator
* @param app the app
* @param api the api
* @return the custom care data record count
* @throws APIManagementException the API management exception
* @throws BusinessException
*/
private static String getCustomCareDataRecordCount(String fromDate, String toDate, String msisdn, String subscriberName, String operator, String app, String api) throws BusinessException {
String ret = null;
try {
ret = SbHostObjectUtils.generateCustomrCareDataRecordCount(true, fromDate, toDate, msisdn, subscriberName,
operator, app, api);
} catch (Exception e) {
log.error("Error occurred while generating report",e);
throw new BusinessException(ReportingServiceError.INTERNAL_SERVER_ERROR);
}
return ret;
}
/**
* Generate financial report.
*
* @param subscriberName the subscriber name
* @param period the period
* @param opcode the opcode
* @param application the application
* @return the native array
* @throws APIManagementException the API management exception
*/
private static NativeArray generateFinancialReport(String subscriberName, String period,
String opcode, String application) throws BusinessException {
NativeArray ret = null;
try {
ret = SbHostObjectUtils.generateCostperApisummary(true, subscriberName, period, opcode, application);
} catch (Exception e) {
log.error("Error occurred while generating report.", e);
throw new BusinessException(ReportingServiceError.INTERNAL_SERVER_ERROR);
}
return ret;
}
/**
* Js function_get response time data.
*
* @param cx the cx
* @param thisObj the this obj
* @param args the args
* @param funObj the fun obj
* @return the native array
* @throws APIManagementException the API management exception
*/
public static NativeArray jsFunction_getResponseTimeData(Context cx, Scriptable thisObj,
Object[] args, Function funObj)
throws BusinessException {
String subscriberName = (String) args[0];
NativeArray nativeArray = null;
log.debug("Starting getResponseTimeData funtion with " + subscriberName);
try {
Map<String, String> responseTimes = SbHostObjectUtils.getResponseTimesForSubscriber(subscriberName);
short i = 0;
log.debug(subscriberName + ", responseTimes " + responseTimes);
if (responseTimes != null) {
nativeArray = new NativeArray(0);
}
for (Map.Entry<String, String> timeEntry : responseTimes.entrySet()) {
NativeObject row = new NativeObject();
log.debug(subscriberName + ", timeEntry key " + timeEntry.getKey());
log.debug(subscriberName + ", timeEntry value" + timeEntry.getValue());
row.put("apiName", row, timeEntry.getKey().toString());
row.put("responseTime", row, timeEntry.getValue().toString());
nativeArray.put(i, nativeArray, row);
i++;
}
} catch (Exception e) {
log.error("Error occured getResponseTimeData ",e);
throw new BusinessException(ReportingServiceError.INTERNAL_SERVER_ERROR);
}
log.info("End of getResponseTimeData");
return nativeArray;
}
/**
* Js function_get all response times.
*
* @param cx the cx
* @param thisObj the this obj
* @param args the args
* @param funObj the fun obj
* @return the native array
* @throws APIManagementException the API management exception
*/
public static NativeArray jsFunction_getAllResponseTimes(Context cx, Scriptable thisObj, Object[] args, Function funObj)
throws BusinessException {
String operatorName = (String) args[0];
String subscriberName = (String) args[1];
String appId = (String) args[2];
String fromDate = (String) args[3];
String toDate = (String) args[4];
String appName = "";
if (appId.equals("0") || appId.equalsIgnoreCase("__All__")) {
appId = "__ALL__";
appName = "__ALL__";
} else {
try {
Application application = ApiMgtDAO.getInstance().getApplicationById(Integer.parseInt(appId));
appName = application.getName();//HostObjectUtils.getApplicationNameById(appId);
} catch (Exception e) {
log.error("jsFunction_getAllResponseTimes",e);
throw new BusinessException(ReportingServiceError.INTERNAL_SERVER_ERROR);
}
}
NativeArray apis = new NativeArray(0);
log.debug("Starting getAllResponseTimes function for user- " + subscriberName + " app- " + appName);
try {
Map<String, List<APIResponseDTO>> responseMap = SbHostObjectUtils.getAllResponseTimes(operatorName,
subscriberName,
appName, appId,
fromDate, toDate);
short i = 0;
log.debug(subscriberName + ", responseMap " + responseMap);
for (Map.Entry<String, List<APIResponseDTO>> timeEntry : responseMap.entrySet()) {
NativeObject api = new NativeObject();
api.put("apiName", api, timeEntry.getKey());
NativeArray responseTimes = new NativeArray(0);
for (APIResponseDTO dto : timeEntry.getValue()) {
NativeObject responseData = new NativeObject();
responseData.put("serviceTime", responseData, dto.getServiceTime());
responseData.put("responseCount", responseData, dto.getResponseCount());
responseData.put("date", responseData, dto.getDate().toString());
responseTimes.put(responseTimes.size(), responseTimes, responseData);
}
api.put("responseData", api, responseTimes);
apis.put(i, apis, api);
i++;
}
} catch (Exception e) {
log.error("Error occured getAllResponseTimes",e);
throw new BusinessException(ReportingServiceError.INTERNAL_SERVER_ERROR);
}
return apis;
}
/**
* Js function_get all subscribers.
*
* @param cx the cx
* @param thisObj the this obj
* @param args the args
* @param funObj the fun obj
* @return the native array
* @throws APIManagementException the API management exception
*/
public static NativeArray jsFunction_getAllSubscribers(Context cx, Scriptable thisObj, Object[] args,
Function funObj) throws BusinessException {
NativeArray nativeArray = new NativeArray(0);
try {
List<String> subscribers = SbHostObjectUtils.getAllSubscribers();
if (subscribers != null) {
int i = 0;
for (String subscriber : subscribers) {
nativeArray.put(i, nativeArray, subscriber);
i++;
}
}
} catch (Exception e) {
log.error("Error occurred getAllSubscribers",e);
throw new BusinessException(ReportingServiceError.INTERNAL_SERVER_ERROR);
}
return nativeArray;
}
/**
* Js function_get all operators.
*
* @return the native array
* @throws APIManagementException the API management exception
*/
public static NativeArray jsFunction_getAllOperators() throws BusinessException {
NativeArray nativeArray = new NativeArray(0);
try {
List<String> operators = SbHostObjectUtils.getAllOperators();
if (operators != null) {
int i = 0;
for (String op : operators) {
nativeArray.put(i, nativeArray, op);
i++;
}
}
} catch (Exception e) {
log.error("Error occurred getAllOperators",e);
throw new BusinessException(ReportingServiceError.INTERNAL_SERVER_ERROR);
}
return nativeArray;
}
/**
* Js function_get total api traffic for pie chart.
*
* @param cx the cx
* @param thisObj the this obj
* @param args the args
* @param funObj the fun obj
* @return the native array
* @throws APIManagementException the API management exception
* @throws BusinessException
*/
public static NativeArray jsFunction_getTotalAPITrafficForPieChart(Context cx, Scriptable thisObj, Object[] args,
Function funObj) throws BusinessException {
NativeArray nativeArray = new NativeArray(0);
String fromDate = args[0].toString();
String toDate = args[1].toString();
String subscriber = args[2].toString();
int applicationId = Integer.parseInt(args[3].toString());
String operator = args[4].toString();
try {
List<String[]> api_requests = SbHostObjectUtils.getTotalAPITrafficForPieChart(fromDate, toDate, subscriber, operator, applicationId);
if (api_requests != null) {
int i = 0;
for (String[] api_request : api_requests) {
nativeArray.put(i, nativeArray, api_request);
i++;
}
}
} catch (Exception e) {
log.error("Error occurred getTotalTrafficForPieChart",e);
throw new BusinessException(ReportingServiceError.INTERNAL_SERVER_ERROR);
}
return nativeArray;
}
/**
* Js function_get operator app list.
*
* @param cx the cx
* @param thisObj the this obj
* @param args the args
* @param funObj the fun obj
* @return the native array
* @throws APIManagementException the API management exception
*/
public static NativeArray jsFunction_getOperatorAppList(Context cx, Scriptable thisObj, Object[] args, Function funObj) throws BusinessException {
NativeArray nativeArray = new NativeArray(0);
String operator = args[0].toString();
try {
List<Integer> opertatorAppIds = OperatorDAO.getApplicationsByOperator(operator);
int i = 0;
if (opertatorAppIds != null) {
for (Integer temp : opertatorAppIds) {
String appName = SbHostObjectUtils.getApplicationNameById(temp.toString());
if (appName != null) {
NativeObject appData = new NativeObject();
appData.put("id", appData, temp.toString());
appData.put("name", appData, appName);
nativeArray.put(i, nativeArray, appData);
}
i++;
}
}
} catch (Exception e) {
log.error("Error occurred getOperatorAppList",e);
throw new BusinessException(ReportingServiceError.INTERNAL_SERVER_ERROR);
}
return nativeArray;
}
/**
* Js function_get total api traffic for histogram.
*
* @param cx the cx
* @param thisObj the this obj
* @param args the args
* @param funObj the fun obj
* @return the native array
* @throws APIManagementException the API management exception
*/
public static NativeArray jsFunction_getTotalAPITrafficForHistogram(Context cx, Scriptable thisObj, Object[] args,
Function funObj) throws BusinessException {
NativeArray nativeArray = new NativeArray(0);
String fromDate = args[0].toString();
String toDate = args[1].toString();
String subscriber = args[2].toString();
int applicationId = Integer.parseInt(args[3].toString());
String operator = args[4].toString();
String api = args[5].toString();
try {
List<String[]> api_requests = SbHostObjectUtils.getTotalAPITrafficForHistogram(fromDate, toDate, subscriber, operator, applicationId, api);
List<String[]> apis = SbHostObjectUtils.getAllAPIs(fromDate, toDate, subscriber, operator, applicationId, api);
NativeArray apiHits = null;
NativeArray apiHitDates = null;
if (api_requests != null && apis != null) {
for (int i = 0; i < apis.size(); i++) {
apiHits = new NativeArray(0);
apiHitDates = new NativeArray(0);
int x = 0;
for (int j = 0; j < api_requests.size(); j++) {
if (apis.get(i)[0].toString().equals(api_requests.get(j)[0].toString())) {
apiHits.put(x, apiHits, api_requests.get(j)[2].toString());
apiHitDates.put(x, apiHitDates, api_requests.get(j)[1].toString());
x++;
}
}
NativeObject reqData = new NativeObject();
reqData.put("apiName", reqData, apis.get(i)[0].toString());
reqData.put("apiHits", reqData, apiHits);
reqData.put("apiHitDates", reqData, apiHitDates);
nativeArray.put(i, nativeArray, reqData);
}
}
} catch (Exception e) {
log.error("Error occurred getTotalTrafficForHistogram");
throw new BusinessException(ReportingServiceError.INTERNAL_SERVER_ERROR);
}
return nativeArray;
}
/**
* Js function_get operator wise api traffic for pie chart.
*
* @param cx the cx
* @param thisObj the this obj
* @param args the args
* @param funObj the fun obj
* @return the native array
* @throws APIManagementException the API management exception
*/
public static NativeArray jsFunction_getOperatorWiseAPITrafficForPieChart(Context cx, Scriptable thisObj, Object[] args,
Function funObj) throws BusinessException {
NativeArray nativeArray = new NativeArray(0);
String fromDate = args[0].toString();
String toDate = args[1].toString();
String subscriber = args[2].toString();
int applicationId = Integer.parseInt(args[3].toString());
String api = args[4].toString();
try {
List<String[]> api_requests = SbHostObjectUtils.getOperatorWiseAPITrafficForPieChart(fromDate, toDate,
subscriber, api,
applicationId);
if (api_requests != null) {
int i = 0;
for (String[] api_request : api_requests) {
nativeArray.put(i, nativeArray, api_request);
i++;
}
}
} catch (Exception e) {
log.error("Error occurred getTotalTrafficForHistogram",e);
throw new BusinessException(ReportingServiceError.INTERNAL_SERVER_ERROR);
}
return nativeArray;
}
/**
* Js function_get subscribers by operator.
*
* @param cx the cx
* @param thisObj the this obj
* @param args the args
* @param funObj the fun obj
* @return the native array
* @throws APIManagementException the API management exception
* @throws BusinessException
*/
public static NativeArray jsFunction_getSubscribersByOperator(Context cx, Scriptable thisObj, Object[] args,
Function funObj) throws BusinessException {
NativeArray nativeArray = new NativeArray(0);
String operatorName = args[0].toString();
try {
List<String> subscribers = SbHostObjectUtils.getSubscribersByOperator(operatorName);
if (subscribers != null) {
int i = 0;
for (String subscriber : subscribers) {
nativeArray.put(i, nativeArray, subscriber);
i++;
}
}
} catch (Exception e) {
log.error("Error occurred getSubscribersByOperator",e);
throw new BusinessException(ReportingServiceError.INTERNAL_SERVER_ERROR);
}
return nativeArray;
}
/**
* Js function_get applications by subscriber.
*
* @param cx the cx
* @param thisObj the this obj
* @param args the args
* @param funObj the fun obj
* @return the native array
* @throws APIManagementException the API management exception
* @throws BusinessException
*/
public static NativeArray jsFunction_getApplicationsBySubscriber(Context cx, Scriptable thisObj, Object[] args,
Function funObj) throws BusinessException {
NativeArray nativeArray = new NativeArray(0);
String subscriberName = args[0].toString();
try {
List<String[]> applications = SbHostObjectUtils.getApplicationsBySubscriber(subscriberName);
if (applications != null) {
int i = 0;
for (String[] application : applications) {
nativeArray.put(i, nativeArray, application);
i++;
}
}
} catch (Exception e) {
log.error("Error occurred getApplicationsBySubscriber",e);
throw new BusinessException(ReportingServiceError.INTERNAL_SERVER_ERROR);
}
return nativeArray;
}
/**
* Js function_get operators by subscriber.
*
* @param cx the cx
* @param thisObj the this obj
* @param args the args
* @param funObj the fun obj
* @return the native array
* @throws APIManagementException the API management exception
*/
public static NativeArray jsFunction_getOperatorsBySubscriber(Context cx, Scriptable thisObj, Object[] args,
Function funObj) throws BusinessException {
NativeArray nativeArray = new NativeArray(0);
String subscriberName = args[0].toString();
try {
List<String> operators = SbHostObjectUtils.getOperatorsBySubscriber(subscriberName);
if (operators != null) {
int i = 0;
for (String operator : operators) {
nativeArray.put(i, nativeArray, operator);
i++;
}
}
} catch (Exception e) {
log.error("Error occurred getOperatorsBySubscriber",e);
throw new BusinessException(ReportingServiceError.INTERNAL_SERVER_ERROR);
}
return nativeArray;
}
/**
* Js function_get ap is by subscriber.
*
* @param cx the cx
* @param thisObj the this obj
* @param args the args
* @param funObj the fun obj
* @return the native array
* @throws APIManagementException the API management exception
*/
public static NativeArray jsFunction_getAPIsBySubscriber(Context cx, Scriptable thisObj, Object[] args,
Function funObj) throws BusinessException {
NativeArray nativeArray = new NativeArray(0);
String subscriberName = args[0].toString();
try {
List<String> apis = SbHostObjectUtils.getAPIsBySubscriber(subscriberName);
if (apis != null) {
int i = 0;
for (String api : apis) {
nativeArray.put(i, nativeArray, api);
i++;
}
}
} catch (Exception e) {
log.error("Error occurred getAPIsBySubscriber",e);
throw new BusinessException(ReportingServiceError.INTERNAL_SERVER_ERROR);
}
return nativeArray;
}
/**
* Js function_get all operation types.
*
* @param cx the cx
* @param thisObj the this obj
* @param args the args
* @param funObj the fun obj
* @return the native array
* @throws APIManagementException the API management exception
*/
public static NativeArray jsFunction_getAllOperationTypes(Context cx, Scriptable thisObj, Object[] args,
Function funObj) throws BusinessException {
NativeArray nativeArray = new NativeArray(0);
List<String[]> opTypes;
try {
opTypes = SbHostObjectUtils.getOperationTypes();
if (opTypes != null) {
int i = 0;
for (String[] operation : opTypes) {
nativeArray.put(i, nativeArray, operation);
i++;
}
}
} catch (Exception e) {
log.error("Error occurred getAllOperationTypes",e);
throw new BusinessException(ReportingServiceError.INTERNAL_SERVER_ERROR);
}
return nativeArray;
}
/**
* Js function_get approval history.
*
* @param cx the cx
* @param thisObj the this obj
* @param args the args
* @param funObj the fun obj
* @return the native array
* @throws APIManagementException the API management exception
*/
public static NativeArray jsFunction_getApprovalHistory(Context cx, Scriptable thisObj, Object[] args,
Function funObj) throws BusinessException {
NativeArray nativeArray = new NativeArray(0);
String fromDate = null;
String toDate = null;
String subscriber = args[2].toString();
int applicationId = Integer.parseInt(args[3].toString());
String operator = (String) args[4];
String api = null;
int offset = 0;
int count = 0;
try {
if (args.length >= 8) {
Object offsetObject = args[6];
Object countObject = args[7];
if (offsetObject != null && countObject != null) {
offset = Integer.parseInt(offsetObject.toString());
count = Integer.parseInt(countObject.toString());
}
}
} catch (NumberFormatException e) {
//ignore
}
try {
List<String[]> api_requests = SbHostObjectUtils.getApprovalHistory(fromDate, toDate, subscriber, api, applicationId, operator, offset, count);
if (api_requests != null) {
int i = 0;
for (String[] api_request : api_requests) {
nativeArray.put(i, nativeArray, api_request);
i++;
}
}
} catch (Exception e) {
log.error("Error occurred getTotalTrafficForHistogram",e);
throw new BusinessException(ReportingServiceError.INTERNAL_SERVER_ERROR);
}
return nativeArray;
}
/**
* Js function_get approval history app.
*
* @param cx the cx
* @param thisObj the this obj
* @param args the args
* @param funObj the fun obj
* @return the native object
* @throws APIManagementException the API management exception
*/
public static NativeObject jsFunction_getApprovalHistoryApp(Context cx, Scriptable thisObj, Object[] args,
Function funObj) throws BusinessException {
NativeArray nativeArray = new NativeArray(0);
int applicationId = Integer.parseInt(args[0].toString());
String operator = args[1].toString();
//String api = args[4].toString();
NativeObject Application = new NativeObject();
NativeArray opcoapps = new NativeArray(0);
NativeArray Subscriptions = new NativeArray(0);
NativeArray opcosubs = new NativeArray(0);
try {
List<Approval> api_requests = SbHostObjectUtils.getApprovalHistoryApp(applicationId, operator);
if (api_requests != null) {
int j = 0;
int k = 0;
int ai = 0;
for (Approval obj : api_requests) {
//set application status
String retstat = obj.getIsactive();
if ((obj.getIsactive().equalsIgnoreCase("CREATED")) || (obj.getIsactive().equalsIgnoreCase("ON_HOLD"))) {
retstat = "PENDING APPROVE";
} else if (obj.getIsactive().equalsIgnoreCase("UNBLOCKED")) {
retstat = "APPROVED";
}
if (obj.getType().equalsIgnoreCase("1")) {
NativeObject app = new NativeObject();
app.put("appid", app, obj.getApplication_id());
app.put("type", app, obj.getType());
app.put("name", app, obj.getName());
app.put("operatorid", app, obj.getOperatorid());
app.put("status", app, retstat);
Application.put("application", Application, app);
} else if (obj.getType().equalsIgnoreCase("2")) {
NativeObject appopco = new NativeObject();
appopco.put("type", appopco, obj.getType());
appopco.put("name", appopco, obj.getName());
appopco.put("operatorid", appopco, obj.getOperatorid());
appopco.put("status", appopco, retstat);
opcoapps.put(ai, opcoapps, appopco);
ai++;
} else if (obj.getType().equalsIgnoreCase("3")) {
NativeObject sub = new NativeObject();
sub.put("appid", sub, obj.getApplication_id());
sub.put("type", sub, obj.getType());
sub.put("name", sub, obj.getName());
sub.put("operatorid", sub, obj.getOperatorid());
sub.put("status", sub, retstat);
sub.put("tier", sub, obj.getTier_id());
sub.put("api", sub, obj.getApi_name());
sub.put("apiversion", sub, obj.getApi_version());
Subscriptions.put(j, Subscriptions, sub);
j++;
} else if (obj.getType().equalsIgnoreCase("4")) {
NativeObject subop = new NativeObject();
subop.put("appid", subop, obj.getApplication_id());
subop.put("type", subop, obj.getType());
subop.put("name", subop, obj.getName());
subop.put("operatorid", subop, obj.getOperatorid());
subop.put("status", subop, retstat);
subop.put("tier", subop, obj.getTier_id());
subop.put("api", subop, obj.getApi_name());
subop.put("apiversion", subop, obj.getApi_version());
subop.put("created", subop, obj.getCreated());
subop.put("lastupdated", subop, obj.getLast_updated());
opcosubs.put(k, opcosubs, subop);
k++;
}
}
Application.put("opcoapps", Application, opcoapps);
Application.put("Subscriptions", Application, Subscriptions);
Application.put("opcosubs", Application, opcosubs);
}
} catch (Exception e) {
log.error("Error occurred getTotalTrafficForHistogram",e);
throw new BusinessException(ReportingServiceError.INTERNAL_SERVER_ERROR);
}
return Application;
}
/**
* Js function_get error response codes for pie chart.
*
* @param cx the cx
* @param thisObj the this obj
* @param args the args
* @param funObj the fun obj
* @return the native array
* @throws APIManagementException the API management exception
*/
public static NativeArray jsFunction_getErrorResponseCodesForPieChart(Context cx, Scriptable thisObj, Object[] args,
Function funObj) throws BusinessException {
NativeArray nativeArray = new NativeArray(0);
String fromDate = args[0].toString();
String toDate = args[1].toString();
String subscriber = args[2].toString();
int applicationId = Integer.parseInt(args[3].toString());
String operator = args[4].toString();
String api = args[5].toString();
try {
List<String[]> api_requests = SbHostObjectUtils.getErrorResponseCodesForPieChart(fromDate, toDate, subscriber, operator, applicationId, api);
if (api_requests != null) {
int i = 0;
for (String[] api_request : api_requests) {
nativeArray.put(i, nativeArray, api_request);
i++;
}
}
} catch (Exception e) {
log.error("Error occurred getErrorResponseCodesForPieChart");
throw new BusinessException(ReportingServiceError.INTERNAL_SERVER_ERROR);
}
return nativeArray;
}
/**
* Js function_get error response codes for histogram.
*
* @param cx the cx
* @param thisObj the this obj
* @param args the args
* @param funObj the fun obj
* @return the native array
* @throws APIManagementException the API management exception
*/
public static NativeArray jsFunction_getErrorResponseCodesForHistogram(Context cx, Scriptable thisObj, Object[] args,
Function funObj) throws BusinessException {
NativeArray nativeArray = new NativeArray(0);
String fromDate = args[0].toString();
String toDate = args[1].toString();
String subscriber = args[2].toString();
int applicationId = Integer.parseInt(args[3].toString());
String operator = args[4].toString();
String api = args[5].toString();
try {
List<String[]> api_response_codes = SbHostObjectUtils.getErrorResponseCodesForHistogram(fromDate, toDate, subscriber, operator, applicationId, api);
List<String[]> resCodes = SbHostObjectUtils.getAllErrorResponseCodes(fromDate, toDate, subscriber, operator, applicationId, api);
NativeArray apiHits = null;
NativeArray apiHitDates = null;
if (api_response_codes != null && resCodes != null) {
for (int i = 0; i < resCodes.size(); i++) {
apiHits = new NativeArray(0);
apiHitDates = new NativeArray(0);
int x = 0;
for (int j = 0; j < api_response_codes.size(); j++) {
if (resCodes.get(i)[0].equals(api_response_codes.get(j)[0])) {
apiHitDates.put(x, apiHitDates, api_response_codes.get(j)[1]);
apiHits.put(x, apiHits, api_response_codes.get(j)[2]);
x++;
}
}
NativeObject reqData = new NativeObject();
reqData.put("errorCode", reqData, resCodes.get(i)[0]);
reqData.put("apiHits", reqData, apiHits);
reqData.put("apiHitDates", reqData, apiHitDates);
nativeArray.put(i, nativeArray, reqData);
}
}
} catch (Exception e) {
log.error("Error occurred getErrorResponseCodesForHistogram",e);
throw new BusinessException(ReportingServiceError.INTERNAL_SERVER_ERROR);
}
return nativeArray;
}
/**
* Gets the max count.
*
* @param tier the tier
* @return the max count
* @throws XMLStreamException the XML stream exception
*/
private static int getMaxCount(Tier tier) throws XMLStreamException {
OMElement policy = AXIOMUtil.stringToOM(new String(tier.getPolicyContent()));
OMElement maxCount = policy.getFirstChildWithName(APIConstants.POLICY_ELEMENT)
.getFirstChildWithName(APIConstants.THROTTLE_CONTROL_ELEMENT)
.getFirstChildWithName(APIConstants.POLICY_ELEMENT)
.getFirstChildWithName(APIConstants.THROTTLE_MAXIMUM_COUNT_ELEMENT);
if (maxCount != null) {
return Integer.parseInt(maxCount.getText());
}
return -1;
}
/**
* Gets the time unit.
*
* @param tier the tier
* @return the time unit
* @throws XMLStreamException the XML stream exception
*/
private static int getTimeUnit(Tier tier) throws XMLStreamException {
OMElement policy = AXIOMUtil.stringToOM(new String(tier.getPolicyContent()));
OMElement timeUnit = policy.getFirstChildWithName(APIConstants.POLICY_ELEMENT)
.getFirstChildWithName(APIConstants.THROTTLE_CONTROL_ELEMENT)
.getFirstChildWithName(APIConstants.POLICY_ELEMENT)
.getFirstChildWithName(APIConstants.THROTTLE_UNIT_TIME_ELEMENT);
if (timeUnit != null) {
return Integer.parseInt(timeUnit.getText());
}
return -1;
}
/**
* Creates the tier pricing map.
*
* @throws APIManagementException the API management exception
*/
private static void createTierPricingMap() throws APIManagementException {
Map<String, Tier> tierMap = APIUtil.getTiers();
for (Map.Entry<String, Tier> entry : tierMap.entrySet()) {
Map<String, Object> attributes = entry.getValue().getTierAttributes();
if (attributes != null && attributes.containsKey("Rate")) {
tierPricing.put(entry.getKey(), Float.parseFloat(attributes.get("Rate").toString()));
} else {
tierPricing.put(entry.getKey(), 0f);
}
try {
int maxCount = getMaxCount(entry.getValue());
tierMaximumCount.put(entry.getKey(), maxCount);
} catch (XMLStreamException e) {
}
try {
int unitTime = getTimeUnit(entry.getValue());
tierUnitTime.put(entry.getKey(), unitTime);
} catch (XMLStreamException e) {
}
}
}
/**
* Prints the tier pricing.
*
* @throws APIManagementException the API management exception
*/
private static void printTierPricing() throws APIManagementException {
createTierPricingMap();
System.out.println("Print Tier Pricings");
for (Map.Entry<String, Float> pricing : tierPricing.entrySet()) {
System.out.println("Price for Tier : " + pricing.getKey() + " = " + pricing.getValue());
}
}
/**
* Handle exception.
*
* @param msg the msg
* @throws APIManagementException the API management exception
*/
private static void handleException(String msg) throws APIManagementException {
log.error(msg);
throw new APIManagementException(msg);
}
/**
* Handle exception.
*
* @param msg the msg
* @param t the t
* @throws APIManagementException the API management exception
*/
private static void handleException(String msg, Throwable t) throws APIManagementException {
log.error(msg, t);
throw new APIManagementException(msg, t);
}
/**
* Js function_get s pfor blacklist.
*
* @param cx the cx
* @param thisObj the this obj
* @param args the args
* @param funObj the fun obj
* @return the native array
* @throws Exception
*/
@SuppressWarnings("null")
public static NativeArray jsFunction_getSPforBlacklist(Context cx, Scriptable thisObj, Object[] args, Function funObj) throws BusinessException {
if (args == null || args.length == 0) {
log.error("Invalid number of parameters.");
}
String operator = String.valueOf(args[2]);
Boolean isadmin = Boolean.valueOf(String.valueOf(args[1]));
BillingDAO billingDAO = new BillingDAO();
List<SPObject> spList;
try {
spList = billingDAO.generateSPList();
} catch (Exception e) {
throw new BusinessException(ReportingServiceError.INTERNAL_SERVER_ERROR);
}
List<SPObject> spListoperator = OperatorDAO.getSPList(operator);
NativeArray nativeArray = new NativeArray(0);
NativeObject nativeObject;
if (spList != null) {
int i = 0;
for (SPObject spObject : spList) {
NativeObject row = new NativeObject();
row.put("appId", row, spObject.getAppId().toString());
row.put("spName", row, spObject.getSpName());
if (!isadmin) {
for (SPObject SPObjectoperator : spListoperator) {
if (SPObjectoperator.getAppId() == spObject.getAppId()) {
nativeArray.put(i, nativeArray, row);
break;
}
}
} else {
nativeArray.put(i, nativeArray, row);
}
i++;
}
}
return nativeArray;
}
/**
* Js function_get appfor blacklist.
*
* @param cx the cx
* @param thisObj the this obj
* @param args the args
* @param funObj the fun obj
* @return the native object
* @throws Exception
*/
public static NativeObject jsFunction_getAppforBlacklist(Context cx, Scriptable thisObj, Object[] args, Function funObj) throws BusinessException {
if (args == null || args.length == 0) {
log.error("Invalid number of parameters.");
}
BillingDAO billingDAO = new BillingDAO();
String appId = args[0].toString();
SPObject spObject;
try {
spObject = billingDAO.generateSPObject(appId);
} catch (Exception e) {
throw new BusinessException(ReportingServiceError.INTERNAL_SERVER_ERROR);
}
NativeObject row = new NativeObject();
if (spObject != null) {
row.put("appId", row, spObject.getAppId().toString());
row.put("spName", row, spObject.getSpName());
row.put("userName", row, spObject.getUserName());
row.put("token", row, spObject.getToken());
row.put("secret", row, spObject.getSecret());
row.put("key", row, spObject.getKey());
}
return row;
}
/**
* Js function_get dashboard api traffic for pie chart.
*
* @param cx the cx
* @param thisObj the this obj
* @param args the args
* @param funObj the fun obj
* @return the native array
* @throws APIManagementException the API management exception
*/
public static NativeArray jsFunction_getDashboardAPITrafficForPieChart(Context cx, Scriptable thisObj, Object[] args,
Function funObj) throws BusinessException {
NativeArray nativeArray = new NativeArray(0);
String timeRange = args[0].toString();
String operator = args[1].toString();
String subscriber = args[2].toString();
if (operator.equalsIgnoreCase("All")) {
operator = HostObjectConstants.ALL_OPERATORS;
} else {
operator = operator.toUpperCase();
}
if (subscriber.equalsIgnoreCase("All")) {
subscriber = HostObjectConstants.ALL_SUBSCRIBERS;
}
Calendar now = Calendar.getInstance();
String toDate = getCurrentTime(now);
String fromDate = subtractTimeRange(now, timeRange);
int applicationId = HostObjectConstants.ALL_APPLICATIONS;
try {
List<String[]> api_requests = SbHostObjectUtils.getTotalAPITrafficForPieChart(fromDate, toDate, subscriber, operator, applicationId);
if (api_requests != null) {
//get the total requests first to calculate the percentage
double totalRequests = 0;
for (String[] api_request : api_requests) {
totalRequests = totalRequests + Integer.parseInt(api_request[1]);
}
int i = 0;
for (String[] api_request : api_requests) {
String[] chartData = new String[3];
chartData[0] = api_request[0];
chartData[1] = api_request[1];
double percentage = Math.round((Integer.parseInt(api_request[1]) * 100) / totalRequests);
chartData[2] = String.valueOf((int) percentage);
nativeArray.put(i, nativeArray, chartData);
i++;
}
}
} catch (Exception e) {
log.error("Error occurred getDashboardAPITrafficForPieChart",e);
throw new BusinessException(ReportingServiceError.INTERNAL_SERVER_ERROR);
}
return nativeArray;
}
/**
* Subtract time range.
*
* @param date the date
* @param timeRange the time range
* @return the string
*/
private static String subtractTimeRange(Calendar date, String timeRange) {
String fromDate = null;
if (timeRange.equals(HostObjectConstants.DATE_LAST_DAY)) {
date.add(Calendar.DATE, -1);
} else if (timeRange.equals(HostObjectConstants.DATE_LAST_WEEK)) {
date.add(Calendar.DATE, -7);
} else if (timeRange.equals(HostObjectConstants.DATE_LAST_MONTH)) {
date.add(Calendar.MONTH, -1);
} else if (timeRange.equals(HostObjectConstants.DATE_LAST_YEAR)) {
date.add(Calendar.YEAR, -1);
}
fromDate = date.get(Calendar.YEAR) + "-" + (date.get(Calendar.MONTH) + 1) + "-" + date.get(Calendar.DATE);
return fromDate;
}
/**
* Gets the current time.
*
* @param date the date
* @return the current time
*/
private static String getCurrentTime(Calendar date) {
return date.get(Calendar.YEAR) + "-" + (date.get(Calendar.MONTH) + 1) + "-" + date.get(Calendar.DATE);
}
/**
* Gets the time in milli.
*
* @param date the date
* @return the time in milli
*/
private static String getTimeInMilli(String date) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
String dateString = "";
Date parsedDate;
try {
parsedDate = format.parse(date);
dateString = String.valueOf(parsedDate.getTime());
} catch (ParseException e) {
log.error("error in parsing the date");
}
return dateString;
}
/**
* Js function_get dashboard api traffic for line chart.
*
* @param cx the cx
* @param thisObj the this obj
* @param args the args
* @param funObj the fun obj
* @return the native array
* @throws APIManagementException the API management exception
*/
public static NativeArray jsFunction_getDashboardAPITrafficForLineChart(Context cx, Scriptable thisObj, Object[] args,
Function funObj) throws BusinessException {
NativeArray nativeArray = new NativeArray(0);
String timeRange = args[0].toString();
String operator = args[1].toString();
String subscriber = args[2].toString();
if (operator.equalsIgnoreCase("All")) {
operator = HostObjectConstants.ALL_OPERATORS;
} else {
operator = operator.toUpperCase();
}
if (subscriber.equalsIgnoreCase("All")) {
subscriber = HostObjectConstants.ALL_SUBSCRIBERS;
}
Calendar now = Calendar.getInstance();
String toDate = getCurrentTime(now);
String fromDate = subtractTimeRange(now, timeRange);
int applicationId = HostObjectConstants.ALL_APPLICATIONS;
String api = HostObjectConstants.ALL_APIS;
try {
List<String[]> api_requests = SbHostObjectUtils.getTotalAPITrafficForLineChart(fromDate, toDate, subscriber, operator, applicationId, api);
NativeArray apiHits = null;
NativeArray apiHitDates = null;
apiHits = new NativeArray(0);
apiHitDates = new NativeArray(0);
int x = 0;
for (int j = 0; j < api_requests.size(); j++) {
apiHits.put(x, apiHits, api_requests.get(j)[1].toString());
String hitDateInMilli = getTimeInMilli(api_requests.get(j)[0].toString());
apiHitDates.put(x, apiHitDates, hitDateInMilli);
x++;
}
NativeObject reqData = new NativeObject();
reqData.put("apiHits", reqData, apiHits);
reqData.put("apiHitDates", reqData, apiHitDates);
reqData.put("startDate", reqData, getTimeInMilli(fromDate));
nativeArray.put(0, nativeArray, reqData);
} catch (Exception e) {
log.error("Error occurred getTotalAPITrafficForLineChart",e);
throw new BusinessException(ReportingServiceError.INTERNAL_SERVER_ERROR);
}
return nativeArray;
}
/**
* Js function_get dashboard api response time for line chart.
*
* @param cx the cx
* @param thisObj the this obj
* @param args the args
* @param funObj the fun obj
* @return the native object
* @throws APIManagementException the API management exception
*/
public static NativeObject jsFunction_getDashboardAPIResponseTimeForLineChart(Context cx, Scriptable thisObj, Object[] args,
Function funObj) throws BusinessException {
NativeObject nativeObject = new NativeObject();
String timeRange = args[0].toString();
String operator = args[1].toString();
String subscriber = args[2].toString();
if (operator.equalsIgnoreCase("All")) {
operator = HostObjectConstants.ALL_OPERATORS;
} else {
operator = operator.toUpperCase();
}
if (subscriber.equalsIgnoreCase("All")) {
subscriber = HostObjectConstants.ALL_SUBSCRIBERS;
}
Calendar now = Calendar.getInstance();
String toDate = getCurrentTime(now);
String fromDate = subtractTimeRange(now, timeRange);
try {
List<APIResponseDTO> apiResponses = SbHostObjectUtils.getTotalAPIResponseTimeForLineChart(fromDate, toDate, subscriber, operator, timeRange);
NativeArray apiServiceTimes = new NativeArray(0);
NativeArray apiResponseCount = new NativeArray(0);
NativeArray apiAvgServiceTime = new NativeArray(0);
NativeArray apiHitDates = new NativeArray(0);
int x = 0;
int serviceTime = 0;
int respCount = 0;
int avgServiceTime = 0;
for (int j = 0; j < apiResponses.size(); j++) {
APIResponseDTO temp = apiResponses.get(j);
serviceTime = temp.getServiceTime();
respCount = temp.getResponseCount();
avgServiceTime = serviceTime / respCount;
String hitDateInMilli = getTimeInMilli(temp.getDate().toString());
apiServiceTimes.put(x, apiServiceTimes, Integer.toString(serviceTime));
apiResponseCount.put(x, apiResponseCount, Integer.toString(respCount));
apiAvgServiceTime.put(x, apiAvgServiceTime, Integer.toString(avgServiceTime));
apiHitDates.put(x, apiHitDates, hitDateInMilli);
x++;
}
NativeObject respData = new NativeObject();
respData.put("apiServiceTimes", respData, apiServiceTimes);
respData.put("apiResponseCount", respData, apiResponseCount);
respData.put("apiAvgServiceTime", respData, apiAvgServiceTime);
respData.put("apiHitDates", respData, apiHitDates);
nativeObject.put("responseTimes", nativeObject, respData);
nativeObject.put("startDate", nativeObject, getTimeInMilli(fromDate));
} catch (Exception e) {
log.error("Error occurred getDashboardAPIResponseTimeForLineChart");
throw new BusinessException(ReportingServiceError.INTERNAL_SERVER_ERROR);
}
return nativeObject;
}
/**
* Js function_get dashboard response times by api.
*
* @param cx the cx
* @param thisObj the this obj
* @param args the args
* @param funObj the fun obj
* @return the native array
* @throws APIManagementException the API management exception
*/
public static NativeArray jsFunction_getDashboardResponseTimesByAPI(Context cx, Scriptable thisObj, Object[] args, Function funObj)
throws BusinessException {
String timeRange = args[0].toString();
String operator = args[1].toString();
String subscriber = args[2].toString();
if (operator.equalsIgnoreCase("All")) {
operator = HostObjectConstants.ALL_OPERATORS;
} else {
operator = operator.toUpperCase();
}
if (subscriber.equalsIgnoreCase("All")) {
subscriber = HostObjectConstants.ALL_SUBSCRIBERS;
}
Calendar now = Calendar.getInstance();
String toDate = getCurrentTime(now);
String fromDate = subtractTimeRange(now, timeRange);
NativeArray apis = new NativeArray(0);
try {
Map<String, List<APIResponseDTO>> responseMap = SbHostObjectUtils.getAllResponseTimesByDate(operator, subscriber, fromDate, toDate);
short i = 0;
int serviceTime = 0;
int respCount = 0;
int avgServiceTime = 0;
for (Map.Entry<String, List<APIResponseDTO>> timeEntry : responseMap.entrySet()) {
NativeObject api = new NativeObject();
api.put("apiName", api, timeEntry.getKey());
NativeArray responseTimes = new NativeArray(0);
for (APIResponseDTO dto : timeEntry.getValue()) {
NativeObject responseData = new NativeObject();
serviceTime = dto.getServiceTime();
respCount = dto.getResponseCount();
avgServiceTime = serviceTime / respCount;
String hitDateInMilli = getTimeInMilli(dto.getDate().toString());
responseData.put("apiServiceTimes", responseData, serviceTime);
responseData.put("apiResponseCount", responseData, respCount);
responseData.put("apiAvgServiceTime", responseData, avgServiceTime);
responseData.put("apiHitDates", responseData, hitDateInMilli);
responseTimes.put(responseTimes.size(), responseTimes, responseData);
}
api.put("responseData", api, responseTimes);
apis.put(i, apis, api);
i++;
}
} catch (Exception e) {
log.error("Error occured getAllResponseTimes ",e);
throw new BusinessException(ReportingServiceError.INTERNAL_SERVER_ERROR);
}
return apis;
}
/**
* Js function_get dashboard time consumers by api.
*
* @param cx the cx
* @param thisObj the this obj
* @param args the args
* @param funObj the fun obj
* @return the native object
* @throws APIManagementException the API management exception
*/
public static NativeObject jsFunction_getDashboardTimeConsumersByAPI(Context cx, Scriptable thisObj, Object[] args, Function funObj)
throws APIManagementException {
String timeRange = args[0].toString();
String operator = args[1].toString();
String subscriber = args[2].toString();
if (operator.equalsIgnoreCase("All")) {
operator = HostObjectConstants.ALL_OPERATORS;
} else {
operator = operator.toUpperCase();
}
if (subscriber.equalsIgnoreCase("All")) {
subscriber = HostObjectConstants.ALL_SUBSCRIBERS;
}
Calendar now = Calendar.getInstance();
String toDate = getCurrentTime(now);
String fromDate = subtractTimeRange(now, timeRange);
NativeObject apiConsumpData = new NativeObject();
NativeArray slowestApis = new NativeArray(0);
NativeArray chartData = new NativeArray(0);
try {
Map<String, String[]> responseMap = SbHostObjectUtils.getTimeConsumptionForAllAPIs(operator, subscriber, fromDate, toDate);
short i = 0;
for (Map.Entry<String, String[]> timeEntry : responseMap.entrySet()) {
NativeObject slowestApiInfo = new NativeObject();
NativeObject chartDataForApi = new NativeObject();
String[] data = timeEntry.getValue();
slowestApiInfo.put("apiName", slowestApiInfo, timeEntry.getKey());
slowestApiInfo.put("highestAvgConsumption", slowestApiInfo, data[1]);
chartDataForApi.put("apiName", chartDataForApi, timeEntry.getKey());
chartDataForApi.put("totalAvgConsumption", chartDataForApi, data[2]);
slowestApis.put(i, slowestApis, slowestApiInfo);
chartData.put(i, chartData, chartDataForApi);
i++;
}
apiConsumpData.put("slowestApis", apiConsumpData, slowestApis);
apiConsumpData.put("chartData", apiConsumpData, chartData);
} catch (Exception e) {
log.error("Error occured getAllResponseTimes ");
log.error(e.getStackTrace());
handleException("Error occurred while populating Response Time graph.", e);
}
return apiConsumpData;
}
}
| apache-2.0 |
emre-aydin/hazelcast | hazelcast/src/main/java/com/hazelcast/spi/discovery/multicast/MulticastProperties.java | 1913 | /*
* Copyright (c) 2008-2021, Hazelcast, 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.hazelcast.spi.discovery.multicast;
import com.hazelcast.config.properties.PropertyDefinition;
import com.hazelcast.config.properties.PropertyTypeConverter;
import com.hazelcast.config.properties.SimplePropertyDefinition;
import com.hazelcast.config.properties.ValueValidator;
import static com.hazelcast.config.properties.PropertyTypeConverter.INTEGER;
import static com.hazelcast.config.properties.PropertyTypeConverter.STRING;
/**
* Defines the name and default value for the Multicast Discovery Strategy.
*/
public final class MulticastProperties {
/**
* Property used to define multicast port.
*/
public static final PropertyDefinition PORT = property("port", INTEGER);
/**
* Property used to define zones for node filtering.
*/
public static final PropertyDefinition GROUP = property("group", STRING);
private MulticastProperties() {
}
private static PropertyDefinition property(String key, PropertyTypeConverter typeConverter) {
return property(key, typeConverter, null);
}
private static PropertyDefinition property(String key, PropertyTypeConverter typeConverter, ValueValidator valueValidator) {
return new SimplePropertyDefinition(key, true, typeConverter, valueValidator);
}
}
| apache-2.0 |
kensipe/myriad | myriad-scheduler/src/main/java/com/ebay/myriad/state/MyriadStateStore.java | 1127 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ebay.myriad.state;
import com.ebay.myriad.state.utils.StoreContext;
/**
* Interface implemented by all Myriad State Store implementations
*/
public interface MyriadStateStore {
StoreContext loadMyriadState() throws Exception;
void storeMyriadState(StoreContext storeContext) throws Exception;
}
| apache-2.0 |
meiercaleb/incubator-rya | common/rya.api/src/main/java/org/apache/rya/api/persist/utils/RyaDAOHelper.java | 7127 | package org.apache.rya.api.persist.utils;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import info.aduna.iteration.CloseableIteration;
import org.apache.rya.api.RdfCloudTripleStoreConfiguration;
import org.apache.rya.api.RdfCloudTripleStoreUtils;
import org.apache.rya.api.domain.RyaStatement;
import org.apache.rya.api.persist.RyaDAO;
import org.apache.rya.api.persist.RyaDAOException;
import org.apache.rya.api.resolver.RdfToRyaConversions;
import org.apache.rya.api.resolver.RyaToRdfConversions;
import org.apache.rya.api.utils.NullableStatementImpl;
import org.openrdf.model.Resource;
import org.openrdf.model.Statement;
import org.openrdf.model.URI;
import org.openrdf.model.Value;
import org.openrdf.query.BindingSet;
import org.openrdf.query.QueryEvaluationException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;
import java.util.NoSuchElementException;
/**
* Date: 7/20/12
* Time: 10:36 AM
*/
public class RyaDAOHelper {
public static CloseableIteration<Statement, QueryEvaluationException> query(RyaDAO ryaDAO, Resource subject, URI predicate, Value object, RdfCloudTripleStoreConfiguration conf, Resource... contexts) throws QueryEvaluationException {
return query(ryaDAO, new NullableStatementImpl(subject, predicate, object, contexts), conf);
}
public static CloseableIteration<Statement, QueryEvaluationException> query(RyaDAO ryaDAO, Statement stmt, RdfCloudTripleStoreConfiguration conf) throws QueryEvaluationException {
final CloseableIteration<RyaStatement, RyaDAOException> query;
try {
query = ryaDAO.getQueryEngine().query(RdfToRyaConversions.convertStatement(stmt),
conf);
} catch (RyaDAOException e) {
throw new QueryEvaluationException(e);
}
//TODO: only support one context for now
return new CloseableIteration<Statement, QueryEvaluationException>() { //TODO: Create a new class struct for this
private boolean isClosed = false;
@Override
public void close() throws QueryEvaluationException {
try {
isClosed = true;
query.close();
} catch (RyaDAOException e) {
throw new QueryEvaluationException(e);
}
}
@Override
public boolean hasNext() throws QueryEvaluationException {
try {
return query.hasNext();
} catch (RyaDAOException e) {
throw new QueryEvaluationException(e);
}
}
@Override
public Statement next() throws QueryEvaluationException {
if (!hasNext() || isClosed) {
throw new NoSuchElementException();
}
try {
RyaStatement next = query.next();
if (next == null) {
return null;
}
return RyaToRdfConversions.convertStatement(next);
} catch (RyaDAOException e) {
throw new QueryEvaluationException(e);
}
}
@Override
public void remove() throws QueryEvaluationException {
try {
query.remove();
} catch (RyaDAOException e) {
throw new QueryEvaluationException(e);
}
}
};
}
public static CloseableIteration<? extends Map.Entry<Statement, BindingSet>, QueryEvaluationException> query(RyaDAO ryaDAO, Collection<Map.Entry<Statement, BindingSet>> statements, RdfCloudTripleStoreConfiguration conf) throws QueryEvaluationException {
Collection<Map.Entry<RyaStatement, BindingSet>> ryaStatements = new ArrayList<Map.Entry<RyaStatement, BindingSet>>(statements.size());
for (Map.Entry<Statement, BindingSet> entry : statements) {
ryaStatements.add(new RdfCloudTripleStoreUtils.CustomEntry<RyaStatement, BindingSet>
(RdfToRyaConversions.convertStatement(entry.getKey()), entry.getValue()));
}
final CloseableIteration<? extends Map.Entry<RyaStatement, BindingSet>, RyaDAOException> query;
try {
query = ryaDAO.getQueryEngine().queryWithBindingSet(ryaStatements, conf);
} catch (RyaDAOException e) {
throw new QueryEvaluationException(e);
}
return new CloseableIteration<Map.Entry<Statement, BindingSet>, QueryEvaluationException>() { //TODO: Create a new class struct for this
private boolean isClosed = false;
@Override
public void close() throws QueryEvaluationException {
isClosed = true;
try {
query.close();
} catch (RyaDAOException e) {
throw new QueryEvaluationException(e);
}
}
@Override
public boolean hasNext() throws QueryEvaluationException {
try {
return query.hasNext();
} catch (RyaDAOException e) {
throw new QueryEvaluationException(e);
}
}
@Override
public Map.Entry<Statement, BindingSet> next() throws QueryEvaluationException {
if (!hasNext() || isClosed) {
throw new NoSuchElementException();
}
try {
Map.Entry<RyaStatement, BindingSet> next = query.next();
if (next == null) {
return null;
}
return new RdfCloudTripleStoreUtils.CustomEntry<Statement, BindingSet>(RyaToRdfConversions.convertStatement(next.getKey()), next.getValue());
} catch (RyaDAOException e) {
throw new QueryEvaluationException(e);
}
}
@Override
public void remove() throws QueryEvaluationException {
try {
query.remove();
} catch (RyaDAOException e) {
throw new QueryEvaluationException(e);
}
}
};
}
}
| apache-2.0 |
apache/directory-kerby | kerby-kerb/kerb-core/src/main/java/org/apache/kerby/kerberos/kerb/type/base/AuthToken.java | 3363 | /**
* 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.kerby.kerberos.kerb.type.base;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
* This is the token definition API according to TokenPreauth draft.
*/
public interface AuthToken {
/**
* Get the token subject
* @return token subject
*/
String getSubject();
/**
* Set token subject
* @param sub The token subject
*/
void setSubject(String sub);
/**
* Get the token issuer
* @return token issuer
*/
String getIssuer();
/**
* Set token issuer
* @param issuer The token issuer
*/
void setIssuer(String issuer);
/**
* Get token audiences
* @return token audiences
*/
List<String> getAudiences();
/**
* Set token audiences
* @param audiences The token audiences
*/
void setAudiences(List<String> audiences);
/**
* Is an Identity Token ?
* @return true if it's an identity token, false otherwise
*/
boolean isIdToken();
void isIdToken(boolean isIdToken);
/**
* Is an Access Token ?
* @return true if it's an access token, false otherwise
*/
boolean isAcToken();
void isAcToken(boolean isAcToken);
/**
* Is a Bearer Token ?
* @return true if it's an bearer token, false otherwise
*/
boolean isBearerToken();
/**
* Is an Holder-of-Key Token (HOK) ?
* @return true if it's a HOK token, false otherwise
*/
boolean isHolderOfKeyToken();
/**
* Get token expired data time.
* @return expired time
*/
Date getExpiredTime();
/**
* Set token expired time
* @param exp The token expired time
*/
void setExpirationTime(Date exp);
/**
* Get token not before time.
* @return not before time
*/
Date getNotBeforeTime();
/**
* Set token not before time.
* @param nbt The time
*/
void setNotBeforeTime(Date nbt);
/**
* Get token issued at time when the token is issued.
* @return issued at time
*/
Date getIssueTime();
/**
* Set token issued at time.
* @param iat Time time when token issued
*/
void setIssueTime(Date iat);
/**
* Get token attributes.
* @return token attributes
*/
Map<String, Object> getAttributes();
/**
* Add a token attribute.
* @param name The attribute name
* @param value The attribute value
*/
void addAttribute(String name, Object value);
}
| apache-2.0 |
hurricup/intellij-community | platform/platform-impl/src/com/intellij/openapi/progress/util/AbstractProgressIndicatorExBase.java | 9467 | /*
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.progress.util;
import com.intellij.openapi.application.*;
import com.intellij.openapi.application.impl.LaterInvocator;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.TaskInfo;
import com.intellij.openapi.wm.ex.ProgressIndicatorEx;
import com.intellij.ui.GuiUtils;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.WeakList;
import org.jetbrains.annotations.NotNull;
import java.util.List;
public class AbstractProgressIndicatorExBase extends AbstractProgressIndicatorBase implements ProgressIndicatorEx {
private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.progress.util.ProgressIndicatorBase");
private static final IndicatorAction CHECK_CANCELED_ACTION = new IndicatorAction() {
@Override
public void execute(@NotNull ProgressIndicatorEx each) {
each.checkCanceled();
}
};
private static final IndicatorAction STOP_ACTION = new IndicatorAction() {
@Override
public void execute(@NotNull final ProgressIndicatorEx each) {
each.stop();
}
};
private static final IndicatorAction START_ACTION = new IndicatorAction() {
@Override
public void execute(@NotNull final ProgressIndicatorEx each) {
each.start();
}
};
private static final IndicatorAction CANCEL_ACTION = new IndicatorAction() {
@Override
public void execute(@NotNull final ProgressIndicatorEx each) {
each.cancel();
}
};
private static final IndicatorAction PUSH_ACTION = new IndicatorAction() {
@Override
public void execute(@NotNull final ProgressIndicatorEx each) {
each.pushState();
}
};
private static final IndicatorAction POP_ACTION = new IndicatorAction() {
@Override
public void execute(@NotNull final ProgressIndicatorEx each) {
each.popState();
}
};
private static final IndicatorAction STARTNC_ACTION = new IndicatorAction() {
@Override
public void execute(@NotNull final ProgressIndicatorEx each) {
each.startNonCancelableSection();
}
};
private static final IndicatorAction FINISHNC_ACTION = new IndicatorAction() {
@Override
public void execute(@NotNull final ProgressIndicatorEx each) {
each.finishNonCancelableSection();
}
};
protected final boolean myReusable;
private volatile boolean myModalityEntered;
private volatile List<ProgressIndicatorEx> myStateDelegates;
private volatile WeakList<TaskInfo> myFinished;
private volatile boolean myWasStarted;
private TaskInfo myOwnerTask;
public AbstractProgressIndicatorExBase(boolean reusable) {
myReusable = reusable;
}
public AbstractProgressIndicatorExBase() {
this(false);
}
@Override
public void start() {
synchronized (this) {
super.start();
delegateRunningChange(START_ACTION);
}
myWasStarted = true;
enterModality();
}
protected final void enterModality() {
if (myModalityProgress == this) {
ModalityState modalityState = ModalityState.defaultModalityState();
if (!myModalityEntered &&
!ApplicationManager.getApplication().isDispatchThread() &&
!((TransactionGuardImpl)TransactionGuard.getInstance()).isWriteSafeModality(modalityState)) {
// exceptions here should be assigned to Peter
LOG.error("Non-modal progress should be started in a write-safe context: an action or modality-aware invokeLater. See also TransactionGuard documentation.");
}
GuiUtils.invokeLaterIfNeeded(this::doEnterModality, modalityState);
}
}
private void doEnterModality() {
if (!myModalityEntered) {
LaterInvocator.enterModal(this);
myModalityEntered = true;
}
}
@Override
public void stop() {
super.stop();
delegateRunningChange(STOP_ACTION);
exitModality();
}
protected final void exitModality() {
if (myModalityProgress == this) {
GuiUtils.invokeLaterIfNeeded(this::doExitModality, ModalityState.defaultModalityState());
}
}
private void doExitModality() {
if (myModalityEntered) {
myModalityEntered = false;
LaterInvocator.leaveModal(this);
}
}
@Override
public void cancel() {
super.cancel();
delegateRunningChange(CANCEL_ACTION);
}
@Override
public boolean isCanceled() {
return super.isCanceled();
}
@Override
public void finish(@NotNull final TaskInfo task) {
WeakList<TaskInfo> finished = myFinished;
if (finished == null) {
synchronized (this) {
finished = myFinished;
if (finished == null) {
myFinished = finished = new WeakList<>();
}
}
}
if (!finished.addIfAbsent(task)) return;
delegateRunningChange(new IndicatorAction() {
@Override
public void execute(@NotNull final ProgressIndicatorEx each) {
each.finish(task);
}
});
}
@Override
public boolean isFinished(@NotNull final TaskInfo task) {
List<TaskInfo> list = myFinished;
return list != null && list.contains(task);
}
protected void setOwnerTask(TaskInfo owner) {
myOwnerTask = owner;
}
@Override
public void processFinish() {
if (myOwnerTask != null) {
finish(myOwnerTask);
myOwnerTask = null;
}
}
@Override
public final void checkCanceled() {
super.checkCanceled();
delegate(CHECK_CANCELED_ACTION);
}
@Override
public void setText(final String text) {
super.setText(text);
delegateProgressChange(new IndicatorAction() {
@Override
public void execute(@NotNull final ProgressIndicatorEx each) {
each.setText(text);
}
});
}
@Override
public void setText2(final String text) {
super.setText2(text);
delegateProgressChange(new IndicatorAction() {
@Override
public void execute(@NotNull final ProgressIndicatorEx each) {
each.setText2(text);
}
});
}
@Override
public void setFraction(final double fraction) {
super.setFraction(fraction);
delegateProgressChange(new IndicatorAction() {
@Override
public void execute(@NotNull final ProgressIndicatorEx each) {
each.setFraction(fraction);
}
});
}
@Override
public synchronized void pushState() {
super.pushState();
delegateProgressChange(PUSH_ACTION);
}
@Override
public synchronized void popState() {
super.popState();
delegateProgressChange(POP_ACTION);
}
@Override
public void startNonCancelableSection() {
super.startNonCancelableSection();
delegateProgressChange(STARTNC_ACTION);
}
@Override
public void finishNonCancelableSection() {
super.finishNonCancelableSection();
delegateProgressChange(FINISHNC_ACTION);
}
@Override
protected boolean isReuseable() {
return myReusable;
}
@Override
public void setIndeterminate(final boolean indeterminate) {
super.setIndeterminate(indeterminate);
delegateProgressChange(new IndicatorAction() {
@Override
public void execute(@NotNull final ProgressIndicatorEx each) {
each.setIndeterminate(indeterminate);
}
});
}
@Override
public final void addStateDelegate(@NotNull ProgressIndicatorEx delegate) {
delegate.initStateFrom(this);
synchronized (this) {
List<ProgressIndicatorEx> stateDelegates = myStateDelegates;
if (stateDelegates == null) {
myStateDelegates = stateDelegates = ContainerUtil.createLockFreeCopyOnWriteList();
}
else {
LOG.assertTrue(!stateDelegates.contains(delegate), "Already registered: " + delegate);
}
stateDelegates.add(delegate);
}
}
protected void delegateProgressChange(@NotNull IndicatorAction action) {
delegate(action);
onProgressChange();
}
protected void delegateRunningChange(@NotNull IndicatorAction action) {
delegate(action);
onRunningChange();
}
private void delegate(@NotNull IndicatorAction action) {
List<ProgressIndicatorEx> list = myStateDelegates;
if (list != null && !list.isEmpty()) {
for (ProgressIndicatorEx each : list) {
action.execute(each);
}
}
}
protected void onProgressChange() {
}
protected void onRunningChange() {
}
@Override
public boolean isModalityEntered() {
return myModalityEntered;
}
@Override
public synchronized void initStateFrom(@NotNull final ProgressIndicator indicator) {
super.initStateFrom(indicator);
if (indicator instanceof ProgressIndicatorEx) {
myModalityEntered = ((ProgressIndicatorEx)indicator).isModalityEntered();
}
}
@Override
public boolean wasStarted() {
return myWasStarted;
}
protected interface IndicatorAction {
void execute(@NotNull ProgressIndicatorEx each);
}
}
| apache-2.0 |
olamy/archiva | archiva-modules/archiva-base/archiva-mock/src/main/java/org/apache/archiva/mock/MockProxyConnectorAdmin.java | 2405 | package org.apache.archiva.mock;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.archiva.admin.model.AuditInformation;
import org.apache.archiva.admin.model.RepositoryAdminException;
import org.apache.archiva.admin.model.beans.ProxyConnector;
import org.apache.archiva.admin.model.proxyconnector.ProxyConnectorAdmin;
import java.util.Collections;
import java.util.List;
import java.util.Map;
/**
* @author Olivier Lamy
*/
public class MockProxyConnectorAdmin
implements ProxyConnectorAdmin
{
@Override
public List<ProxyConnector> getProxyConnectors()
throws RepositoryAdminException
{
return Collections.emptyList();
}
@Override
public ProxyConnector getProxyConnector( String sourceRepoId, String targetRepoId )
throws RepositoryAdminException
{
return null;
}
@Override
public Boolean addProxyConnector( ProxyConnector proxyConnector, AuditInformation auditInformation )
throws RepositoryAdminException
{
return Boolean.FALSE;
}
@Override
public Boolean deleteProxyConnector( ProxyConnector proxyConnector, AuditInformation auditInformation )
throws RepositoryAdminException
{
return Boolean.FALSE;
}
@Override
public Boolean updateProxyConnector( ProxyConnector proxyConnector, AuditInformation auditInformation )
throws RepositoryAdminException
{
return Boolean.FALSE;
}
@Override
public Map<String, List<ProxyConnector>> getProxyConnectorAsMap()
throws RepositoryAdminException
{
return Collections.emptyMap();
}
}
| apache-2.0 |
janstey/fabric8 | gateway/gateway-core/src/main/java/io/fabric8/gateway/handlers/detecting/protocol/openwire/command/SessionId.java | 3077 | /**
* Copyright 2005-2014 Red Hat, Inc.
*
* Red Hat licenses this file to you under the Apache License, version
* 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package io.fabric8.gateway.handlers.detecting.protocol.openwire.command;
import org.fusesource.hawtbuf.UTF8Buffer;
/**
*
* @openwire:marshaller code="121"
*/
public class SessionId implements DataStructure {
public static final byte DATA_STRUCTURE_TYPE = CommandTypes.SESSION_ID;
protected UTF8Buffer connectionId;
protected long value;
protected transient int hashCode;
protected transient String key;
protected transient ConnectionId parentId;
public SessionId() {
}
public SessionId(ConnectionId connectionId, long sessionId) {
this.connectionId = connectionId.getValue();
this.value = sessionId;
}
public SessionId(SessionId id) {
this.connectionId = id.getConnectionId();
this.value = id.getValue();
}
public SessionId(ProducerId id) {
this.connectionId = id.getConnectionId();
this.value = id.getSessionId();
}
public SessionId(ConsumerId id) {
this.connectionId = id.getConnectionId();
this.value = id.getSessionId();
}
public ConnectionId getParentId() {
if (parentId == null) {
parentId = new ConnectionId(this);
}
return parentId;
}
public int hashCode() {
if (hashCode == 0) {
hashCode = connectionId.hashCode() ^ (int)value;
}
return hashCode;
}
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || o.getClass() != SessionId.class) {
return false;
}
SessionId id = (SessionId)o;
return value == id.value && connectionId.equals(id.connectionId);
}
public byte getDataStructureType() {
return DATA_STRUCTURE_TYPE;
}
/**
* @openwire:property version=1 cache=true
*/
public UTF8Buffer getConnectionId() {
return connectionId;
}
public void setConnectionId(UTF8Buffer connectionId) {
this.connectionId = connectionId;
}
/**
* @openwire:property version=1
*/
public long getValue() {
return value;
}
public void setValue(long sessionId) {
this.value = sessionId;
}
public String toString() {
if (key == null) {
key = connectionId + ":" + value;
}
return key;
}
public boolean isMarshallAware() {
return false;
}
}
| apache-2.0 |
jwren/intellij-community | plugins/maven/src/test/java/org/jetbrains/idea/maven/dom/MavenModelReadingAndWritingTest.java | 4692 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.idea.maven.dom;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiManager;
import com.intellij.psi.codeStyle.CodeStyleManager;
import com.intellij.util.IncorrectOperationException;
import com.intellij.maven.testFramework.MavenMultiVersionImportingTestCase;
import org.jetbrains.idea.maven.dom.model.MavenDomDependency;
import org.jetbrains.idea.maven.dom.model.MavenDomProjectModel;
import org.junit.Test;
public class MavenModelReadingAndWritingTest extends MavenMultiVersionImportingTestCase {
@Override
protected void setUp() throws Exception {
super.setUp();
importProject("<groupId>test</groupId>" +
"<artifactId>project</artifactId>" +
"<version>1</version>");
}
@Test
public void testReading() {
MavenDomProjectModel model = getDomModel();
assertEquals("test", model.getGroupId().getStringValue());
assertEquals("project", model.getArtifactId().getStringValue());
assertEquals("1", model.getVersion().getStringValue());
}
@Test
public void testWriting() throws Exception {
CommandProcessor.getInstance().executeCommand(myProject, () -> ApplicationManager.getApplication().runWriteAction(() -> {
MavenDomProjectModel model = getDomModel();
model.getGroupId().setStringValue("foo");
model.getArtifactId().setStringValue("bar");
model.getVersion().setStringValue("baz");
formatAndSaveProjectPomDocument();
}), null, null);
assertSameLines("<?xml version=\"1.0\"?>\r\n" +
"<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\r\n" +
" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\r\n" +
" <modelVersion>4.0.0</modelVersion>\r\n" +
" <groupId>foo</groupId>\r\n" +
" <artifactId>bar</artifactId>\r\n" +
" <version>baz</version>\r\n" +
"</project>",
VfsUtil.loadText(myProjectPom));
}
@Test
public void testAddingADependency() throws Exception {
CommandProcessor.getInstance().executeCommand(myProject, () -> ApplicationManager.getApplication().runWriteAction(() -> {
MavenDomProjectModel model = getDomModel();
MavenDomDependency d = model.getDependencies().addDependency();
d.getGroupId().setStringValue("group");
d.getArtifactId().setStringValue("artifact");
d.getVersion().setStringValue("version");
formatAndSaveProjectPomDocument();
}), null, null);
assertSameLines("<?xml version=\"1.0\"?>\r\n" +
"<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\r\n" +
" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\r\n" +
" <modelVersion>4.0.0</modelVersion>\r\n" +
" <groupId>test</groupId>\r\n" +
" <artifactId>project</artifactId>\r\n" +
" <version>1</version>\r\n" +
" <dependencies>\r\n" +
" <dependency>\r\n" +
" <groupId>group</groupId>\r\n" +
" <artifactId>artifact</artifactId>\r\n" +
" <version>version</version>\r\n" +
" </dependency>\r\n" +
" </dependencies>\r\n" +
"</project>", VfsUtil.loadText(myProjectPom));
}
private MavenDomProjectModel getDomModel() {
return MavenDomUtil.getMavenDomProjectModel(myProject, myProjectPom);
}
private void formatAndSaveProjectPomDocument() {
try {
PsiFile psiFile = PsiManager.getInstance(myProject).findFile(myProjectPom);
CodeStyleManager.getInstance(myProject).reformat(psiFile);
Document d = FileDocumentManager.getInstance().getDocument(myProjectPom);
FileDocumentManager.getInstance().saveDocument(d);
}
catch (IncorrectOperationException e) {
throw new RuntimeException(e);
}
}
}
| apache-2.0 |
narahari92/metamodel | csv/src/main/java/org/apache/metamodel/csv/CsvDataContext.java | 12699 | /**
* 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.metamodel.csv;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.util.List;
import org.apache.metamodel.MetaModelException;
import org.apache.metamodel.QueryPostprocessDataContext;
import org.apache.metamodel.UpdateScript;
import org.apache.metamodel.UpdateSummary;
import org.apache.metamodel.UpdateableDataContext;
import org.apache.metamodel.data.DataSet;
import org.apache.metamodel.data.EmptyDataSet;
import org.apache.metamodel.query.FilterItem;
import org.apache.metamodel.schema.Column;
import org.apache.metamodel.schema.Table;
import org.apache.metamodel.util.FileHelper;
import org.apache.metamodel.util.FileResource;
import org.apache.metamodel.util.Resource;
import org.apache.metamodel.util.ResourceUtils;
import org.apache.metamodel.util.UrlResource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.opencsv.CSVParserBuilder;
import com.opencsv.CSVReader;
import com.opencsv.ICSVParser;
import com.opencsv.RFC4180ParserBuilder;
/**
* DataContext implementation for reading CSV files.
*/
public final class CsvDataContext extends QueryPostprocessDataContext implements UpdateableDataContext {
private static final Logger logger = LoggerFactory.getLogger(CsvDataContext.class);
private final Object WRITE_LOCK = new Object();
private final Resource _resource;
private final CsvConfiguration _configuration;
private final boolean _writable;
/**
* Constructs a CSV DataContext based on a file
*
* The file provided can be either existing or non-existing. In the case of
* non-existing files, a file will be automatically created when a CREATE
* TABLE update is executed on the DataContext.
*
* @param file
* @param configuration
*/
public CsvDataContext(File file, CsvConfiguration configuration) {
if (file == null) {
throw new IllegalArgumentException("File cannot be null");
}
if (configuration == null) {
throw new IllegalArgumentException("CsvConfiguration cannot be null");
}
_resource = new FileResource(file);
_configuration = configuration;
_writable = true;
}
public CsvDataContext(Resource resource, CsvConfiguration configuration) {
if (resource == null) {
throw new IllegalArgumentException("File cannot be null");
}
if (configuration == null) {
throw new IllegalArgumentException("CsvConfiguration cannot be null");
}
_resource = resource;
_configuration = configuration;
_writable = !resource.isReadOnly();
}
/**
* Constructs a CSV DataContext based on a {@link URL}
*
* @param url
* @param configuration
*/
public CsvDataContext(URL url, CsvConfiguration configuration) {
_resource = new UrlResource(url);
_configuration = configuration;
_writable = false;
}
/**
* Constructs a CSV DataContext based on a file
*
* @param file
*/
public CsvDataContext(File file) {
this(file, new CsvConfiguration());
}
/**
* Constructs a CSV DataContext based on an {@link InputStream}
*
* @param inputStream
* @param configuration
*/
public CsvDataContext(InputStream inputStream, CsvConfiguration configuration) {
File file = createFileFromInputStream(inputStream, configuration.getEncoding());
_configuration = configuration;
_writable = false;
_resource = new FileResource(file);
}
/**
* Gets the CSV configuration used
*
* @return a CSV configuration
*/
public CsvConfiguration getConfiguration() {
return _configuration;
}
/**
* Gets the resource that is being read from.
*
* @return
*/
public Resource getResource() {
return _resource;
}
private static File createFileFromInputStream(InputStream inputStream, String encoding) {
final File file;
final File tempDir = FileHelper.getTempDir();
File fileCandidate = null;
boolean usableName = false;
int index = 0;
while (!usableName) {
index++;
fileCandidate = new File(tempDir, "metamodel" + index + ".csv");
usableName = !fileCandidate.exists();
}
file = fileCandidate;
final BufferedWriter writer = FileHelper.getBufferedWriter(file, encoding);
final BufferedReader reader = FileHelper.getBufferedReader(inputStream, encoding);
try {
file.createNewFile();
file.deleteOnExit();
boolean firstLine = true;
for (String line = reader.readLine(); line != null; line = reader.readLine()) {
if (firstLine) {
firstLine = false;
} else {
writer.write('\n');
}
writer.write(line);
}
} catch (IOException e) {
throw new IllegalStateException(e);
} finally {
FileHelper.safeClose(writer, reader);
}
return file;
}
@Override
protected Number executeCountQuery(Table table, List<FilterItem> whereItems, boolean functionApproximationAllowed) {
if (!functionApproximationAllowed) {
return null;
}
if (whereItems != null && !whereItems.isEmpty()) {
return null;
}
final long length = _resource.getSize();
if (length < 0) {
// METAMODEL-30: Sometimes the size of the resource is not known
return null;
}
return _resource.read(inputStream -> {
try {
// read up to 5 megs of the file and approximate number of
// lines based on that.
final int sampleSize = (int) Math.min(length, 1024 * 1024 * 5);
final int chunkSize = Math.min(sampleSize, 1024 * 1024);
int readSize = 0;
int newlines = 0;
int carriageReturns = 0;
byte[] byteBuffer = new byte[chunkSize];
char[] charBuffer = new char[chunkSize];
while (readSize < sampleSize) {
final int read = inputStream.read(byteBuffer);
if (read == -1) {
break;
} else {
readSize += read;
}
Reader reader = getReader(byteBuffer, _configuration.getEncoding());
reader.read(charBuffer);
for (char c : charBuffer) {
if ('\n' == c) {
newlines++;
} else if ('\r' == c) {
carriageReturns++;
}
}
}
int lines = Math.max(newlines, carriageReturns);
logger.info("Found {} lines breaks in {} bytes", lines, sampleSize);
long approxCount = (long) (lines * length / sampleSize);
return approxCount;
} catch (IOException e) {
logger.error("Unexpected error during COUNT(*) approximation", e);
throw new IllegalStateException(e);
}
});
}
private Reader getReader(byte[] byteBuffer, String encoding) throws UnsupportedEncodingException {
try {
return new InputStreamReader(new ByteArrayInputStream(byteBuffer), encoding);
} catch (UnsupportedEncodingException e1) {
// this may happen on more exotic encodings, but since this reader
// is only meant for finding newlines, we'll try again with UTF8
try {
return new InputStreamReader(new ByteArrayInputStream(byteBuffer), "UTF8");
} catch (UnsupportedEncodingException e2) {
throw e1;
}
}
}
@Override
public DataSet materializeMainSchemaTable(Table table, List<Column> columns, int maxRows) {
final int lineNumber = _configuration.getColumnNameLineNumber();
final int columnCount = table.getColumnCount();
final BufferedReader reader = FileHelper.getBufferedReader(_resource.read(), _configuration.getEncoding());
try {
// skip column header lines
for (int i = 0; i < lineNumber; i++) {
String line = reader.readLine();
if (line == null) {
FileHelper.safeClose(reader);
return EmptyDataSet.fromColumns(columns);
}
}
} catch (IOException e) {
FileHelper.safeClose(reader);
throw new MetaModelException("IOException occurred while reading from CSV resource: " + _resource, e);
}
final boolean failOnInconsistentRowLength = _configuration.isFailOnInconsistentRowLength();
final Integer maxRowsOrNull = (maxRows > 0 ? maxRows : null);
if (_configuration.isMultilineValues()) {
final CSVReader csvReader = createCsvReader(reader);
return new CsvDataSet(csvReader, columns, maxRowsOrNull, columnCount, failOnInconsistentRowLength);
}
return new SingleLineCsvDataSet(reader, createParser(), columns, maxRowsOrNull, columnCount,
failOnInconsistentRowLength);
}
private ICSVParser createParser() {
final ICSVParser parser;
if (_configuration.getEscapeChar() == _configuration.getQuoteChar()) {
parser = new RFC4180ParserBuilder().withSeparator(_configuration.getSeparatorChar())
.withQuoteChar(_configuration.getQuoteChar()).build();
} else {
parser = new CSVParserBuilder().withSeparator(_configuration.getSeparatorChar())
.withQuoteChar(_configuration.getQuoteChar()).withEscapeChar(_configuration.getEscapeChar())
.build();
}
return parser;
}
protected CSVReader createCsvReader(int skipLines) {
final Reader reader = FileHelper.getReader(_resource.read(), _configuration.getEncoding());
return new CSVReader(reader, skipLines, createParser());
}
protected CSVReader createCsvReader(BufferedReader reader) {
return new CSVReader(reader, CSVReader.DEFAULT_SKIP_LINES, createParser());
}
@Override
protected CsvSchema getMainSchema() throws MetaModelException {
CsvSchema schema = new CsvSchema(getMainSchemaName(), this);
if (_resource.isExists()) {
schema.setTable(new CsvTable(schema, _resource.getName()));
}
return schema;
}
@Override
protected String getMainSchemaName() {
return ResourceUtils.getParentName(_resource);
}
protected boolean isWritable() {
return _writable;
}
private void checkWritable() {
if (!isWritable()) {
throw new IllegalStateException(
"This CSV DataContext is not writable, as it based on a read-only resource.");
}
}
@Override
public UpdateSummary executeUpdate(UpdateScript update) {
checkWritable();
final CsvUpdateCallback callback = new CsvUpdateCallback(this);
synchronized (WRITE_LOCK) {
try {
update.run(callback);
} finally {
callback.close();
}
}
return callback.getUpdateSummary();
}
} | apache-2.0 |
pivotal-amurmann/geode | geode-core/src/main/java/org/apache/geode/internal/cache/CacheObserver.java | 5950 | /*
* 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.geode.internal.cache;
import java.nio.ByteBuffer;
import org.apache.geode.cache.RegionEvent;
/**
* This interface is used by testing/debugging code to be notified of query events. See the
* documentation for class CacheObserverHolder for details. Also the callback is issed only if the
* boolean ISSUE_CALLBACKS_TO_CACHE_OBSERVER present in org.apache.geode.internal.cache.LocalRegion
* is made true
*
*/
public interface CacheObserver {
/**
* Called just after the region's Map is cleared & before Listener callback is issued. The call to
* this method is synchronous
*/
void afterRegionClear(RegionEvent event);
/**
* Called just beforeclearing the DiskRegion.
*
*/
void beforeDiskClear();
/**
* callback to test flushing efficieny. This callback is issued just before the flushing of the
* buffer that is before writing data to the Oplog, but after setting the logical offsets in the
* DiskIds contained in the PendingWrite Buffer
*
*/
void goingToFlush();
/**
* called immediately after bytes are written to the disk Region. In case of asynch mode, it gets
* called immedaitely after the asynch writer has written it to disk & just before releasing the
* ByteBuffer to the pool.
*
*/
public void afterWritingBytes();
/**
*
* Compacting is about to compact
*/
public void beforeGoingToCompact();
/**
* Just finished Compacting
*
*/
public void afterHavingCompacted();
/**
* Callback just after calculating the conflated byte buffer. This function can get called only in
* the asynch mode where conflation can happen
*
* @param origBB Original ByteBuffer object for the operation without considering conflation
* @param conflatedBB Resultant ByteBuffer object after conflation
*/
public void afterConflation(ByteBuffer origBB, ByteBuffer conflatedBB);
/**
* Callback just after setting oplog offset . The Oplog Offset will be set to non negative number
* in case it is a synch mode operation as the offset for synch mode is available in the context
* of thread performing the operation & to -1 for an asynch mode of operation as in case of asynch
* mode of operation the actual offset is determined only when asynch writer performs the write
* operation.
*
* @param offset A non negative number for synch mode of operation indicating the start position
* in the Oplog for the operation & -1 for asynch mode of operation
*
*/
public void afterSettingOplogOffSet(long offset);
/**
* Callback given by the thread performing the operation which causes the switching of the Oplog.
* This function gets invoked before a new Oplog gets created. Thus if the compacting is on , this
* function will get called before the compacter thread gets notified
*
*/
public void beforeSwitchingOplog();
/**
* Callback given by the thread performing the operation which causes the switching of the Oplog.
* This function gets invoked after a new Oplog gets created. Thus if the compacting is on , this
* function will get called after the compacter thread has been notified & the switching thread
* has been able to create a new Oplog
*
*
*/
public void afterSwitchingOplog();
/**
* Callback given by the thread which creates krfs.
*/
public void afterKrfCreated();
/**
* Callback given immediately before any thread invokes ComplexDiskRegion.OplogCompactor's
* stopCompactor method. This method normally gets invoked by clear/destory/close methods of the
* region.
*
*/
public void beforeStoppingCompactor();
/**
* Callback given immediately after any thread invokes ComplexDiskRegion.OplogCompactor's
* stopCompactor method. This method normally gets invoked by clear/destory/close methods of the
* region.
*
*/
public void afterStoppingCompactor();
/**
* Callback given immediately after the ComplexDiskRegion.OplogCompactor's stopCompactor method
* signals the compactor to stop.
*
*/
public void afterSignallingCompactor();
/**
* Called when GII begins
*/
public void afterMarkingGIIStarted();
/**
* Called when GII ends
*/
public void afterMarkingGIICompleted();
/**
* Called after the Oplog.WriterThread (asynch writer thread) swaps the pendingFlushMap and
* pendingWriteMap for flushing.
*/
public void afterSwitchingWriteAndFlushMaps();
/**
* Invoked just before setting the LBHTree reference in the thread local.
*/
public void beforeSettingDiskRef();
/**
* Invoked just after setting the LBHTree reference in the thread local.
*/
public void afterSettingDiskRef();
/**
* Invoked by the compactor thread just before deleting a compacted oplog
*
* @param compactedOplog
*/
public void beforeDeletingCompactedOplog(Oplog compactedOplog);
/**
* Invoked just before deleting an empty oplog
*
* @param emptyOplog
*/
public void beforeDeletingEmptyOplog(Oplog emptyOplog);
/**
* Invoked just before ShutdownAll operation
*/
void beforeShutdownAll();
}
| apache-2.0 |
janstey/fabric8 | gateway/gateway-core/src/main/java/io/fabric8/gateway/handlers/detecting/protocol/openwire/codec/v1/LastPartialCommandMarshaller.java | 3673 | /**
* Copyright 2005-2014 Red Hat, Inc.
*
* Red Hat licenses this file to you under the Apache License, version
* 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package io.fabric8.gateway.handlers.detecting.protocol.openwire.codec.v1;
import io.fabric8.gateway.handlers.detecting.protocol.openwire.codec.BooleanStream;
import io.fabric8.gateway.handlers.detecting.protocol.openwire.codec.OpenWireFormat;
import io.fabric8.gateway.handlers.detecting.protocol.openwire.command.DataStructure;
import io.fabric8.gateway.handlers.detecting.protocol.openwire.command.LastPartialCommand;
import org.fusesource.hawtbuf.DataByteArrayInputStream;
import org.fusesource.hawtbuf.DataByteArrayOutputStream;
import java.io.IOException;
/**
* Marshalling code for Open Wire Format for LastPartialCommandMarshaller
*
*
* NOTE!: This file is auto generated - do not modify!
* Modify the 'apollo-openwire-generator' module instead.
*
*/
public class LastPartialCommandMarshaller extends PartialCommandMarshaller {
/**
* Return the type of Data Structure we marshal
* @return short representation of the type data structure
*/
public byte getDataStructureType() {
return LastPartialCommand.DATA_STRUCTURE_TYPE;
}
/**
* @return a new object instance
*/
public DataStructure createObject() {
return new LastPartialCommand();
}
/**
* Un-marshal an object instance from the data input stream
*
* @param o the object to un-marshal
* @param dataIn the data input stream to build the object from
* @throws IOException
*/
public void tightUnmarshal(OpenWireFormat wireFormat, Object o, DataByteArrayInputStream dataIn, BooleanStream bs) throws IOException {
super.tightUnmarshal(wireFormat, o, dataIn, bs);
}
/**
* Write the booleans that this object uses to a BooleanStream
*/
public int tightMarshal1(OpenWireFormat wireFormat, Object o, BooleanStream bs) throws IOException {
int rc = super.tightMarshal1(wireFormat, o, bs);
return rc + 0;
}
/**
* Write a object instance to data output stream
*
* @param o the instance to be marshaled
* @param dataOut the output stream
* @throws IOException thrown if an error occurs
*/
public void tightMarshal2(OpenWireFormat wireFormat, Object o, DataByteArrayOutputStream dataOut, BooleanStream bs) throws IOException {
super.tightMarshal2(wireFormat, o, dataOut, bs);
}
/**
* Un-marshal an object instance from the data input stream
*
* @param o the object to un-marshal
* @param dataIn the data input stream to build the object from
* @throws IOException
*/
public void looseUnmarshal(OpenWireFormat wireFormat, Object o, DataByteArrayInputStream dataIn) throws IOException {
super.looseUnmarshal(wireFormat, o, dataIn);
}
/**
* Write the booleans that this object uses to a BooleanStream
*/
public void looseMarshal(OpenWireFormat wireFormat, Object o, DataByteArrayOutputStream dataOut) throws IOException {
super.looseMarshal(wireFormat, o, dataOut);
}
}
| apache-2.0 |
pax95/camel | core/camel-management/src/test/java/org/apache/camel/management/ManagedBrowsableEndpointAsXmlFileTest.java | 2413 | /*
* 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.management;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import org.apache.camel.Exchange;
import org.apache.camel.builder.RouteBuilder;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledOnOs;
import org.junit.jupiter.api.condition.OS;
import static org.apache.camel.management.DefaultManagementObjectNameStrategy.TYPE_ENDPOINT;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
@DisabledOnOs(OS.AIX)
public class ManagedBrowsableEndpointAsXmlFileTest extends ManagementTestSupport {
@Test
public void testBrowseableEndpointAsXmlAllIncludeBody() throws Exception {
template.sendBodyAndHeader("direct:start", "Hello World", Exchange.FILE_NAME, "hello.txt");
MBeanServer mbeanServer = getMBeanServer();
ObjectName name = getCamelObjectName(TYPE_ENDPOINT, "file://" + testDirectory());
String out = (String) mbeanServer.invoke(name, "browseAllMessagesAsXml", new Object[] { true },
new String[] { "java.lang.Boolean" });
assertNotNull(out);
log.info(out);
assertTrue(out.contains("Hello World</body>"), "Should contain the body");
}
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
@Override
public void configure() throws Exception {
context.setUseBreadcrumb(false);
from("direct:start").to(fileUri());
}
};
}
}
| apache-2.0 |
android-ia/platform_tools_idea | platform/lang-impl/src/com/intellij/codeInsight/documentation/DocumentationComponent.java | 29265 | /*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.codeInsight.documentation;
import com.intellij.codeInsight.CodeInsightBundle;
import com.intellij.codeInsight.hint.ElementLocationUtil;
import com.intellij.codeInsight.hint.HintManagerImpl;
import com.intellij.codeInsight.hint.HintUtil;
import com.intellij.icons.AllIcons;
import com.intellij.ide.DataManager;
import com.intellij.ide.actions.ExternalJavaDocAction;
import com.intellij.lang.documentation.CompositeDocumentationProvider;
import com.intellij.lang.documentation.DocumentationProvider;
import com.intellij.lang.documentation.ExternalDocumentationHandler;
import com.intellij.lang.documentation.ExternalDocumentationProvider;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.actionSystem.impl.ActionButton;
import com.intellij.openapi.application.ApplicationBundle;
import com.intellij.openapi.editor.colors.EditorColorsManager;
import com.intellij.openapi.editor.colors.EditorColorsScheme;
import com.intellij.openapi.editor.ex.EditorSettingsExternalizable;
import com.intellij.openapi.editor.ex.util.EditorUtil;
import com.intellij.openapi.options.FontSize;
import com.intellij.openapi.ui.popup.JBPopup;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.openapi.wm.ex.WindowManagerEx;
import com.intellij.psi.PsiElement;
import com.intellij.psi.SmartPointerManager;
import com.intellij.psi.SmartPsiElementPointer;
import com.intellij.ui.IdeBorderFactory;
import com.intellij.ui.SideBorder;
import com.intellij.ui.components.JBLayeredPane;
import com.intellij.ui.components.JBScrollPane;
import com.intellij.util.Consumer;
import com.intellij.util.containers.HashMap;
import com.intellij.util.ui.GraphicsUtil;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
import javax.swing.text.*;
import java.awt.*;
import java.awt.event.*;
import java.util.List;
import java.util.Stack;
public class DocumentationComponent extends JPanel implements Disposable, DataProvider {
private static final String DOCUMENTATION_TOPIC_ID = "reference.toolWindows.Documentation";
private static final DataContext EMPTY_DATA_CONTEXT = new DataContext() {
@Override
public Object getData(@NonNls String dataId) {
return null;
}
};
private static final int MAX_WIDTH = 500;
private static final int MAX_HEIGHT = 300;
private static final int MIN_HEIGHT = 45;
private DocumentationManager myManager;
private SmartPsiElementPointer myElement;
private final Stack<Context> myBackStack = new Stack<Context>();
private final Stack<Context> myForwardStack = new Stack<Context>();
private final ActionToolbar myToolBar;
private boolean myIsEmpty;
private boolean myIsShown;
private final JLabel myElementLabel;
private Style myFontSizeStyle;
private JSlider myFontSizeSlider;
private final JComponent mySettingsPanel;
private final MyShowSettingsButton myShowSettingsButton;
private boolean myIgnoreFontSizeSliderChange;
private static class Context {
final SmartPsiElementPointer element;
final String text;
final Rectangle viewRect;
public Context(SmartPsiElementPointer element, String text, Rectangle viewRect) {
this.element = element;
this.text = text;
this.viewRect = viewRect;
}
}
private final JScrollPane myScrollPane;
private final JEditorPane myEditorPane;
private String myText; // myEditorPane.getText() surprisingly crashes.., let's cache the text
private final JPanel myControlPanel;
private boolean myControlPanelVisible;
private final ExternalDocAction myExternalDocAction;
private Consumer<PsiElement> myNavigateCallback;
private JBPopup myHint;
private final HashMap<KeyStroke, ActionListener> myKeyboardActions = new HashMap<KeyStroke, ActionListener>();
// KeyStroke --> ActionListener
@Override
public boolean requestFocusInWindow() {
return myScrollPane.requestFocusInWindow();
}
@Override
public void requestFocus() {
myScrollPane.requestFocus();
}
public DocumentationComponent(final DocumentationManager manager, final AnAction[] additionalActions) {
myManager = manager;
myIsEmpty = true;
myIsShown = false;
myEditorPane = new JEditorPane(UIUtil.HTML_MIME, "") {
@Override
public Dimension getPreferredScrollableViewportSize() {
if (getWidth() == 0 || getHeight() == 0) {
setSize(MAX_WIDTH, MAX_HEIGHT);
}
Insets ins = myEditorPane.getInsets();
View rootView = myEditorPane.getUI().getRootView(myEditorPane);
rootView.setSize(MAX_WIDTH,
MAX_HEIGHT); // Necessary! Without this line, size will not increase then you go from small page to bigger one
int prefHeight = (int)rootView.getPreferredSpan(View.Y_AXIS);
prefHeight += ins.bottom + ins.top + myScrollPane.getHorizontalScrollBar().getMaximumSize().height;
return new Dimension(MAX_WIDTH, Math.max(MIN_HEIGHT, Math.min(MAX_HEIGHT, prefHeight)));
}
{
enableEvents(AWTEvent.KEY_EVENT_MASK);
}
@Override
protected void processKeyEvent(KeyEvent e) {
KeyStroke keyStroke = KeyStroke.getKeyStrokeForEvent(e);
ActionListener listener = myKeyboardActions.get(keyStroke);
if (listener != null) {
listener.actionPerformed(new ActionEvent(DocumentationComponent.this, 0, ""));
e.consume();
return;
}
super.processKeyEvent(e);
}
@Override
protected void paintComponent(Graphics g) {
GraphicsUtil.setupAntialiasing(g);
super.paintComponent(g);
}
};
DataProvider helpDataProvider = new DataProvider() {
@Override
public Object getData(@NonNls String dataId) {
return PlatformDataKeys.HELP_ID.is(dataId) ? DOCUMENTATION_TOPIC_ID : null;
}
};
myEditorPane.putClientProperty(DataManager.CLIENT_PROPERTY_DATA_PROVIDER, helpDataProvider);
myText = "";
myEditorPane.setEditable(false);
myEditorPane.setBackground(HintUtil.INFORMATION_COLOR);
myEditorPane.setEditorKit(UIUtil.getHTMLEditorKit());
myScrollPane = new JBScrollPane(myEditorPane) {
@Override
protected void processMouseWheelEvent(MouseWheelEvent e) {
if (!EditorSettingsExternalizable.getInstance().isWheelFontChangeEnabled() || !EditorUtil.isChangeFontSize(e)) {
super.processMouseWheelEvent(e);
return;
}
int change = Math.abs(e.getWheelRotation());
boolean increase = e.getWheelRotation() <= 0;
EditorColorsManager colorsManager = EditorColorsManager.getInstance();
EditorColorsScheme scheme = colorsManager.getGlobalScheme();
FontSize newFontSize = scheme.getQuickDocFontSize();
for (; change > 0; change--) {
if (increase) {
newFontSize = newFontSize.larger();
}
else {
newFontSize = newFontSize.smaller();
}
}
if (newFontSize == scheme.getQuickDocFontSize()) {
return;
}
scheme.setQuickDocFontSize(newFontSize);
applyFontSize();
setFontSizeSliderSize(newFontSize);
}
};
myScrollPane.setBorder(null);
myScrollPane.putClientProperty(DataManager.CLIENT_PROPERTY_DATA_PROVIDER, helpDataProvider);
final MouseAdapter mouseAdapter = new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
myManager.requestFocus();
myShowSettingsButton.hideSettings();
}
};
myEditorPane.addMouseListener(mouseAdapter);
Disposer.register(this, new Disposable() {
@Override
public void dispose() {
myEditorPane.removeMouseListener(mouseAdapter);
}
});
final FocusAdapter focusAdapter = new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
Component previouslyFocused = WindowManagerEx.getInstanceEx().getFocusedComponent(manager.getProject(getElement()));
if (!(previouslyFocused == myEditorPane)) {
if (myHint != null && !myHint.isDisposed()) myHint.cancel();
}
}
};
myEditorPane.addFocusListener(focusAdapter);
Disposer.register(this, new Disposable() {
@Override
public void dispose() {
myEditorPane.removeFocusListener(focusAdapter);
}
});
setLayout(new BorderLayout());
JLayeredPane layeredPane = new JBLayeredPane() {
@Override
public void doLayout() {
final Rectangle r = getBounds();
for (Component component : getComponents()) {
if (component instanceof JScrollPane) {
component.setBounds(0, 0, r.width, r.height);
}
else {
int insets = 2;
Dimension d = component.getPreferredSize();
component.setBounds(r.width - d.width - insets, insets, d.width, d.height);
}
}
}
@Override
public Dimension getPreferredSize() {
Dimension editorPaneSize = myEditorPane.getPreferredScrollableViewportSize();
Dimension controlPanelSize = myControlPanel.getPreferredSize();
return new Dimension(Math.max(editorPaneSize.width, controlPanelSize.width), editorPaneSize.height + controlPanelSize.height);
}
};
layeredPane.add(myScrollPane);
layeredPane.setLayer(myScrollPane, 0);
mySettingsPanel = createSettingsPanel();
layeredPane.add(mySettingsPanel);
layeredPane.setLayer(mySettingsPanel, JLayeredPane.POPUP_LAYER);
add(layeredPane, BorderLayout.CENTER);
setOpaque(true);
myScrollPane.setViewportBorder(JBScrollPane.createIndentBorder());
final DefaultActionGroup actions = new DefaultActionGroup();
final BackAction back = new BackAction();
final ForwardAction forward = new ForwardAction();
actions.add(back);
actions.add(forward);
actions.add(myExternalDocAction = new ExternalDocAction());
back.registerCustomShortcutSet(CustomShortcutSet.fromString("LEFT"), this);
forward.registerCustomShortcutSet(CustomShortcutSet.fromString("RIGHT"), this);
myExternalDocAction.registerCustomShortcutSet(CustomShortcutSet.fromString("UP"), this);
if (additionalActions != null) {
for (final AnAction action : additionalActions) {
actions.add(action);
}
}
myToolBar = ActionManager.getInstance().createActionToolbar(ActionPlaces.JAVADOC_TOOLBAR, actions, true);
myControlPanel = new JPanel();
myControlPanel.setLayout(new BorderLayout());
myControlPanel.setBorder(IdeBorderFactory.createBorder(SideBorder.BOTTOM));
JPanel dummyPanel = new JPanel();
myElementLabel = new JLabel();
dummyPanel.setLayout(new BorderLayout());
dummyPanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 5));
dummyPanel.add(myElementLabel, BorderLayout.EAST);
myControlPanel.add(myToolBar.getComponent(), BorderLayout.WEST);
myControlPanel.add(dummyPanel, BorderLayout.CENTER);
myControlPanel.add(myShowSettingsButton = new MyShowSettingsButton(), BorderLayout.EAST);
myControlPanelVisible = false;
final HyperlinkListener hyperlinkListener = new HyperlinkListener() {
@Override
public void hyperlinkUpdate(HyperlinkEvent e) {
HyperlinkEvent.EventType type = e.getEventType();
if (type == HyperlinkEvent.EventType.ACTIVATED) {
manager.navigateByLink(DocumentationComponent.this, e.getDescription());
}
}
};
myEditorPane.addHyperlinkListener(hyperlinkListener);
Disposer.register(this, new Disposable() {
@Override
public void dispose() {
myEditorPane.removeHyperlinkListener(hyperlinkListener);
}
});
registerActions();
updateControlState();
}
public DocumentationComponent(final DocumentationManager manager) {
this(manager, null);
}
@Override
public Object getData(@NonNls String dataId) {
if (DocumentationManager.SELECTED_QUICK_DOC_TEXT.getName().equals(dataId)) {
// Javadocs often contain symbols (non-breakable white space). We don't want to copy them as is and replace
// with raw white spaces. See IDEA-86633 for more details.
String selectedText = myEditorPane.getSelectedText();
return selectedText == null? null : selectedText.replace((char)160, ' ');
}
return null;
}
private JComponent createSettingsPanel() {
JPanel result = new JPanel(new FlowLayout(FlowLayout.RIGHT, 3, 0));
result.add(new JLabel(ApplicationBundle.message("label.font.size")));
myFontSizeSlider = new JSlider(JSlider.HORIZONTAL, 0, FontSize.values().length - 1, 3);
myFontSizeSlider.setMinorTickSpacing(1);
myFontSizeSlider.setPaintTicks(true);
myFontSizeSlider.setPaintTrack(true);
myFontSizeSlider.setSnapToTicks(true);
UIUtil.setSliderIsFilled(myFontSizeSlider, true);
result.add(myFontSizeSlider);
result.setBorder(BorderFactory.createLineBorder(UIUtil.getBorderColor(), 1));
myFontSizeSlider.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
if (myIgnoreFontSizeSliderChange) {
return;
}
EditorColorsManager colorsManager = EditorColorsManager.getInstance();
EditorColorsScheme scheme = colorsManager.getGlobalScheme();
scheme.setQuickDocFontSize(FontSize.values()[myFontSizeSlider.getValue()]);
applyFontSize();
}
});
String tooltipText = ApplicationBundle.message("quickdoc.tooltip.font.size.by.wheel");
result.setToolTipText(tooltipText);
myFontSizeSlider.setToolTipText(tooltipText);
result.setVisible(false);
result.setOpaque(true);
myFontSizeSlider.setOpaque(true);
return result;
}
private void setFontSizeSliderSize(FontSize fontSize) {
myIgnoreFontSizeSliderChange = true;
try {
FontSize[] sizes = FontSize.values();
for (int i = 0; i < sizes.length; i++) {
if (fontSize == sizes[i]) {
myFontSizeSlider.setValue(i);
break;
}
}
}
finally {
myIgnoreFontSizeSliderChange = false;
}
}
public synchronized boolean isEmpty() {
return myIsEmpty;
}
public synchronized void startWait() {
myIsEmpty = true;
}
private void setControlPanelVisible(boolean visible) {
if (visible == myControlPanelVisible) return;
if (visible) {
add(myControlPanel, BorderLayout.NORTH);
}
else {
remove(myControlPanel);
}
myControlPanelVisible = visible;
}
public void setHint(JBPopup hint) {
myHint = hint;
}
public JComponent getComponent() {
return myEditorPane;
}
@Nullable
public PsiElement getElement() {
return myElement != null ? myElement.getElement() : null;
}
public void setNavigateCallback(Consumer<PsiElement> navigateCallback) {
myNavigateCallback = navigateCallback;
}
public void setText(String text, @Nullable PsiElement element, boolean clearHistory) {
setText(text, element, false, clearHistory);
}
public void setText(String text, PsiElement element, boolean clean, boolean clearHistory) {
if (clean && myElement != null) {
myBackStack.push(saveContext());
myForwardStack.clear();
}
updateControlState();
setData(element, text, clearHistory);
if (clean) {
myIsEmpty = false;
}
if (clearHistory) clearHistory();
}
public void replaceText(String text, PsiElement element) {
if (element == null || getElement() != element) return;
setText(text, element, false);
if (!myBackStack.empty()) myBackStack.pop();
}
private void clearHistory() {
myForwardStack.clear();
myBackStack.clear();
}
public void setData(PsiElement _element, String text, final boolean clearHistory) {
if (myElement != null) {
myBackStack.push(saveContext());
myForwardStack.clear();
}
final SmartPsiElementPointer element = _element != null && _element.isValid()
? SmartPointerManager.getInstance(_element.getProject()).createSmartPsiElementPointer(_element)
: null;
if (element != null) {
myElement = element;
}
myIsEmpty = false;
updateControlState();
setDataInternal(element, text, new Rectangle(0, 0));
if (clearHistory) clearHistory();
}
private void setDataInternal(SmartPsiElementPointer element, String text, final Rectangle viewRect) {
setDataInternal(element, text, viewRect, false);
}
private void setDataInternal(SmartPsiElementPointer element, String text, final Rectangle viewRect, boolean skip) {
boolean justShown = false;
myElement = element;
if (!myIsShown && myHint != null) {
myEditorPane.setText(text);
applyFontSize();
myManager.showHint(myHint);
myIsShown = justShown = true;
}
if (!justShown) {
myEditorPane.setText(text);
applyFontSize();
}
if (!skip) {
myText = text;
}
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
myEditorPane.scrollRectToVisible(viewRect);
}
});
}
private void applyFontSize() {
Document document = myEditorPane.getDocument();
if (!(document instanceof StyledDocument)) {
return;
}
StyledDocument styledDocument = (StyledDocument)document;
if (myFontSizeStyle == null) {
myFontSizeStyle = styledDocument.addStyle("active", null);
}
EditorColorsManager colorsManager = EditorColorsManager.getInstance();
EditorColorsScheme scheme = colorsManager.getGlobalScheme();
StyleConstants.setFontSize(myFontSizeStyle, scheme.getQuickDocFontSize().getSize());
if (Registry.is("documentation.component.editor.font")) {
StyleConstants.setFontFamily(myFontSizeStyle, scheme.getEditorFontName());
}
styledDocument.setCharacterAttributes(0, document.getLength(), myFontSizeStyle, false);
}
private void goBack() {
if (myBackStack.isEmpty()) return;
Context context = myBackStack.pop();
myForwardStack.push(saveContext());
restoreContext(context);
updateControlState();
}
private void goForward() {
if (myForwardStack.isEmpty()) return;
Context context = myForwardStack.pop();
myBackStack.push(saveContext());
restoreContext(context);
updateControlState();
}
private Context saveContext() {
Rectangle rect = myScrollPane.getViewport().getViewRect();
return new Context(myElement, myText, rect);
}
private void restoreContext(Context context) {
setDataInternal(context.element, context.text, context.viewRect);
if (myNavigateCallback != null) {
final PsiElement element = context.element.getElement();
if (element != null) {
myNavigateCallback.consume(element);
}
}
}
private void updateControlState() {
ElementLocationUtil.customizeElementLabel(myElement != null ? myElement.getElement() : null, myElementLabel);
myToolBar.updateActionsImmediately(); // update faster
setControlPanelVisible(true);//(!myBackStack.isEmpty() || !myForwardStack.isEmpty());
}
private class BackAction extends AnAction implements HintManagerImpl.ActionToIgnore {
public BackAction() {
super(CodeInsightBundle.message("javadoc.action.back"), null, AllIcons.Actions.Back);
}
@Override
public void actionPerformed(AnActionEvent e) {
goBack();
}
@Override
public void update(AnActionEvent e) {
Presentation presentation = e.getPresentation();
presentation.setEnabled(!myBackStack.isEmpty());
}
}
private class ForwardAction extends AnAction implements HintManagerImpl.ActionToIgnore {
public ForwardAction() {
super(CodeInsightBundle.message("javadoc.action.forward"), null, AllIcons.Actions.Forward);
}
@Override
public void actionPerformed(AnActionEvent e) {
goForward();
}
@Override
public void update(AnActionEvent e) {
Presentation presentation = e.getPresentation();
presentation.setEnabled(!myForwardStack.isEmpty());
}
}
private class ExternalDocAction extends AnAction implements HintManagerImpl.ActionToIgnore {
public ExternalDocAction() {
super(CodeInsightBundle.message("javadoc.action.view.external"), null, AllIcons.Actions.Browser_externalJavaDoc);
registerCustomShortcutSet(ActionManager.getInstance().getAction(IdeActions.ACTION_EXTERNAL_JAVADOC).getShortcutSet(), null);
}
@Override
public void actionPerformed(AnActionEvent e) {
if (myElement != null) {
final PsiElement element = myElement.getElement();
final DocumentationProvider provider = DocumentationManager.getProviderFromElement(element);
final PsiElement originalElement = DocumentationManager.getOriginalElement(element);
boolean processed = false;
if (provider instanceof CompositeDocumentationProvider) {
for (final DocumentationProvider documentationProvider : ((CompositeDocumentationProvider)provider).getProviders()) {
if (documentationProvider instanceof ExternalDocumentationHandler && ((ExternalDocumentationHandler)documentationProvider).handleExternal(element, originalElement)) {
processed = true;
break;
}
}
}
if (!processed) {
final List<String> urls = provider.getUrlFor(element, originalElement);
assert urls != null : provider;
assert !urls.isEmpty() : provider;
ExternalJavaDocAction.showExternalJavadoc(urls);
}
}
}
@Override
public void update(AnActionEvent e) {
final Presentation presentation = e.getPresentation();
presentation.setEnabled(false);
if (myElement != null) {
final PsiElement element = myElement.getElement();
final DocumentationProvider provider = DocumentationManager.getProviderFromElement(element);
final PsiElement originalElement = DocumentationManager.getOriginalElement(element);
if (provider instanceof ExternalDocumentationProvider) {
presentation.setEnabled(element != null && ((ExternalDocumentationProvider)provider).hasDocumentationFor(element, originalElement));
}
else {
final List<String> urls = provider.getUrlFor(element, originalElement);
presentation.setEnabled(element != null && urls != null && !urls.isEmpty());
}
}
}
}
private void registerActions() {
myExternalDocAction
.registerCustomShortcutSet(ActionManager.getInstance().getAction(IdeActions.ACTION_EXTERNAL_JAVADOC).getShortcutSet(), myEditorPane);
myKeyboardActions.put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0), new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JScrollBar scrollBar = myScrollPane.getVerticalScrollBar();
int value = scrollBar.getValue() - scrollBar.getUnitIncrement(-1);
value = Math.max(value, 0);
scrollBar.setValue(value);
}
});
myKeyboardActions.put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0), new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JScrollBar scrollBar = myScrollPane.getVerticalScrollBar();
int value = scrollBar.getValue() + scrollBar.getUnitIncrement(+1);
value = Math.min(value, scrollBar.getMaximum());
scrollBar.setValue(value);
}
});
myKeyboardActions.put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JScrollBar scrollBar = myScrollPane.getHorizontalScrollBar();
int value = scrollBar.getValue() - scrollBar.getUnitIncrement(-1);
value = Math.max(value, 0);
scrollBar.setValue(value);
}
});
myKeyboardActions.put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0), new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JScrollBar scrollBar = myScrollPane.getHorizontalScrollBar();
int value = scrollBar.getValue() + scrollBar.getUnitIncrement(+1);
value = Math.min(value, scrollBar.getMaximum());
scrollBar.setValue(value);
}
});
myKeyboardActions.put(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP, 0), new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JScrollBar scrollBar = myScrollPane.getVerticalScrollBar();
int value = scrollBar.getValue() - scrollBar.getBlockIncrement(-1);
value = Math.max(value, 0);
scrollBar.setValue(value);
}
});
myKeyboardActions.put(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_DOWN, 0), new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JScrollBar scrollBar = myScrollPane.getVerticalScrollBar();
int value = scrollBar.getValue() + scrollBar.getBlockIncrement(+1);
value = Math.min(value, scrollBar.getMaximum());
scrollBar.setValue(value);
}
});
myKeyboardActions.put(KeyStroke.getKeyStroke(KeyEvent.VK_HOME, 0), new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JScrollBar scrollBar = myScrollPane.getHorizontalScrollBar();
scrollBar.setValue(0);
}
});
myKeyboardActions.put(KeyStroke.getKeyStroke(KeyEvent.VK_END, 0), new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JScrollBar scrollBar = myScrollPane.getHorizontalScrollBar();
scrollBar.setValue(scrollBar.getMaximum());
}
});
myKeyboardActions.put(KeyStroke.getKeyStroke(KeyEvent.VK_HOME, KeyEvent.CTRL_MASK), new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JScrollBar scrollBar = myScrollPane.getVerticalScrollBar();
scrollBar.setValue(0);
}
});
myKeyboardActions.put(KeyStroke.getKeyStroke(KeyEvent.VK_END, KeyEvent.CTRL_MASK), new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JScrollBar scrollBar = myScrollPane.getVerticalScrollBar();
scrollBar.setValue(scrollBar.getMaximum());
}
});
}
public String getText() {
return myText;
}
@Override
public void dispose() {
myBackStack.clear();
myForwardStack.clear();
myKeyboardActions.clear();
myElement = null;
myManager = null;
myHint = null;
myNavigateCallback = null;
}
private class MyShowSettingsButton extends ActionButton {
MyShowSettingsButton() {
this(new MyShowSettingsAction(), new Presentation(), ActionPlaces.JAVADOC_INPLACE_SETTINGS, ActionToolbar.DEFAULT_MINIMUM_BUTTON_SIZE);
}
MyShowSettingsButton(AnAction action, Presentation presentation, String place, @NotNull Dimension minimumSize) {
super(action, presentation, place, minimumSize);
myPresentation.setIcon(AllIcons.General.SecondaryGroup);
}
public void hideSettings() {
if (!mySettingsPanel.isVisible()) {
return;
}
AnActionEvent event = new AnActionEvent(
null, EMPTY_DATA_CONTEXT, ActionPlaces.JAVADOC_INPLACE_SETTINGS, myPresentation, ActionManager.getInstance(), 0
);
myAction.actionPerformed(event);
}
}
private class MyShowSettingsAction extends ToggleAction {
@Override
public boolean isSelected(AnActionEvent e) {
return mySettingsPanel.isVisible();
}
@Override
public void setSelected(AnActionEvent e, boolean state) {
if (!state) {
mySettingsPanel.setVisible(false);
return;
}
EditorColorsManager colorsManager = EditorColorsManager.getInstance();
EditorColorsScheme scheme = colorsManager.getGlobalScheme();
setFontSizeSliderSize(scheme.getQuickDocFontSize());
mySettingsPanel.setVisible(true);
}
}
}
| apache-2.0 |
hgschmie/presto | presto-main/src/test/java/io/prestosql/sql/planner/TestConnectorExpressionTranslator.java | 4792 | /*
* 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.prestosql.sql.planner;
import com.google.common.collect.ImmutableMap;
import io.prestosql.Session;
import io.prestosql.metadata.Metadata;
import io.prestosql.spi.expression.ConnectorExpression;
import io.prestosql.spi.expression.FieldDereference;
import io.prestosql.spi.expression.Variable;
import io.prestosql.spi.type.Type;
import io.prestosql.sql.parser.SqlParser;
import io.prestosql.sql.tree.DereferenceExpression;
import io.prestosql.sql.tree.Expression;
import io.prestosql.sql.tree.Identifier;
import io.prestosql.sql.tree.SymbolReference;
import io.prestosql.testing.TestingSession;
import org.testng.annotations.Test;
import java.util.Map;
import java.util.Optional;
import static com.google.common.collect.ImmutableMap.toImmutableMap;
import static io.prestosql.metadata.MetadataManager.createTestMetadataManager;
import static io.prestosql.spi.type.DoubleType.DOUBLE;
import static io.prestosql.spi.type.IntegerType.INTEGER;
import static io.prestosql.spi.type.RowType.field;
import static io.prestosql.spi.type.RowType.rowType;
import static io.prestosql.spi.type.VarcharType.createVarcharType;
import static io.prestosql.sql.planner.ConnectorExpressionTranslator.translate;
import static org.testng.Assert.assertEquals;
public class TestConnectorExpressionTranslator
{
private static final Session TEST_SESSION = TestingSession.testSessionBuilder().build();
private static final Metadata METADATA = createTestMetadataManager();
private static final TypeAnalyzer TYPE_ANALYZER = new TypeAnalyzer(new SqlParser(), METADATA);
private static final Type ROW_TYPE = rowType(field("int_symbol_1", INTEGER), field("varchar_symbol_1", createVarcharType(5)));
private static final LiteralEncoder LITERAL_ENCODER = new LiteralEncoder(METADATA);
private static final Map<Symbol, Type> symbols = ImmutableMap.<Symbol, Type>builder()
.put(new Symbol("double_symbol_1"), DOUBLE)
.put(new Symbol("row_symbol_1"), ROW_TYPE)
.build();
private static final TypeProvider TYPE_PROVIDER = TypeProvider.copyOf(symbols);
private static final Map<String, Symbol> variableMappings = symbols.entrySet().stream()
.collect(toImmutableMap(entry -> entry.getKey().getName(), Map.Entry::getKey));
@Test
public void testTranslationToConnectorExpression()
{
assertTranslationToConnectorExpression(new SymbolReference("double_symbol_1"), Optional.of(new Variable("double_symbol_1", DOUBLE)));
assertTranslationToConnectorExpression(
new DereferenceExpression(
new SymbolReference("row_symbol_1"),
new Identifier("int_symbol_1")),
Optional.of(
new FieldDereference(
INTEGER,
new Variable("row_symbol_1", ROW_TYPE),
0)));
}
@Test
public void testTranslationFromConnectorExpression()
{
assertTranslationFromConnectorExpression(new Variable("double_symbol_1", DOUBLE), new SymbolReference("double_symbol_1"));
assertTranslationFromConnectorExpression(
new FieldDereference(
INTEGER,
new Variable("row_symbol_1", ROW_TYPE),
0),
new DereferenceExpression(
new SymbolReference("row_symbol_1"),
new Identifier("int_symbol_1")));
}
private void assertTranslationToConnectorExpression(Expression expression, Optional<ConnectorExpression> connectorExpression)
{
Optional<ConnectorExpression> translation = translate(TEST_SESSION, expression, TYPE_ANALYZER, TYPE_PROVIDER);
assertEquals(connectorExpression.isPresent(), translation.isPresent());
translation.ifPresent(value -> assertEquals(value, connectorExpression.get()));
}
private void assertTranslationFromConnectorExpression(ConnectorExpression connectorExpression, Expression expected)
{
Expression translation = translate(connectorExpression, variableMappings, LITERAL_ENCODER);
assertEquals(translation, expected);
}
}
| apache-2.0 |
bings/lumify | data-mapping/core/src/main/java/io/lumify/mapping/predicate/AndPredicate.java | 2140 | package io.lumify.mapping.predicate;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeName;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* An implementation of MappingPredicate that matches input values
* if all sub-predicates match the input value.
* @param <T> the type of values being matched
*/
@JsonTypeName("and")
public final class AndPredicate<T> implements MappingPredicate<T> {
/**
* The predicates that will be and-ed.
*/
private final List<MappingPredicate<T>> predicates;
/**
* Create a new AndPredicate.
* @param preds the predicates to AND together
*/
public AndPredicate(final MappingPredicate<T>... preds) {
this(Arrays.asList(preds));
}
/**
* Create a new AndPredicate.
* @param preds the predicates to AND together
*/
@JsonCreator
public AndPredicate(@JsonProperty("predicates") final List<MappingPredicate<T>> preds) {
checkNotNull(preds, "predicates must be provided");
List<MappingPredicate<T>> myPreds = new ArrayList<MappingPredicate<T>>(preds);
// remove all null values from myPreds
while (myPreds.remove(null)) {}
checkArgument(!myPreds.isEmpty(), "at least one predicate must be provided");
this.predicates = Collections.unmodifiableList(myPreds);
}
@Override
public boolean matches(final T value) {
boolean match = true;
for (MappingPredicate<T> pred : predicates) {
if (!pred.matches(value)) {
match = false;
break;
}
}
return match;
}
@JsonProperty("predicates")
public List<MappingPredicate<T>> getPredicates() {
return predicates;
}
@Override
public String toString() {
return String.format("AND( %s )", predicates);
}
}
| apache-2.0 |
gureronder/midpoint | model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/helpers/ExpressionFilterHelper.java | 2219 | /*
* Copyright (c) 2010-2013 Evolveum
*
* 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.evolveum.midpoint.notifications.impl.helpers;
import com.evolveum.midpoint.notifications.api.NotificationManager;
import com.evolveum.midpoint.notifications.api.events.Event;
import com.evolveum.midpoint.schema.result.OperationResult;
import com.evolveum.midpoint.task.api.Task;
import com.evolveum.midpoint.util.logging.Trace;
import com.evolveum.midpoint.util.logging.TraceManager;
import com.evolveum.midpoint.xml.ns._public.common.common_3.EventHandlerType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ExpressionType;
import org.springframework.stereotype.Component;
/**
* @author mederly
*/
@Component
public class ExpressionFilterHelper extends BaseHelper {
private static final Trace LOGGER = TraceManager.getTrace(ExpressionFilterHelper.class);
@Override
public boolean processEvent(Event event, EventHandlerType eventHandlerType, NotificationManager notificationManager,
Task task, OperationResult result) {
if (eventHandlerType.getExpressionFilter().isEmpty()) {
return true;
}
logStart(LOGGER, event, eventHandlerType, eventHandlerType.getExpressionFilter());
boolean retval = true;
for (ExpressionType expressionType : eventHandlerType.getExpressionFilter()) {
if (!evaluateBooleanExpressionChecked(expressionType, getDefaultVariables(event, result),
"event filter expression", task, result)) {
retval = false;
break;
}
}
logEnd(LOGGER, event, eventHandlerType, retval);
return retval;
}
}
| apache-2.0 |
smartan/lucene | src/main/java/org/apache/lucene/index/FieldFilterAtomicReader.java | 5777 | package org.apache.lucene.index;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Set;
import org.apache.lucene.util.Bits;
import org.apache.lucene.util.FilterIterator;
/**
* A {@link FilterAtomicReader} that exposes only a subset
* of fields from the underlying wrapped reader.
*/
public final class FieldFilterAtomicReader extends FilterAtomicReader {
private final Set<String> fields;
private final boolean negate;
private final FieldInfos fieldInfos;
public FieldFilterAtomicReader(AtomicReader in, Set<String> fields, boolean negate) {
super(in);
this.fields = fields;
this.negate = negate;
ArrayList<FieldInfo> filteredInfos = new ArrayList<>();
for (FieldInfo fi : in.getFieldInfos()) {
if (hasField(fi.name)) {
filteredInfos.add(fi);
}
}
fieldInfos = new FieldInfos(filteredInfos.toArray(new FieldInfo[filteredInfos.size()]));
}
boolean hasField(String field) {
return negate ^ fields.contains(field);
}
@Override
public FieldInfos getFieldInfos() {
return fieldInfos;
}
@Override
public Fields getTermVectors(int docID) throws IOException {
Fields f = super.getTermVectors(docID);
if (f == null) {
return null;
}
f = new FieldFilterFields(f);
// we need to check for emptyness, so we can return
// null:
return f.iterator().hasNext() ? f : null;
}
@Override
public void document(final int docID, final StoredFieldVisitor visitor) throws IOException {
super.document(docID, new StoredFieldVisitor() {
@Override
public void binaryField(FieldInfo fieldInfo, byte[] value) throws IOException {
visitor.binaryField(fieldInfo, value);
}
@Override
public void stringField(FieldInfo fieldInfo, String value) throws IOException {
visitor.stringField(fieldInfo, value);
}
@Override
public void intField(FieldInfo fieldInfo, int value) throws IOException {
visitor.intField(fieldInfo, value);
}
@Override
public void longField(FieldInfo fieldInfo, long value) throws IOException {
visitor.longField(fieldInfo, value);
}
@Override
public void floatField(FieldInfo fieldInfo, float value) throws IOException {
visitor.floatField(fieldInfo, value);
}
@Override
public void doubleField(FieldInfo fieldInfo, double value) throws IOException {
visitor.doubleField(fieldInfo, value);
}
@Override
public Status needsField(FieldInfo fieldInfo) throws IOException {
return hasField(fieldInfo.name) ? visitor.needsField(fieldInfo) : Status.NO;
}
});
}
@Override
public Fields fields() throws IOException {
final Fields f = super.fields();
return (f == null) ? null : new FieldFilterFields(f);
}
@Override
public NumericDocValues getNumericDocValues(String field) throws IOException {
return hasField(field) ? super.getNumericDocValues(field) : null;
}
@Override
public BinaryDocValues getBinaryDocValues(String field) throws IOException {
return hasField(field) ? super.getBinaryDocValues(field) : null;
}
@Override
public SortedDocValues getSortedDocValues(String field) throws IOException {
return hasField(field) ? super.getSortedDocValues(field) : null;
}
@Override
public SortedNumericDocValues getSortedNumericDocValues(String field) throws IOException {
return hasField(field) ? super.getSortedNumericDocValues(field) : null;
}
@Override
public SortedSetDocValues getSortedSetDocValues(String field) throws IOException {
return hasField(field) ? super.getSortedSetDocValues(field) : null;
}
@Override
public NumericDocValues getNormValues(String field) throws IOException {
return hasField(field) ? super.getNormValues(field) : null;
}
@Override
public Bits getDocsWithField(String field) throws IOException {
return hasField(field) ? super.getDocsWithField(field) : null;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("FieldFilterAtomicReader(reader=");
sb.append(in).append(", fields=");
if (negate) sb.append('!');
return sb.append(fields).append(')').toString();
}
private class FieldFilterFields extends FilterFields {
public FieldFilterFields(Fields in) {
super(in);
}
@Override
public int size() {
// this information is not cheap, return -1 like MultiFields does:
return -1;
}
@Override
public Iterator<String> iterator() {
return new FilterIterator<String>(super.iterator()) {
@Override
protected boolean predicateFunction(String field) {
return hasField(field);
}
};
}
@Override
public Terms terms(String field) throws IOException {
return hasField(field) ? super.terms(field) : null;
}
}
}
| apache-2.0 |
Noremac201/runelite | runelite-client/src/test/java/net/runelite/client/plugins/hiscore/HiscorePanelTest.java | 1611 | /*
* Copyright (c) 2017, Adam <Adam@sigterm.info>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package net.runelite.client.plugins.hiscore;
import org.junit.Test;
public class HiscorePanelTest
{
@Test
public void testConstructor()
{
new HiscorePanel(new HiscoreConfig() {});
}
}
| bsd-2-clause |
quantumsamurai/wpilibj.project | src/edu/wpi/first/wpilibj/command/CommandGroup.java | 15217 | /*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package edu.wpi.first.wpilibj.command;
import java.util.Enumeration;
import java.util.Vector;
/**
* A {@link CommandGroup} is a list of commands which are executed in sequence.
*
* <p>Commands in a {@link CommandGroup} are added using the {@link CommandGroup#addSequential(Command) addSequential(...)} method
* and are called sequentially.
* {@link CommandGroup CommandGroups} are themselves {@link Command commands}
* and can be given to other {@link CommandGroup CommandGroups}.</p>
*
* <p>{@link CommandGroup CommandGroups} will carry all of the requirements of their {@link Command subcommands}. Additional
* requirements can be specified by calling {@link CommandGroup#requires(Subsystem) requires(...)}
* normally in the constructor.</P>
*
* <p>CommandGroups can also execute commands in parallel, simply by adding them
* using {@link CommandGroup#addParallel(Command) addParallel(...)}.</p>
*
* @author Brad Miller
* @author Joe Grinstead
* @see Command
* @see Subsystem
* @see IllegalUseOfCommandException
*/
public class CommandGroup extends Command {
/** The commands in this group (stored in entries) */
private Vector m_commands = new Vector();
/** The active children in this group (stored in entries) */
Vector m_children = new Vector();
/** The current command, -1 signifies that none have been run */
private int m_currentCommandIndex = -1;
/**
* Creates a new {@link CommandGroup CommandGroup}.
* The name of this command will be set to its class name.
*/
public CommandGroup() {
}
/**
* Creates a new {@link CommandGroup CommandGroup} with the given name.
* @param name the name for this command group
* @throws IllegalArgumentException if name is null
*/
public CommandGroup(String name) {
super(name);
}
/**
* Adds a new {@link Command Command} to the group. The {@link Command Command} will be started after
* all the previously added {@link Command Commands}.
*
* <p>Note that any requirements the given {@link Command Command} has will be added to the
* group. For this reason, a {@link Command Command's} requirements can not be changed after
* being added to a group.</p>
*
* <p>It is recommended that this method be called in the constructor.</p>
*
* @param command The {@link Command Command} to be added
* @throws IllegalUseOfCommandException if the group has been started before or been given to another group
* @throws IllegalArgumentException if command is null
*/
public synchronized final void addSequential(Command command) {
validate("Can not add new command to command group");
if (command == null) {
throw new IllegalArgumentException("Given null command");
}
command.setParent(this);
m_commands.addElement(new Entry(command, Entry.IN_SEQUENCE));
for (Enumeration e = command.getRequirements(); e.hasMoreElements();) {
requires((Subsystem) e.nextElement());
}
}
/**
* Adds a new {@link Command Command} to the group with a given timeout.
* The {@link Command Command} will be started after all the previously added commands.
*
* <p>Once the {@link Command Command} is started, it will be run until it finishes or the time
* expires, whichever is sooner. Note that the given {@link Command Command} will have no
* knowledge that it is on a timer.</p>
*
* <p>Note that any requirements the given {@link Command Command} has will be added to the
* group. For this reason, a {@link Command Command's} requirements can not be changed after
* being added to a group.</p>
*
* <p>It is recommended that this method be called in the constructor.</p>
*
* @param command The {@link Command Command} to be added
* @param timeout The timeout (in seconds)
* @throws IllegalUseOfCommandException if the group has been started before or been given to another group or
* if the {@link Command Command} has been started before or been given to another group
* @throws IllegalArgumentException if command is null or timeout is negative
*/
public synchronized final void addSequential(Command command, double timeout) {
validate("Can not add new command to command group");
if (command == null) {
throw new IllegalArgumentException("Given null command");
}
if (timeout < 0) {
throw new IllegalArgumentException("Can not be given a negative timeout");
}
command.setParent(this);
m_commands.addElement(new Entry(command, Entry.IN_SEQUENCE, timeout));
for (Enumeration e = command.getRequirements(); e.hasMoreElements();) {
requires((Subsystem) e.nextElement());
}
}
/**
* Adds a new child {@link Command} to the group. The {@link Command} will be started after
* all the previously added {@link Command Commands}.
*
* <p>Instead of waiting for the child to finish, a {@link CommandGroup} will have it
* run at the same time as the subsequent {@link Command Commands}. The child will run until either
* it finishes, a new child with conflicting requirements is started, or
* the main sequence runs a {@link Command} with conflicting requirements. In the latter
* two cases, the child will be canceled even if it says it can't be
* interrupted.</p>
*
* <p>Note that any requirements the given {@link Command Command} has will be added to the
* group. For this reason, a {@link Command Command's} requirements can not be changed after
* being added to a group.</p>
*
* <p>It is recommended that this method be called in the constructor.</p>
*
* @param command The command to be added
* @throws IllegalUseOfCommandException if the group has been started before or been given to another command group
* @throws IllegalArgumentException if command is null
*/
public synchronized final void addParallel(Command command) {
validate("Can not add new command to command group");
if (command == null) {
throw new NullPointerException("Given null command");
}
command.setParent(this);
m_commands.addElement(new Entry(command, Entry.BRANCH_CHILD));
for (Enumeration e = command.getRequirements(); e.hasMoreElements();) {
requires((Subsystem) e.nextElement());
}
}
/**
* Adds a new child {@link Command} to the group with the given timeout. The {@link Command} will be started after
* all the previously added {@link Command Commands}.
*
* <p>Once the {@link Command Command} is started, it will run until it finishes, is interrupted,
* or the time expires, whichever is sooner. Note that the given {@link Command Command} will have no
* knowledge that it is on a timer.</p>
*
* <p>Instead of waiting for the child to finish, a {@link CommandGroup} will have it
* run at the same time as the subsequent {@link Command Commands}. The child will run until either
* it finishes, the timeout expires, a new child with conflicting requirements is started, or
* the main sequence runs a {@link Command} with conflicting requirements. In the latter
* two cases, the child will be canceled even if it says it can't be
* interrupted.</p>
*
* <p>Note that any requirements the given {@link Command Command} has will be added to the
* group. For this reason, a {@link Command Command's} requirements can not be changed after
* being added to a group.</p>
*
* <p>It is recommended that this method be called in the constructor.</p>
*
* @param command The command to be added
* @param timeout The timeout (in seconds)
* @throws IllegalUseOfCommandException if the group has been started before or been given to another command group
* @throws IllegalArgumentException if command is null
*/
public synchronized final void addParallel(Command command, double timeout) {
validate("Can not add new command to command group");
if (command == null) {
throw new NullPointerException("Given null command");
}
if (timeout < 0) {
throw new IllegalArgumentException("Can not be given a negative timeout");
}
command.setParent(this);
m_commands.addElement(new Entry(command, Entry.BRANCH_CHILD, timeout));
for (Enumeration e = command.getRequirements(); e.hasMoreElements();) {
requires((Subsystem) e.nextElement());
}
}
void _initialize() {
m_currentCommandIndex = -1;
}
void _execute() {
Entry entry = null;
Command cmd = null;
boolean firstRun = false;
if (m_currentCommandIndex == -1) {
firstRun = true;
m_currentCommandIndex = 0;
}
while (m_currentCommandIndex < m_commands.size()) {
if (cmd != null) {
if (entry.isTimedOut()) {
cmd._cancel();
}
if (cmd.run()) {
break;
} else {
cmd.removed();
m_currentCommandIndex++;
firstRun = true;
cmd = null;
continue;
}
}
entry = (Entry) m_commands.elementAt(m_currentCommandIndex);
cmd = null;
switch (entry.state) {
case Entry.IN_SEQUENCE:
cmd = entry.command;
if (firstRun) {
cmd.startRunning();
cancelConflicts(cmd);
}
firstRun = false;
break;
case Entry.BRANCH_PEER:
m_currentCommandIndex++;
entry.command.start();
break;
case Entry.BRANCH_CHILD:
m_currentCommandIndex++;
cancelConflicts(entry.command);
entry.command.startRunning();
m_children.addElement(entry);
break;
}
}
// Run Children
for (int i = 0; i < m_children.size(); i++) {
entry = (Entry) m_children.elementAt(i);
Command child = entry.command;
if (entry.isTimedOut()) {
child._cancel();
}
if (!child.run()) {
child.removed();
m_children.removeElementAt(i--);
}
}
}
void _end() {
// Theoretically, we don't have to check this, but we do if teams override the isFinished method
if (m_currentCommandIndex != -1 && m_currentCommandIndex < m_commands.size()) {
Command cmd = ((Entry) m_commands.elementAt(m_currentCommandIndex)).command;
cmd._cancel();
cmd.removed();
}
Enumeration children = m_children.elements();
while (children.hasMoreElements()) {
Command cmd = ((Entry) children.nextElement()).command;
cmd._cancel();
cmd.removed();
}
m_children.removeAllElements();
}
void _interrupted() {
_end();
}
/**
* Returns true if all the {@link Command Commands} in this group
* have been started and have finished.
*
* <p>Teams may override this method, although they should probably
* reference super.isFinished() if they do.</p>
*
* @return whether this {@link CommandGroup} is finished
*/
protected boolean isFinished() {
return m_currentCommandIndex >= m_commands.size() && m_children.isEmpty();
}
// Can be overwritten by teams
protected void initialize() {
}
// Can be overwritten by teams
protected void execute() {
}
// Can be overwritten by teams
protected void end() {
}
// Can be overwritten by teams
protected void interrupted() {
}
/**
* Returns whether or not this group is interruptible.
* A command group will be uninterruptible if {@link CommandGroup#setInterruptible(boolean) setInterruptable(false)}
* was called or if it is currently running an uninterruptible command
* or child.
*
* @return whether or not this {@link CommandGroup} is interruptible.
*/
public synchronized boolean isInterruptible() {
if (!super.isInterruptible()) {
return false;
}
if (m_currentCommandIndex != -1 && m_currentCommandIndex < m_commands.size()) {
Command cmd = ((Entry) m_commands.elementAt(m_currentCommandIndex)).command;
if (!cmd.isInterruptible()) {
return false;
}
}
for (int i = 0; i < m_children.size(); i++) {
if (!((Entry) m_children.elementAt(i)).command.isInterruptible()) {
return false;
}
}
return true;
}
private void cancelConflicts(Command command) {
for (int i = 0; i < m_children.size(); i++) {
Command child = ((Entry) m_children.elementAt(i)).command;
Enumeration requirements = command.getRequirements();
while (requirements.hasMoreElements()) {
Object requirement = requirements.nextElement();
if (child.doesRequire((Subsystem) requirement)) {
child._cancel();
child.removed();
m_children.removeElementAt(i--);
break;
}
}
}
}
private static class Entry {
private static final int IN_SEQUENCE = 0;
private static final int BRANCH_PEER = 1;
private static final int BRANCH_CHILD = 2;
Command command;
int state;
double timeout;
Entry(Command command, int state) {
this.command = command;
this.state = state;
this.timeout = -1;
}
Entry(Command command, int state, double timeout) {
this.command = command;
this.state = state;
this.timeout = timeout;
}
boolean isTimedOut() {
if (timeout == -1) {
return false;
} else {
double time = command.timeSinceInitialized();
return time == 0 ? false : time >= timeout;
}
}
}
}
| bsd-3-clause |
kaulkie/jline2 | src/main/java/jline/console/internal/ConsoleRunner.java | 3357 | /*
* Copyright (c) 2002-2015, the original author or authors.
*
* This software is distributable under the BSD license. See the terms of the
* BSD license in the documentation provided with this software.
*
* http://www.opensource.org/licenses/bsd-license.php
*/
package jline.console.internal;
import jline.console.ConsoleReader;
import jline.console.completer.ArgumentCompleter;
import jline.console.completer.Completer;
import jline.console.history.FileHistory;
import jline.internal.Configuration;
import java.io.File;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.StringTokenizer;
// FIXME: Clean up API and move to jline.console.runner package
/**
* A pass-through application that sets the system input stream to a
* {@link ConsoleReader} and invokes the specified main method.
*
* @author <a href="mailto:mwp1@cornell.edu">Marc Prud'hommeaux</a>
* @since 2.7
*/
public class ConsoleRunner
{
public static final String property = "jline.history";
// FIXME: This is really ugly... re-write this
public static void main(final String[] args) throws Exception {
List<String> argList = new ArrayList<String>(Arrays.asList(args));
if (argList.size() == 0) {
usage();
return;
}
String historyFileName = System.getProperty(ConsoleRunner.property, null);
String mainClass = argList.remove(0);
ConsoleReader reader = new ConsoleReader();
if (historyFileName != null) {
reader.setHistory(new FileHistory(new File(Configuration.getUserHome(),
String.format(".jline-%s.%s.history", mainClass, historyFileName))));
}
else {
reader.setHistory(new FileHistory(new File(Configuration.getUserHome(),
String.format(".jline-%s.history", mainClass))));
}
String completors = System.getProperty(ConsoleRunner.class.getName() + ".completers", "");
List<Completer> completorList = new ArrayList<Completer>();
for (StringTokenizer tok = new StringTokenizer(completors, ","); tok.hasMoreTokens();) {
Object obj = Class.forName(tok.nextToken()).newInstance();
completorList.add((Completer) obj);
}
if (completorList.size() > 0) {
reader.addCompleter(new ArgumentCompleter(completorList));
}
ConsoleReaderInputStream.setIn(reader);
try {
Class<?> type = Class.forName(mainClass);
Method method = type.getMethod("main", String[].class);
String[] mainArgs = argList.toArray(new String[argList.size()]);
method.invoke(null, (Object) mainArgs);
}
finally {
// just in case this main method is called from another program
ConsoleReaderInputStream.restoreIn();
}
}
private static void usage() {
System.out.println("Usage: \n java " + "[-Djline.history='name'] "
+ ConsoleRunner.class.getName()
+ " <target class name> [args]"
+ "\n\nThe -Djline.history option will avoid history"
+ "\nmangling when running ConsoleRunner on the same application."
+ "\n\nargs will be passed directly to the target class name.");
}
}
| bsd-3-clause |
minagri-rwanda/DHIS2-Agriculture | dhis-web/dhis-web-ohie/src/main/java/org/hisp/dhis/web/ohie/csd/domain/ProviderDirectory.java | 1952 | package org.hisp.dhis.web.ohie.csd.domain;
/*
* Copyright (c) 2004-2016, University of Oslo
* 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 the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
/**
* @author Morten Olav Hansen <mortenoh@gmail.com>
*/
@XmlAccessorType( XmlAccessType.FIELD )
@XmlType( name = "providerDirectory", namespace = "urn:ihe:iti:csd:2013" )
public class ProviderDirectory
{
}
| bsd-3-clause |
troyel/dhis2-core | dhis-2/dhis-api/src/main/java/org/hisp/dhis/user/UserAccess.java | 3874 | package org.hisp.dhis.user;
/*
* Copyright (c) 2004-2017, University of Oslo
* 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 the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
import com.google.common.base.MoreObjects;
import org.hisp.dhis.common.DxfNamespaces;
import org.hisp.dhis.common.EmbeddedObject;
import java.io.Serializable;
/**
* @author Morten Olav Hansen <mortenoh@gmail.com>
*/
@JacksonXmlRootElement( localName = "userAccess", namespace = DxfNamespaces.DXF_2_0 )
public class UserAccess
implements Serializable, EmbeddedObject
{
private int id;
private User user;
private transient String uid;
private transient String access;
public UserAccess()
{
}
public int getId()
{
return id;
}
@JsonIgnore
public void setId( int id )
{
this.id = id;
}
@JsonProperty
@JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
public String getAccess()
{
return access;
}
public void setAccess( String access )
{
this.access = access;
}
@JsonProperty
@JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
public String getUserUid()
{
return user != null ? user.getUid() : null;
}
@JsonProperty( "id" )
@JacksonXmlProperty( localName = "id", namespace = DxfNamespaces.DXF_2_0 )
public String getUid()
{
return uid != null ? uid : (user != null ? user.getUid() : null);
}
public void setUid( String uid )
{
this.uid = uid;
}
@JsonProperty
@JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
public String displayName()
{
return user != null ? user.getDisplayName() : null;
}
public User getUser()
{
if ( user == null )
{
User user = new User();
user.setUid( uid );
return user;
}
return user;
}
public void setUser( User user )
{
this.user = user;
}
@Override
public String toString()
{
return MoreObjects.toStringHelper( this )
.add( "id", id )
.add( "access", access )
.toString();
}
}
| bsd-3-clause |
amkimian/Rapture | Libs/RaptureAddins/MongoDb/src/main/java/rapture/idgen/mongodb/IdGenMongoStore.java | 5242 | /**
* The MIT License (MIT)
*
* Copyright (c) 2011-2016 Incapture Technologies LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package rapture.idgen.mongodb;
import java.net.HttpURLConnection;
import java.util.Map;
import org.apache.log4j.Logger;
import org.bson.Document;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.model.FindOneAndUpdateOptions;
import com.mongodb.client.model.ReturnDocument;
import rapture.common.Messages;
import rapture.common.exception.RaptureExceptionFactory;
import rapture.dsl.idgen.IdGenStore;
import rapture.mongodb.MongoDBFactory;
/**
* A idgen implemented on MongoDb
*/
public class IdGenMongoStore implements IdGenStore {
private static Logger log = Logger.getLogger(IdGenMongoStore.class);
private static final String DOLLARINC = "$inc";
private static final String SEQ = "seq";
private static final String IDGEN = "idgen";
private static final String IDGEN_NAME = "idgenName";
private static final String TABLE_NAME = "prefix";
private static final String VALID = "valid";
private String tableName;
private String idGenName = "idgen";
private String instanceName = "default";
private Messages mongoMsgCatalog = new Messages("Mongo");
public IdGenMongoStore() {
}
@Override
public void setInstanceName(String instanceName) {
this.instanceName = instanceName;
}
private MongoCollection<Document> getIdGenCollection() {
return MongoDBFactory.getCollection(instanceName, tableName);
}
private Document getIncUpdateObject(Document update) {
Document realUpdate = new Document();
realUpdate.put(DOLLARINC, update);
return realUpdate;
}
@Override
public Long getNextIdGen(Long interval) {
Document realUpdate = getIncUpdateObject(getUpdateObject(interval));
FindOneAndUpdateOptions options = new FindOneAndUpdateOptions()
.upsert(true)
.returnDocument(ReturnDocument.AFTER);
Document ret = getIdGenCollection().findOneAndUpdate(getQueryObject(), realUpdate, options);
if (ret == null) return null;
Boolean valid = (Boolean) ret.get(VALID);
if (valid != null && !valid) {
throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST,
mongoMsgCatalog.getMessage("IdGenerator"));
}
return (Long) ret.get(SEQ);
}
private Document getQueryObject() {
Document query = new Document();
query.put(IDGEN, idGenName);
return query;
}
private Document getUpdateObject(Long interval) {
Document update = new Document();
update.put(SEQ, interval);
return update;
}
private Document getInvalidator() {
Document invalidator = new Document();
invalidator.append("$set", new Document().append(VALID, false));
return invalidator;
}
private Document getRevalidator() {
Document invalidator = new Document();
invalidator.append("$set", new Document().append(VALID, true));
return invalidator;
}
@Override
public void resetIdGen(Long number) {
// RAP-2109 Just use maths to change the value. Trying to replace the
// object does not work.
Long currentValue = getNextIdGen(0L);
Long decrement = number - currentValue;
getNextIdGen(decrement);
}
@Override
public void setConfig(Map<String, String> config) {
log.info("Set config is " + config);
tableName = config.get(TABLE_NAME);
if (config.containsKey(IDGEN_NAME)) {
idGenName = config.get(IDGEN_NAME);
}
}
@Override
public void invalidate() {
Document invalidator = getInvalidator();
getIdGenCollection().findOneAndUpdate(getQueryObject(), invalidator, new FindOneAndUpdateOptions().upsert(true));
}
public void makeValid() {
Document invalidator = getRevalidator();
getIdGenCollection().findOneAndUpdate(getQueryObject(), invalidator, new FindOneAndUpdateOptions().upsert(true));
}
@Override
public void init() {
}
}
| mit |
brunyuriy/quick-fix-scout | org.eclipse.jdt.ui_3.7.1.r371_v20110824-0800/src/org/eclipse/jdt/internal/ui/text/java/AnonymousTypeProposalInfo.java | 1856 | /*******************************************************************************
* Copyright (c) 2005, 2011 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.text.java;
import org.eclipse.jdt.core.CompletionProposal;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.internal.corext.template.java.SignatureUtil;
/**
* Proposal info that computes the javadoc lazily when it is queried.
*
* @since 3.1
*/
public final class AnonymousTypeProposalInfo extends MemberProposalInfo {
/**
* Creates a new proposal info.
*
* @param project the java project to reference when resolving types
* @param proposal the proposal to generate information for
*/
public AnonymousTypeProposalInfo(IJavaProject project, CompletionProposal proposal) {
super(project, proposal);
}
/**
* Resolves the member described by the receiver and returns it if found.
* Returns <code>null</code> if no corresponding member can be found.
*
* @return the resolved member or <code>null</code> if none is found
* @throws JavaModelException if accessing the java model fails
*/
@Override
protected IMember resolveMember() throws JavaModelException {
char[] signature= fProposal.getDeclarationSignature();
String typeName= SignatureUtil.stripSignatureToFQN(String.valueOf(signature));
return fJavaProject.findType(typeName);
}
}
| mit |
godotgildor/igv | src/org/broad/igv/ui/FilterComponent.java | 11946 | /*
* The MIT License (MIT)
*
* Copyright (c) 2007-2015 Broad Institute
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.broad.igv.ui;
import com.jidesoft.swing.JideButton;
import org.broad.igv.ui.TrackFilterPane;
import org.broad.igv.util.Filter;
import org.broad.igv.util.FilterElement;
import org.broad.igv.util.FilterElement.BooleanOperator;
import org.broad.igv.util.FilterElement.Operator;
import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
abstract public class FilterComponent extends javax.swing.JPanel {
private FilterElement filterElement;
private TrackFilterPane filterPane;
public FilterComponent(TrackFilterPane filterPane, String text, List<String> items,
FilterElement element) {
initComponents();
// Load the Item ComboBox
this.filterPane = filterPane;
itemComboBox.setModel(new DefaultComboBoxModel(items.toArray()));
// Load available operators into combobox
List<String> textForOperators = new ArrayList<String>();
Operator[] operators = FilterElement.Operator.values();
for (int i = 0; i < operators.length; i++) {
// List the operators to skip
if (operators[i].equals(Operator.GREATER_THAN_OR_EQUAL) ||
operators[i].equals(Operator.LESS_THAN_OR_EQUAL)) {
continue;
}
textForOperators.add(operators[i].getValue());
}
Collections.sort(textForOperators);
comparisonOperatorComboBox.setModel(
new javax.swing.DefaultComboBoxModel(textForOperators.toArray()));
// If a FilterElement was passed use it otherwise create a default one
if (element != null) {
filterElement = element;
itemComboBox.setSelectedItem(filterElement.getSelectedItem());
valueTextField.setText(filterElement.getValue());
} else {
String selectedItem = (String) itemComboBox.getSelectedItem();
FilterElement.Operator selectedOperator =
getOperatorForText((String) comparisonOperatorComboBox.getSelectedItem());
filterElement =
createFilterElement(filterPane.getFilter(),
selectedItem,
selectedOperator,
null,
null);
}
filterPane.getFilter().add(filterElement);
}
abstract public FilterElement createFilterElement(Filter filter, String item,
Operator comparisonOperator, String value, BooleanOperator booleanOperator);
/**
* Helper method to convert the string representation of an operator
* to the appropriate object representation.
*/
private FilterElement.Operator getOperatorForText(String operatorText) {
FilterElement.Operator selected = null;
FilterElement.Operator[] operators = FilterElement.Operator.values();
for (FilterElement.Operator operator : operators) {
if (operatorText.equals(operator.getValue())) {
selected = operator;
break;
}
}
return selected;
}
public FilterElement getFilterElement() {
return filterElement;
}
public String getItem() {
return (String) itemComboBox.getSelectedItem();
}
public String getComparisonOperator() {
return (String) comparisonOperatorComboBox.getSelectedItem();
}
public String getExpectedValue() {
return valueTextField.getText();
}
/**
* Save the UI content into a non-UI version of the FilterElement
*/
public void save() {
// Item
filterElement.setSelectedItem(getItem());
// Comparison operator
Operator operator = getOperatorForText(getComparisonOperator());
filterElement.setComparisonOperator(operator);
// Value
filterElement.setExpectedValue(getExpectedValue());
}
public void displayMoreButton(boolean value) {
moreButton.setVisible(value);
}
protected void remove() {
if (filterPane != null) {
// Can not leave less than one filter element on the screen
Component[] components = filterPane.getComponents();
if (components.length < 2) {
return;
}
// Remove the visible filter element
filterPane.remove(this);
// Remove the non-visual element
filterPane.getFilter().remove(getFilterElement());
filterPane.adjustMoreAndBooleanButtonVisibility();
filterPane.repaint();
// Resize window to fit the components left
SwingUtilities.getWindowAncestor(filterPane).pack();
}
}
/**
* This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
booleanButtonGroup = new javax.swing.ButtonGroup();
jPanel1 = new javax.swing.JPanel();
itemComboBox = new javax.swing.JComboBox();
comparisonOperatorComboBox = new javax.swing.JComboBox();
valueTextField = new javax.swing.JTextField();
moreButton = new JideButton();
removeButton = new JideButton();
setBackground(new java.awt.Color(255, 255, 255));
setMinimumSize(new java.awt.Dimension(530, 40));
setPreferredSize(new java.awt.Dimension(700, 40));
setRequestFocusEnabled(false);
setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 2, 5));
jPanel1.setBackground(new java.awt.Color(255, 255, 255));
jPanel1.setMinimumSize(new java.awt.Dimension(470, 31));
jPanel1.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT));
itemComboBox.setMinimumSize(new java.awt.Dimension(50, 27));
itemComboBox.setPreferredSize(new java.awt.Dimension(150, 27));
itemComboBox.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
itemComboBoxActionPerformed(evt);
}
});
itemComboBox.addHierarchyBoundsListener(new java.awt.event.HierarchyBoundsListener() {
public void ancestorMoved(java.awt.event.HierarchyEvent evt) {
itemComboBoxAncestorMoved(evt);
}
public void ancestorResized(java.awt.event.HierarchyEvent evt) {
}
});
jPanel1.add(itemComboBox);
comparisonOperatorComboBox.setActionCommand("comparisonOperatorComboBoxChanged");
comparisonOperatorComboBox.setMinimumSize(new java.awt.Dimension(50, 27));
comparisonOperatorComboBox.setPreferredSize(new java.awt.Dimension(150, 27));
comparisonOperatorComboBox.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
comparisonOperatorComboBoxActionPerformed(evt);
}
});
jPanel1.add(comparisonOperatorComboBox);
valueTextField.setMaximumSize(new java.awt.Dimension(32767, 20));
valueTextField.setMinimumSize(new java.awt.Dimension(50, 27));
valueTextField.setPreferredSize(new java.awt.Dimension(150, 27));
valueTextField.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
valueTextFieldActionPerformed(evt);
}
});
jPanel1.add(valueTextField);
add(jPanel1);
moreButton.setFont(new java.awt.Font("Arial", 0, 14));
moreButton.setText("+");
moreButton.setContentAreaFilled(false);
moreButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
moreButton.setPreferredSize(new java.awt.Dimension(45, 27));
moreButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
moreButtonActionPerformed(evt);
}
});
add(moreButton);
removeButton.setFont(new java.awt.Font("Arial", 0, 14));
removeButton.setText("-");
removeButton.setContentAreaFilled(false);
removeButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
removeButton.setPreferredSize(new java.awt.Dimension(45, 27));
removeButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
removeButtonActionPerformed(evt);
}
});
add(removeButton);
}// </editor-fold>//GEN-END:initComponents
private void valueTextFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_valueTextFieldActionPerformed
}//GEN-LAST:event_valueTextFieldActionPerformed
private void comparisonOperatorComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_comparisonOperatorComboBoxActionPerformed
}//GEN-LAST:event_comparisonOperatorComboBoxActionPerformed
private void itemComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_itemComboBoxActionPerformed
}//GEN-LAST:event_itemComboBoxActionPerformed
private void itemComboBoxAncestorMoved(java.awt.event.HierarchyEvent evt) {//GEN-FIRST:event_itemComboBoxAncestorMoved
// TODO add your handling code here:
}//GEN-LAST:event_itemComboBoxAncestorMoved
private void moreButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_moreButtonActionPerformed
if (filterPane.more()) {
displayMoreButton(false);
invalidate();
}
}//GEN-LAST:event_moreButtonActionPerformed
private void removeButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removeButtonActionPerformed
// TODO add your handling code here:
remove();
}//GEN-LAST:event_removeButtonActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.ButtonGroup booleanButtonGroup;
private javax.swing.JComboBox comparisonOperatorComboBox;
private javax.swing.JComboBox itemComboBox;
private javax.swing.JPanel jPanel1;
private javax.swing.JButton moreButton;
private javax.swing.JButton removeButton;
private javax.swing.JTextField valueTextField;
// End of variables declaration//GEN-END:variables
}
| mit |
godotgildor/igv | src/org/broad/igv/session/RendererFactory.java | 4428 | /*
* The MIT License (MIT)
*
* Copyright (c) 2007-2015 Broad Institute
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.broad.igv.session;
import org.broad.igv.renderer.*;
/**
* Maps between renderer type name and renderer class. Used for saving and restoring sessions.
*
* @author eflakes
*/
public class RendererFactory {
static public enum RendererType {
BAR_CHART,
BASIC_FEATURE,
FEATURE_DENSITY,
GENE_TRACK,
GISTIC_TRACK,
HEATMAP,
MUTATION,
SCATTER_PLOT,
LINE_PLOT
}
static Class defaultRendererClass = BarChartRenderer.class;
static public Class getRendererClass(String rendererTypeName) {
String typeName = rendererTypeName.toUpperCase();
// Try know type names
if (typeName.equals(RendererType.BAR_CHART.name()) || typeName.equals("BAR")) {
return BarChartRenderer.class;
} else if (typeName.equals(RendererType.BASIC_FEATURE.name())) {
return IGVFeatureRenderer.class;
} else if (typeName.equals(RendererType.FEATURE_DENSITY.name())) {
return FeatureDensityRenderer.class;
} else if (typeName.equals(RendererType.GENE_TRACK.name())) {
return GeneTrackRenderer.class;
} else if (typeName.equals(RendererType.GISTIC_TRACK.name())) {
return GisticTrackRenderer.class;
} else if (typeName.equals(RendererType.HEATMAP.name())) {
return HeatmapRenderer.class;
} else if (typeName.equals(RendererType.MUTATION.name())) {
return MutationRenderer.class;
} else if (typeName.equals(RendererType.SCATTER_PLOT.name()) ||
typeName.toUpperCase().equals("POINTS")) {
return PointsRenderer.class;
} else if (typeName.equals(RendererType.LINE_PLOT.name()) ||
typeName.toUpperCase().equals("LINE")) {
return LineplotRenderer.class;
}
return null;
}
static public RendererType getRenderType(Renderer renderer) {
Class rendererClass = renderer.getClass();
RendererType rendererType = null;
if (rendererClass.equals(BarChartRenderer.class)) {
rendererType = RendererType.BAR_CHART;
} else if (rendererClass.equals(IGVFeatureRenderer.class)) {
rendererType = RendererType.BASIC_FEATURE;
} else if (rendererClass.equals(FeatureDensityRenderer.class)) {
rendererType = RendererType.FEATURE_DENSITY;
} else if (rendererClass.equals(GeneTrackRenderer.class)) {
rendererType = RendererType.GENE_TRACK;
} else if (rendererClass.equals(GisticTrackRenderer.class)) {
rendererType = RendererType.GISTIC_TRACK;
} else if (rendererClass.equals(HeatmapRenderer.class)) {
rendererType = RendererType.HEATMAP;
} else if (rendererClass.equals(MutationRenderer.class)) {
rendererType = RendererType.MUTATION;
} else if (rendererClass.equals(PointsRenderer.class)) {
rendererType = RendererType.SCATTER_PLOT;
} else if (rendererClass.equals(LineplotRenderer.class)) {
rendererType = RendererType.LINE_PLOT;
}
return rendererType;
}
}
| mit |
RallySoftware/eclipselink.runtime | foundation/eclipselink.core.test/src/org/eclipse/persistence/testing/models/mapping/Crib.java | 1743 | /*******************************************************************************
* Copyright (c) 1998, 2015 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Oracle - initial API and implementation from Oracle TopLink
******************************************************************************/
package org.eclipse.persistence.testing.models.mapping;
import java.io.*;
import java.math.*;
public class Crib implements Serializable {
private Baby baby;
private String color;
private BigDecimal id;
private BabyMonitor babyMonitor;
public Crib() {
}
public static void addToDescriptor(org.eclipse.persistence.descriptors.ClassDescriptor desc) {
desc.addConstraintDependencies(BabyMonitor.class);
}
public Baby getBaby() {
return baby;
}
public BabyMonitor getBabyMonitor() {
return babyMonitor;
}
public String getColor() {
return color;
}
public BigDecimal getId() {
return id;
}
public void setBaby(Baby baby) {
this.baby = baby;
}
public void setBabyMonitor(BabyMonitor babyMonitor) {
this.babyMonitor = babyMonitor;
}
public void setColor(String color) {
this.color = color;
}
public void setId(BigDecimal id) {
this.id = id;
}
}
| epl-1.0 |
RallySoftware/eclipselink.runtime | foundation/eclipselink.core.test/src/org/eclipse/persistence/testing/models/generic/Class10.java | 918 | /*******************************************************************************
* Copyright (c) 1998, 2015 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Oracle - initial API and implementation from Oracle TopLink
******************************************************************************/
package org.eclipse.persistence.testing.models.generic;
import org.eclipse.persistence.testing.models.generic.ClassI10;
public class Class10 implements ClassI10 {
int id;
int value;
}
| epl-1.0 |
RallySoftware/eclipselink.runtime | foundation/eclipselink.core.test/src/org/eclipse/persistence/testing/models/mapping/Address.java | 4007 | /*******************************************************************************
* Copyright (c) 1998, 2015 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Oracle - initial API and implementation from Oracle TopLink
******************************************************************************/
package org.eclipse.persistence.testing.models.mapping;
import java.io.*;
import java.util.*;
import org.eclipse.persistence.sessions.*;
import org.eclipse.persistence.queries.*;
import org.eclipse.persistence.tools.schemaframework.TableDefinition;
public class Address implements Serializable {
public Number id;
public String location;
public Employee employee;
public Vector employeeRows;
public String province;
public Address() {
}
public Object copy() {
return new Address();
}
public static Address example1() {
Address example = new Address();
//please keep the province in capitals
example.setLocation("OTTAWA");
example.setProvince("ONTARIO");
return example;
}
public static Address example2() {
Address example = new Address();
//Please keep the province in capitals
example.setLocation("Montreal");
example.setProvince("QUEBEC");
return example;
}
public Employee getEmployee() {
return employee;
}
public String getProvince() {
return province;
}
public String getProvinceFromObject() {
String province = "";
if (getProvince() == null) {
return null;
}
if (getProvince().equals("ONTARIO")) {
province = "ON";
}
if (getProvince().equals("QUEBEC")) {
province = "QUE";
}
return province;
}
public String getProvinceFromRow(Record row, Session session) {
String code = (String)row.get("PROVINCE");
String provinceString = null;
// This method was causing this model to fail randomly because
// the read for employee cause the newly commited objects to be read
// into the cache before the merge, so the merge did not merge into the
// originals used for testing compares.
//this.employee = ((Employee) session.readObject(Employee.class)));
// The test is basically verifying that the session can be used in transforms
// so just do an SQL read.
this.employeeRows = session.executeSelectingCall(new SQLCall("Select * from MAP_EMP"));
if (code == "ON") {
provinceString = new String("ONTARIO");
}
if (code == "QUE") {
provinceString = new String("QUEBEC");
}
return provinceString;
}
public void setEmployee(Employee anEmployee) {
this.employee = anEmployee;
}
public void setLocation(String location) {
this.location = location;
}
public void setProvince(String province) {
this.province = province;
}
/**
* Return a platform independant definition of the database table.
*/
public static TableDefinition tableDefinition() {
TableDefinition definition = new TableDefinition();
definition.setName("MAP_ADD");
definition.addIdentityField("A_ID", java.math.BigDecimal.class, 15);
definition.addField("LOCATION", String.class, 15);
definition.addField("PROVINCE", String.class, 3);
return definition;
}
public String toString() {
return "Address(" + location + "--" + province + ")";
}
}
| epl-1.0 |
RallySoftware/eclipselink.runtime | foundation/eclipselink.core.test/src/org/eclipse/persistence/testing/tests/workbenchintegration/CMWorkbenchIntegrationSubSystem.java | 1128 | /*******************************************************************************
* Copyright (c) 1998, 2015 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Oracle - initial API and implementation from Oracle TopLink
******************************************************************************/
package org.eclipse.persistence.testing.tests.workbenchintegration;
// Test some special types in expression comparison by writing to project class
// generator and reading it back
public class CMWorkbenchIntegrationSubSystem extends CMWorkbenchIntegrationSystem {
protected void buildProject() {
project = WorkbenchIntegrationSystemHelper.buildProjectClass(project, PROJECT_FILE);
}
}
| epl-1.0 |
RallySoftware/eclipselink.runtime | foundation/eclipselink.core.test/src/org/eclipse/persistence/testing/tests/mapping/BidirectionalUOWInsertAndDeleteTest.java | 2159 | /*******************************************************************************
* Copyright (c) 1998, 2015 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Oracle - initial API and implementation from Oracle TopLink
******************************************************************************/
package org.eclipse.persistence.testing.tests.mapping;
import org.eclipse.persistence.testing.framework.*;
import org.eclipse.persistence.sessions.*;
import org.eclipse.persistence.expressions.*;
import org.eclipse.persistence.testing.models.mapping.Computer;
import org.eclipse.persistence.testing.models.mapping.Monitor;
public class BidirectionalUOWInsertAndDeleteTest extends AutoVerifyTestCase {
public BidirectionalUOWInsertAndDeleteTest() {
setDescription("Test bidirectional insert, then delete, in a unit of work.");
}
public void reset() {
rollbackTransaction();
getSession().getIdentityMapAccessor().initializeAllIdentityMaps();
}
protected void setup() {
beginTransaction();
UnitOfWork uow = getSession().acquireUnitOfWork();
Computer computer = new Computer();
Monitor monitor = Monitor.example1();
computer.setDescription("IBM PS2");
computer.notMacintosh();
computer.setMonitor(monitor);
computer.getMonitor().setComputer(computer);
computer.setSerialNumber("1124345-1876212-2");
uow.registerObject(computer);
uow.commit();
}
protected void test() {
UnitOfWork uow = getSession().acquireUnitOfWork();
uow.deleteObject(uow.readObject(Computer.class, new ExpressionBuilder().get("serialNumber").equal("1124345-1876212-2")));
uow.commit();
}
}
| epl-1.0 |
RallySoftware/eclipselink.runtime | jpa/org.eclipse.persistence.jpa/src/org/eclipse/persistence/internal/jpa/metadata/accessors/classes/InterfaceAccessor.java | 4431 | /*******************************************************************************
* Copyright (c) 1998, 2015 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* 03/26/2008-1.0M6 Guy Pelletier
* - 211302: Add variable 1-1 mapping support to the EclipseLink-ORM.XML Schema
* 05/16/2008-1.0M8 Guy Pelletier
* - 218084: Implement metadata merging functionality between mapping files
* 03/27/2009-2.0 Guy Pelletier
* - 241413: JPA 2.0 Add EclipseLink support for Map type attributes
* 05/04/2010-2.1 Guy Pelletier
* - 309373: Add parent class attribute to EclipseLink-ORM
* 03/24/2011-2.3 Guy Pelletier
* - 337323: Multi-tenant with shared schema support (part 1)
******************************************************************************/
package org.eclipse.persistence.internal.jpa.metadata.accessors.classes;
import java.util.HashSet;
import org.eclipse.persistence.internal.jpa.metadata.MetadataProject;
import org.eclipse.persistence.internal.jpa.metadata.accessors.mappings.VariableOneToOneAccessor;
import org.eclipse.persistence.internal.jpa.metadata.accessors.objects.MetadataAnnotation;
import org.eclipse.persistence.internal.jpa.metadata.accessors.objects.MetadataClass;
/**
* An interface accessor. This is kinda forward thinking. I assume once we
* get into full interface support etc. this class will handle much more and
* will map directly to an interface schema element from the eclipselink orm
* schema.
*
* Things that should or could be mapped on this interface are:
* - alias
* - query keys
*
* Key notes:
* - any metadata mapped from XML to this class must be compared in the
* equals method.
* - any metadata mapped from XML to this class must be handled in the merge
* method. (merging is done at the accessor/mapping level)
* - any metadata mapped from XML to this class must be initialized in the
* initXMLObject method.
* - methods should be preserved in alphabetical order.
*
* @author Guy Pelletier
* @since EclipseLink 1.0
*/
public class InterfaceAccessor extends ClassAccessor {
private HashSet<VariableOneToOneAccessor> m_variableOneToOneAccessors;
/**
* INTERNAL:
*/
public InterfaceAccessor(MetadataAnnotation annotation, MetadataClass cls, MetadataProject project) {
super(annotation, cls, project);
m_variableOneToOneAccessors = new HashSet<VariableOneToOneAccessor>();
}
/**
* INTERNAL:
* Add the given entity accessor to this interface's list of variable one
* to one accessors.
*/
public void addEntityAccessor(EntityAccessor accessor) {
for (VariableOneToOneAccessor variableOneToOne : m_variableOneToOneAccessors) {
variableOneToOne.addDiscriminatorClassFor(accessor);
}
}
/**
* INTERNAL:
* Query keys are stored internally in a map (keyed on the query key name).
* Therefore, adding the same query key name multiple times (for each
* variable one to one accessor to this interface) will not cause a problem.
*/
public void addQueryKey(String queryKeyName) {
getDescriptor().getClassDescriptor().addAbstractQueryKey(queryKeyName);
}
/**
* INTERNAL:
* Add a variable one to one accessor for this interface. Those entities
* that implement the interface on the accessor will need to make sure they
* add themselves to the class indicator list. See the process method below
* which is called from MetadataProject processing.
*/
public void addVariableOneToOneAccessor(VariableOneToOneAccessor accessor) {
m_variableOneToOneAccessors.add(accessor);
}
/**
* INTERNAL:
*/
@Override
public void process() {
// Does nothing at this point ... perhaps it will in the future ...
}
/**
* INTERNAL:
*/
@Override
public void processAccessType() {
// Does nothing at this point ... perhaps it will in the future ...
}
}
| epl-1.0 |
RallySoftware/eclipselink.runtime | jpa/eclipselink.jpa.test/src/org/eclipse/persistence/testing/models/jpa/inherited/Beverage.java | 2250 | /*******************************************************************************
* Copyright (c) 1998, 2015 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Oracle - initial API and implementation from Oracle TopLink
* 06/20/2008-1.0 Guy Pelletier
* - 232975: Failure when attribute type is generic
* 07/15/2010-2.2 Guy Pelletier
* -311395 : Multiple lifecycle callback methods for the same lifecycle event
* 10/05/2012-2.4.1 Guy Pelletier
* - 373092: Exceptions using generics, embedded key and entity inheritance
******************************************************************************/
package org.eclipse.persistence.testing.models.jpa.inherited;
import javax.persistence.Id;
import javax.persistence.GeneratedValue;
import javax.persistence.PostPersist;
import javax.persistence.TableGenerator;
import javax.persistence.MappedSuperclass;
import org.eclipse.persistence.testing.models.jpa.inheritance.GenericTestInterface2;
import static javax.persistence.GenerationType.*;
@MappedSuperclass
// The reference to GenericTestInterface2 is added as a test for the fix for bug 411560
public class Beverage<U, PK> extends Consumable<PK> implements GenericTestInterface2<U, PK> {
public static int BEVERAGE_POST_PERSIST_COUNT = 0;
private PK id;
public Beverage() {}
@Id
@GeneratedValue(strategy=TABLE, generator="BEVERAGE_TABLE_GENERATOR")
@TableGenerator(
name="BEVERAGE_TABLE_GENERATOR",
table="CMP3_BEVERAGE_SEQ",
pkColumnName="SEQ_NAME",
valueColumnName="SEQ_COUNT",
pkColumnValue="BEVERAGE_SEQ")
public PK getId() {
return id;
}
public void setId(PK id) {
this.id = id;
}
@PostPersist
public void celebrateAgain() {
BEVERAGE_POST_PERSIST_COUNT++;
}
}
| epl-1.0 |
md-5/jdk10 | test/hotspot/jtreg/serviceability/tmtools/jstat/GcCauseTest03.java | 2372 | /*
* Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @summary Test checks output displayed with jstat -gccause.
* Test scenario:
* test forces debuggee application call System.gc(), runs jstat and checks that
* cause of last garbage collection displayed by jstat (LGCC) is 'System.gc()'.
* @requires vm.gc != "Z" & vm.gc != "Shenandoah"
* @modules java.base/jdk.internal.misc
* @library /test/lib
* @library ../share
* @run main/othervm -XX:+UsePerfData -Xmx128M -XX:MaxMetaspaceSize=128M GcCauseTest03
*/
import utils.*;
public class GcCauseTest03 {
private final static float targetMemoryUsagePercent = 0.7f;
public static void main(String[] args) throws Exception {
// We will be running "jstat -gc" tool
JstatGcCauseTool jstatGcTool = new JstatGcCauseTool(ProcessHandle.current().pid());
System.gc();
// Run once and get the results asserting that they are reasonable
JstatGcCauseResults measurement = jstatGcTool.measure();
measurement.assertConsistency();
if (measurement.valueExists("LGCC")) {
if (!"System.gc()".equals(measurement.getStringValue("LGCC"))) {
throw new RuntimeException("Unexpected GC cause: " + measurement.getStringValue("LGCC") + ", expected System.gc()");
}
}
}
}
| gpl-2.0 |
archienz/universal-media-server | src/main/java/net/pms/newgui/TracesTab.java | 4921 | /*
* PS3 Media Server, for streaming any medias to your PS3.
* Copyright (C) 2008 A.Brochard
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; version 2
* of the License only.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package net.pms.newgui;
import java.awt.Color;
import java.awt.ComponentOrientation;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Locale;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import net.pms.Messages;
import net.pms.configuration.PmsConfiguration;
import net.pms.logging.LoggingConfigFileLoader;
import net.pms.util.FormLayoutUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.jgoodies.forms.builder.PanelBuilder;
import com.jgoodies.forms.layout.CellConstraints;
import com.jgoodies.forms.layout.FormLayout;
public class TracesTab {
private static final Logger LOGGER = LoggerFactory.getLogger(TracesTab.class);
private PmsConfiguration configuration;
class PopupTriggerMouseListener extends MouseAdapter {
private JPopupMenu popup;
private JComponent component;
public PopupTriggerMouseListener(JPopupMenu popup, JComponent component) {
this.popup = popup;
this.component = component;
}
// Some systems trigger popup on mouse press, others on mouse release, we want to cater for both
private void showMenuIfPopupTrigger(MouseEvent e) {
if (e.isPopupTrigger()) {
popup.show(component, e.getX() + 3, e.getY() + 3);
}
}
// According to the javadocs on isPopupTrigger, checking for popup trigger on mousePressed and mouseReleased
// Should be all that is required
public void mousePressed(MouseEvent e) {
showMenuIfPopupTrigger(e);
}
public void mouseReleased(MouseEvent e) {
showMenuIfPopupTrigger(e);
}
}
private JTextArea jList;
TracesTab(PmsConfiguration configuration) {
this.configuration = configuration;
}
public JTextArea getList() {
return jList;
}
public JComponent build() {
// Apply the orientation for the locale
Locale locale = new Locale(configuration.getLanguage());
ComponentOrientation orientation = ComponentOrientation.getOrientation(locale);
String colSpec = FormLayoutUtil.getColSpec("left:pref, 10:grow", orientation);
FormLayout layout = new FormLayout(
colSpec,
"fill:10:grow, p");
PanelBuilder builder = new PanelBuilder(layout);
// builder.setBorder(Borders.DLU14_BORDER);
builder.setOpaque(true);
CellConstraints cc = new CellConstraints();
//create trace text box
jList = new JTextArea();
jList.setEditable(false);
jList.setBackground(Color.WHITE);
jList.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 12));
final JPopupMenu popup = new JPopupMenu();
JMenuItem defaultItem = new JMenuItem(Messages.getString("TracesTab.3"));
defaultItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
jList.setText("");
}
});
popup.add(defaultItem);
jList.addMouseListener(
new PopupTriggerMouseListener(
popup,
jList));
JScrollPane pane = new JScrollPane(jList, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
builder.add(pane, cc.xyw(1, 1, 2));
// Add buttons opening log files
JPanel pLogFileButtons = new JPanel(new FlowLayout(FlowLayout.RIGHT));
HashMap<String, String> logFiles = LoggingConfigFileLoader.getLogFilePaths();
for (String loggerName : logFiles.keySet()) {
JButton b = new JButton(loggerName);
b.setToolTipText(logFiles.get(loggerName));
b.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
File logFile = new File(((JButton) e.getSource()).getToolTipText());
try {
java.awt.Desktop.getDesktop().open(logFile);
} catch (IOException e1) {
LOGGER.error(String.format("Failed to open file %s in default editor", logFile), e1);
}
}
});
pLogFileButtons.add(b);
}
builder.add(pLogFileButtons, cc.xy(2, 2));
return builder.getPanel();
}
}
| gpl-2.0 |
md-5/jdk10 | test/jdk/java/awt/font/FontPathEnvTest/FontPathEnvTest.java | 3199 | /*
* Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 8212703
* @summary Test JAVA2D_FONTPATH env. var does not set a system property
*/
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class FontPathEnvTest {
public static void main(String args[]) {
String env = System.getenv("JAVA2D_FONTPATH");
if (env == null) {
createChild();
} else {
String prop = System.getProperty("sun.java2d.fontpath");
if (prop != null && env.equals(prop)) {
throw new RuntimeException("sun.java2d.fontpath property set");
}
}
}
static void createChild() {
String cpDir = System.getProperty("java.class.path");
Map<String, String> env = new HashMap<String, String>();
env.put("JAVA2D_FONTPATH", "anyValue");
String jHome = System.getProperty("java.home");
String jCmd = jHome + File.separator + "bin" + File.separator + "java";
int exitValue = doExec(env, jCmd, "-cp", cpDir, "FontPathEnvTest");
if (exitValue != 0) {
throw new RuntimeException("Test Failed");
}
}
static int doExec(Map<String, String> envToSet, String... cmds) {
Process p = null;
ProcessBuilder pb = new ProcessBuilder(cmds);
Map<String, String> env = pb.environment();
for (String cmd : cmds) {
System.out.print(cmd + " ");
}
System.out.println();
if (envToSet != null) {
env.putAll(envToSet);
}
BufferedReader rdr = null;
try {
pb.redirectErrorStream(true);
p = pb.start();
rdr = new BufferedReader(new InputStreamReader(p.getInputStream()));
String in = rdr.readLine();
while (in != null) {
in = rdr.readLine();
System.out.println(in);
}
p.waitFor();
p.destroy();
} catch (Exception ex) {
ex.printStackTrace();
}
return p.exitValue();
}
}
| gpl-2.0 |
md-5/jdk10 | test/jdk/java/net/URLConnection/ZeroContentLength.java | 10962 | /*
* Copyright (c) 2001, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* @test
* @bug 4507412
* @bug 4506998
* @summary Check that a 304 "Not-Modified" response from a server
* doesn't cause http client to close a keep-alive
* connection.
* Check that a content-length of 0 results in an
* empty input stream.
* @library /test/lib
* @run main ZeroContentLength
* @run main/othervm -Djava.net.preferIPv6Addresses=true ZeroContentLength
*/
import java.net.*;
import java.io.*;
import jdk.test.lib.net.URIBuilder;
public class ZeroContentLength {
/*
* Is debugging enabled - start with -d to enable.
*/
static boolean debug = false;
static void debug(String msg) {
if (debug)
System.out.println(msg);
}
/*
* The response string and content-length that
* the server should return;
*/
static String response;
static int contentLength;
static synchronized void setResponse(String rsp, int cl) {
response = rsp;
contentLength = cl;
}
static synchronized String getResponse() {
return response;
}
static synchronized int getContentLength() {
return contentLength;
}
/*
* Worker thread to service single connection - can service
* multiple http requests on same connection.
*/
class Worker extends Thread {
Socket s;
int id;
Worker(Socket s, int id) {
this.s = s;
this.id = id;
}
final int CR = '\r';
final int LF = '\n';
public void run() {
try {
s.setSoTimeout(2000);
int max = 20; // there should only be 20 connections
InputStream in = new BufferedInputStream(s.getInputStream());
for (;;) {
// read entire request from client, until CR LF CR LF
int c, total=0;
try {
while ((c = in.read()) > 0) {
total++;
if (c == CR) {
if ((c = in.read()) > 0) {
total++;
if (c == LF) {
if ((c = in.read()) > 0) {
total++;
if (c == CR) {
if ((c = in.read()) > 0) {
total++;
if (c == LF) {
break;
}
}
}
}
}
}
}
}
} catch (SocketTimeoutException e) {}
debug("worker " + id +
": Read request from client " +
"(" + total + " bytes).");
if (total == 0) {
debug("worker: " + id + ": Shutdown");
return;
}
// response to client
PrintStream out = new PrintStream(
new BufferedOutputStream(
s.getOutputStream() ));
out.print("HTTP/1.1 " + getResponse() + "\r\n");
int clen = getContentLength();
if (clen >= 0) {
out.print("Content-Length: " + clen +
"\r\n");
}
out.print("\r\n");
for (int i=0; i<clen; i++) {
out.write( (byte)'.' );
}
out.flush();
debug("worked " + id +
": Sent response to client, length: " + clen);
if (--max == 0) {
s.close();
return;
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
s.close();
} catch (Exception e) { }
}
}
}
/*
* Server thread to accept connection and create worker threads
* to service each connection.
*/
class Server extends Thread {
ServerSocket ss;
int connectionCount;
boolean shutdown = false;
Server(ServerSocket ss) {
this.ss = ss;
}
public synchronized int connectionCount() {
return connectionCount;
}
public synchronized void shutdown() {
shutdown = true;
}
public void run() {
try {
ss.setSoTimeout(2000);
for (;;) {
Socket s;
try {
debug("server: Waiting for connections");
s = ss.accept();
} catch (SocketTimeoutException te) {
synchronized (this) {
if (shutdown) {
debug("server: Shuting down.");
return;
}
}
continue;
}
int id;
synchronized (this) {
id = connectionCount++;
}
Worker w = new Worker(s, id);
w.start();
debug("server: Started worker " + id);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
ss.close();
} catch (Exception e) { }
}
}
}
/*
* Make a single http request and return the content length
* received. Also do sanity check to ensure that the
* content-length header matches the total received on
* the input stream.
*/
int doRequest(String uri) throws Exception {
URL url = new URL(uri);
HttpURLConnection http = (HttpURLConnection)url.openConnection(Proxy.NO_PROXY);
int cl = http.getContentLength();
InputStream in = http.getInputStream();
byte b[] = new byte[100];
int total = 0;
int n;
do {
n = in.read(b);
if (n > 0) total += n;
} while (n > 0);
in.close();
if (cl >= 0 && total != cl) {
System.err.println("content-length header indicated: " + cl);
System.err.println("Actual received: " + total);
throw new Exception("Content-length didn't match actual received");
}
return total;
}
/*
* Send http requests to "server" and check that they all
* use the same network connection and that the content
* length corresponds to the content length expected.
* stream.
*/
ZeroContentLength() throws Exception {
/* start the server */
ServerSocket ss = new ServerSocket();
ss.bind(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0));
Server svr = new Server(ss);
svr.start();
String uri = URIBuilder.newBuilder()
.scheme("http")
.host(ss.getInetAddress())
.port(ss.getLocalPort())
.path("/foo.html")
.build().toString();
int expectedTotal = 0;
int actualTotal = 0;
System.out.println("**********************************");
System.out.println("200 OK, content-length:1024 ...");
setResponse("200 OK", 1024);
for (int i=0; i<5; i++) {
actualTotal += doRequest(uri);
expectedTotal += 1024;
}
System.out.println("**********************************");
System.out.println("200 OK, content-length:0 ...");
setResponse("200 OK", 0);
for (int i=0; i<5; i++) {
actualTotal += doRequest(uri);
}
System.out.println("**********************************");
System.out.println("304 Not-Modified, (no content-length) ...");
setResponse("304 Not-Modifed", -1);
for (int i=0; i<5; i++) {
actualTotal += doRequest(uri);
}
System.out.println("**********************************");
System.out.println("204 No-Content, (no content-length) ...");
setResponse("204 No-Content", -1);
for (int i=0; i<5; i++) {
actualTotal += doRequest(uri);
}
// shutdown server - we're done.
svr.shutdown();
System.out.println("**********************************");
if (actualTotal == expectedTotal) {
System.out.println("Passed: Actual total equal to expected total");
} else {
throw new Exception("Actual total != Expected total!!!");
}
int cnt = svr.connectionCount();
if (cnt == 1) {
System.out.println("Passed: Only 1 connection established");
} else {
throw new Exception("Test failed: Number of connections " +
"established: " + cnt + " - see log for details.");
}
}
public static void main(String args[]) throws Exception {
if (args.length > 0 && args[0].equals("-d")) {
debug = true;
}
new ZeroContentLength();
}
}
| gpl-2.0 |
khajavi/PageTurner | src/net/nightwhistler/pageturner/catalog/Catalog.java | 3525 | /*
* Copyright (C) 2013 Alex Kuiper
*
* This file is part of PageTurner
*
* PageTurner is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* PageTurner is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with PageTurner. If not, see <http://www.gnu.org/licenses/>.*
*/
package net.nightwhistler.pageturner.catalog;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import jedi.functional.Filter;
import jedi.option.Option;
import net.nightwhistler.htmlspanner.HtmlSpanner;
import net.nightwhistler.nucular.atom.Entry;
import net.nightwhistler.nucular.atom.Feed;
import net.nightwhistler.nucular.atom.Link;
import net.nightwhistler.pageturner.R;
import net.nightwhistler.pageturner.view.FastBitmapDrawable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
import static java.util.Arrays.asList;
import static jedi.functional.FunctionalPrimitives.firstOption;
import static jedi.functional.FunctionalPrimitives.isEmpty;
public class Catalog {
/**
* Reserved ID to identify the feed entry where custom sites are added.
*/
public static final String CUSTOM_SITES_ID = "IdCustomSites";
private static final int ABBREV_TEXT_LEN = 150;
private static final Logger LOG = LoggerFactory.getLogger("Catalog");
private Catalog() {}
/**
* Selects the right image link for an entry, based on preference.
*
* @param feed
* @param entry
* @return
*/
public static Option<Link> getImageLink(Feed feed, Entry entry) {
List<Link> items;
if ( feed.isDetailFeed() ) {
items = asList( entry.getImageLink().unsafeGet(), entry.getThumbnailLink().unsafeGet() );
} else {
items = asList( entry.getThumbnailLink().unsafeGet(), entry.getImageLink().unsafeGet() );
}
return firstOption( items, l -> l != null );
}
/**
* Loads the details for the given entry into the given layout.
*
* @param layout
* @param entry
* @param abbreviateText
*/
public static void loadBookDetails(View layout, Entry entry, boolean abbreviateText ) {
HtmlSpanner spanner = new HtmlSpanner();
//We don't want to load images here
spanner.unregisterHandler( "img" );
TextView title = (TextView) layout.findViewById(R.id.itemTitle);
TextView desc = (TextView) layout
.findViewById(R.id.itemDescription);
title.setText( entry.getTitle());
CharSequence text;
if (entry.getContent() != null) {
text = spanner.fromHtml(entry.getContent().getText());
} else if (entry.getSummary() != null) {
text = spanner.fromHtml(entry.getSummary());
} else {
text = "";
}
if (abbreviateText && text.length() > ABBREV_TEXT_LEN ) {
text = text.subSequence(0, ABBREV_TEXT_LEN) + "…";
}
desc.setText(text);
}
}
| gpl-3.0 |
EliasFarhan/gsn | src/main/java/gsn/utils/services/EmailService.java | 3581 | /**
* Global Sensor Networks (GSN) Source Code
* Copyright (c) 2006-2014, Ecole Polytechnique Federale de Lausanne (EPFL)
*
* This file is part of GSN.
*
* GSN is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* GSN is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with GSN. If not, see <http://www.gnu.org/licenses/>.
*
* File: src/gsn/utils/services/EmailService.java
*
* @author Timotee Maret
*
*/
package gsn.utils.services;
import gsn.utils.Utils;
import org.apache.commons.mail.Email;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.SimpleEmail;
import org.apache.log4j.Logger;
import javax.mail.Session;
import java.util.ArrayList;
/**
* This class provides an access to Email Notification services.
* The implementation is based on the Apache commons Email library @see http://commons.apache.org/email/
* Prior to use this service, you MUST configure the SMTP server (postfix, gmail, ...) which will send your emails.
* The smtp parameters are configured in the conf/emails.properties.
*/
public class EmailService {
private static final transient Logger logger = Logger.getLogger(EmailService.class);
private static final String SMTP_FILE = "conf/emails.properties";
/**
* This method cover most of the cases of sending a simple text email. If the email to be sent has to be configured
* in a way which is not possible whith the parameters provided (such as html email, or email with attachement, ..),
* please use the {@link #sendCustomEmail(org.apache.commons.mail.Email)} method and refer the API
* {@see http://commons.apache.org/email/}.
*
* @param to A set of destination email address of the email. Must contain at least one address.
* @param object The subject of the email.
* @param message The msg of the email.
* @return true if the email has been sent successfully, false otherwise.
*/
public static boolean sendEmail(ArrayList<String> to, String object, String message) {
Email email = new SimpleEmail();
try {
email.setSubject(object);
email.setMsg(message);
if (to != null)
for (String _to : to)
email.addTo(_to);
sendCustomEmail(email);
return true;
}
catch (EmailException e) {
logger.warn("Please, make sure that the SMTP server configuration is correct in the file: " + SMTP_FILE);
logger.error(e.getMessage(), e);
return false;
}
}
/**
* This method send a user configured email {@link org.apache.commons.mail.Email} after having updated the
* email session from the property file.
*
* @param email
* @return true if the email has been sent successfully, false otherwise.
* @throws org.apache.commons.mail.EmailException
*
*/
public static void sendCustomEmail(org.apache.commons.mail.Email email) throws EmailException {
email.setMailSession(Session.getInstance(Utils.loadProperties(SMTP_FILE)));
email.setDebug(true);
email.send();
}
}
| gpl-3.0 |
jerrycable/tasks | src/main/java/com/todoroo/astrid/ui/RandomReminderControlSet.java | 2118 | /**
* Copyright (c) 2012 Todoroo Inc
*
* See the file "LICENSE" for the full license governing this code.
*/
package com.todoroo.astrid.ui;
import android.app.Activity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import com.todoroo.andlib.utility.DateUtilities;
import com.todoroo.astrid.data.Task;
import org.tasks.R;
/**
* Control set dealing with random reminder settings
*
* @author Tim Su <tim@todoroo.com>
*
*/
public class RandomReminderControlSet {
private final Spinner periodSpinner;
private final int[] hours;
public RandomReminderControlSet(Activity activity, View parentView) {
periodSpinner = (Spinner) parentView.findViewById(R.id.reminder_random_interval);
periodSpinner.setVisibility(View.VISIBLE);
// create adapter
ArrayAdapter<String> adapter = new ArrayAdapter<>(
activity, android.R.layout.simple_spinner_item,
activity.getResources().getStringArray(R.array.TEA_reminder_random));
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
periodSpinner.setAdapter(adapter);
// create hour array
String[] hourStrings = activity.getResources().getStringArray(R.array.TEA_reminder_random_hours);
hours = new int[hourStrings.length];
for(int i = 0; i < hours.length; i++) {
hours[i] = Integer.parseInt(hourStrings[i]);
}
}
public void readFromTaskOnInitialize(Task model) {
long time = model.getReminderPeriod();
if(time <= 0) {
/* default interval for spinner if date is unselected */
time = DateUtilities.ONE_WEEK * 2;
}
int i;
for(i = 0; i < hours.length - 1; i++) {
if (hours[i] * DateUtilities.ONE_HOUR >= time) {
break;
}
}
periodSpinner.setSelection(i);
}
public long getReminderPeriod() {
int hourValue = hours[periodSpinner.getSelectedItemPosition()];
return hourValue * DateUtilities.ONE_HOUR;
}
}
| gpl-3.0 |
s20121035/rk3288_android5.1_repo | cts/tools/vm-tests-tf/src/dot/junit/opcodes/if_eq/d/T_if_eq_11.java | 139 | package dot.junit.opcodes.if_eq.d;
public class T_if_eq_11 {
public boolean run(String a, String b) {
return a == b;
}
}
| gpl-3.0 |
moria/popcorn-android | xmlrpc/src/main/java/org/xmlrpc/android/XMLRPCSerializer.java | 12178 | package org.xmlrpc.android;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.util.Xml;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlSerializer;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.SimpleTimeZone;
class XMLRPCSerializer {
static final String TAG_NAME = "name";
static final String TAG_MEMBER = "member";
static final String TAG_VALUE = "value";
static final String TAG_DATA = "data";
static final String TYPE_INT = "int";
static final String TYPE_I4 = "i4";
static final String TYPE_I8 = "i8";
static final String TYPE_DOUBLE = "double";
static final String TYPE_BOOLEAN = "boolean";
static final String TYPE_STRING = "string";
static final String TYPE_DATE_TIME_ISO8601 = "dateTime.iso8601";
static final String TYPE_BASE64 = "base64";
static final String TYPE_ARRAY = "array";
static final String TYPE_STRUCT = "struct";
static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd'T'HH:mm:ss");
static Calendar cal = Calendar.getInstance(new SimpleTimeZone(0, "GMT"));
private static final XmlSerializer serializeTester;
static {
serializeTester = Xml.newSerializer();
try {
serializeTester.setOutput(new NullOutputStream(), "UTF-8");
} catch (IllegalArgumentException e) {
Log.e("XML-RPC", "IllegalArgumentException setting test serializer output stream", e);
} catch (IllegalStateException e) {
Log.e("XML-RPC", "IllegalStateException setting test serializer output stream", e);
} catch (IOException e) {
Log.e("XML-RPC", "IOException setting test serializer output stream", e);
}
}
@SuppressWarnings("unchecked")
static void serialize(XmlSerializer serializer, Object object) throws IOException {
// check for scalar types:
if (object instanceof Integer || object instanceof Short || object instanceof Byte) {
serializer.startTag(null, TYPE_I4).text(object.toString()).endTag(null, TYPE_I4);
} else if (object instanceof Long) {
// Note Long should be represented by a TYPE_I8 but the WordPress end point doesn't support <i8> tag
// Long usually represents IDs, so we convert them to string
serializer.startTag(null, TYPE_STRING).text(object.toString()).endTag(null, TYPE_STRING);
Log.w("XML-RPC", "long type could be misinterpreted when sent to the WordPress XMLRPC end point");
} else if (object instanceof Double || object instanceof Float) {
serializer.startTag(null, TYPE_DOUBLE).text(object.toString()).endTag(null, TYPE_DOUBLE);
} else if (object instanceof Boolean) {
Boolean bool = (Boolean) object;
String boolStr = bool.booleanValue() ? "1" : "0";
serializer.startTag(null, TYPE_BOOLEAN).text(boolStr).endTag(null, TYPE_BOOLEAN);
} else if (object instanceof String) {
serializer.startTag(null, TYPE_STRING).text(makeValidInputString((String) object)).endTag(null, TYPE_STRING);
} else if (object instanceof Date || object instanceof Calendar) {
Date date = (Date) object;
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd'T'HH:mm:ss");
dateFormat.setCalendar(cal);
String sDate = dateFormat.format(date);
serializer.startTag(null, TYPE_DATE_TIME_ISO8601).text(sDate).endTag(null, TYPE_DATE_TIME_ISO8601);
} else if (object instanceof byte[]) {
String value;
try {
value = Base64.encodeToString((byte[]) object, Base64.DEFAULT);
serializer.startTag(null, TYPE_BASE64).text(value).endTag(null, TYPE_BASE64);
} catch (OutOfMemoryError e) {
throw new IOException("Out of memory");
}
} else if (object instanceof List<?>) {
serializer.startTag(null, TYPE_ARRAY).startTag(null, TAG_DATA);
List<Object> list = (List<Object>) object;
Iterator<Object> iter = list.iterator();
while (iter.hasNext()) {
Object o = iter.next();
serializer.startTag(null, TAG_VALUE);
serialize(serializer, o);
serializer.endTag(null, TAG_VALUE);
}
serializer.endTag(null, TAG_DATA).endTag(null, TYPE_ARRAY);
} else if (object instanceof Object[]) {
serializer.startTag(null, TYPE_ARRAY).startTag(null, TAG_DATA);
Object[] objects = (Object[]) object;
for (int i = 0; i < objects.length; i++) {
Object o = objects[i];
serializer.startTag(null, TAG_VALUE);
serialize(serializer, o);
serializer.endTag(null, TAG_VALUE);
}
serializer.endTag(null, TAG_DATA).endTag(null, TYPE_ARRAY);
} else if (object instanceof Map) {
serializer.startTag(null, TYPE_STRUCT);
Map<String, Object> map = (Map<String, Object>) object;
Iterator<Entry<String, Object>> iter = map.entrySet().iterator();
while (iter.hasNext()) {
Entry<String, Object> entry = iter.next();
String key = entry.getKey();
Object value = entry.getValue();
serializer.startTag(null, TAG_MEMBER);
serializer.startTag(null, TAG_NAME).text(key).endTag(null, TAG_NAME);
serializer.startTag(null, TAG_VALUE);
serialize(serializer, value);
serializer.endTag(null, TAG_VALUE);
serializer.endTag(null, TAG_MEMBER);
}
serializer.endTag(null, TYPE_STRUCT);
} else {
throw new IOException("Cannot serialize " + object);
}
}
private static final String makeValidInputString(final String input) throws IOException {
if (TextUtils.isEmpty(input))
return "";
if (serializeTester == null)
return input;
try {
// try to encode the string as-is, 99.9% of the time it's OK
serializeTester.text(input);
return input;
} catch (IllegalArgumentException e) {
// There are characters outside the XML unicode charset as specified by the XML 1.0 standard
// See http://www.w3.org/TR/2000/REC-xml-20001006#NT-Char
Log.e("XML-RPC", "There are characters outside the XML unicode charset as specified by the XML 1.0 standard", e);
}
try {
serializeTester.text(input);
return input;
} catch (IllegalArgumentException e) {
Log.e("XML-RPC", "noEmojiString still contains characters outside the XML unicode charset as specified by the XML 1.0 standard", e);
StringBuilder out = new StringBuilder(); // Used to hold the output.
char current; // Used to reference the current character.
if ("".equals(input)) {
return ""; // vacancy test.
}
for (int i = 0; i < input.length(); i++) {
current = input.charAt(i); // NOTE: No IndexOutOfBoundsException caught here; it should not happen.
if ((current == 0x9) ||
(current == 0xA) ||
(current == 0xD) ||
((current >= 0x20) && (current <= 0xD7FF)) ||
((current >= 0xE000) && (current <= 0xFFFD)) ||
((current >= 0x10000) && (current <= 0x10FFFF))) {
out.append(current);
}
}
return out.toString();
}
}
static Object deserialize(XmlPullParser parser) throws XmlPullParserException, IOException, NumberFormatException {
parser.require(XmlPullParser.START_TAG, null, TAG_VALUE);
parser.nextTag();
String typeNodeName = parser.getName();
Object obj;
if (typeNodeName.equals(TYPE_INT) || typeNodeName.equals(TYPE_I4)) {
String value = parser.nextText();
try {
obj = Integer.parseInt(value);
} catch (NumberFormatException nfe) {
Log.w("XMLRPC", "Server replied with an invalid 4 bytes int value, trying to parse it as 8 bytes long");
obj = Long.parseLong(value);
}
} else if (typeNodeName.equals(TYPE_I8)) {
String value = parser.nextText();
obj = Long.parseLong(value);
} else if (typeNodeName.equals(TYPE_DOUBLE)) {
String value = parser.nextText();
obj = Double.parseDouble(value);
} else if (typeNodeName.equals(TYPE_BOOLEAN)) {
String value = parser.nextText();
obj = value.equals("1") ? Boolean.TRUE : Boolean.FALSE;
} else if (typeNodeName.equals(TYPE_STRING)) {
obj = parser.nextText();
} else if (typeNodeName.equals(TYPE_DATE_TIME_ISO8601)) {
dateFormat.setCalendar(cal);
String value = parser.nextText();
try {
obj = dateFormat.parseObject(value);
} catch (ParseException e) {
Log.e("XMLRPC", e.toString());
obj = value;
}
} else if (typeNodeName.equals(TYPE_BASE64)) {
String value = parser.nextText();
BufferedReader reader = new BufferedReader(new StringReader(value));
String line;
StringBuffer sb = new StringBuffer();
while ((line = reader.readLine()) != null) {
sb.append(line);
}
obj = Base64.decode(sb.toString(), Base64.DEFAULT);
} else if (typeNodeName.equals(TYPE_ARRAY)) {
parser.nextTag(); // TAG_DATA (<data>)
parser.require(XmlPullParser.START_TAG, null, TAG_DATA);
parser.nextTag();
List<Object> list = new ArrayList<Object>();
while (parser.getName().equals(TAG_VALUE)) {
list.add(deserialize(parser));
parser.nextTag();
}
parser.require(XmlPullParser.END_TAG, null, TAG_DATA);
parser.nextTag(); // TAG_ARRAY (</array>)
parser.require(XmlPullParser.END_TAG, null, TYPE_ARRAY);
obj = list.toArray();
} else if (typeNodeName.equals(TYPE_STRUCT)) {
parser.nextTag();
Map<String, Object> map = new HashMap<String, Object>();
while (parser.getName().equals(TAG_MEMBER)) {
String memberName = null;
Object memberValue = null;
while (true) {
parser.nextTag();
String name = parser.getName();
if (name.equals(TAG_NAME)) {
memberName = parser.nextText();
} else if (name.equals(TAG_VALUE)) {
memberValue = deserialize(parser);
} else {
break;
}
}
if (memberName != null && memberValue != null) {
map.put(memberName, memberValue);
}
parser.require(XmlPullParser.END_TAG, null, TAG_MEMBER);
parser.nextTag();
}
parser.require(XmlPullParser.END_TAG, null, TYPE_STRUCT);
obj = map;
} else {
throw new IOException("Cannot deserialize " + parser.getName());
}
parser.nextTag(); // TAG_VALUE (</value>)
parser.require(XmlPullParser.END_TAG, null, TAG_VALUE);
return obj;
}
}
| gpl-3.0 |
open-health-hub/openMAXIMS | openmaxims_workspace/Clinical/src/ims/clinical/forms/cliniclistactionsummary/Handlers.java | 10269 | //#############################################################################
//# #
//# Copyright (C) <2014> <IMS MAXIMS> #
//# #
//# This program is free software: you can redistribute it and/or modify #
//# it under the terms of the GNU Affero General Public License as #
//# published by the Free Software Foundation, either version 3 of the #
//# License, or (at your option) any later version. #
//# #
//# This program is distributed in the hope that it will be useful, #
//# but WITHOUT ANY WARRANTY; without even the implied warranty of #
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//# GNU Affero General Public License for more details. #
//# #
//# You should have received a copy of the GNU Affero General Public License #
//# along with this program. If not, see <http://www.gnu.org/licenses/>. #
//# #
//#############################################################################
//#EOH
// This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751)
// Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved.
// WARNING: DO NOT MODIFY the content of this file
package ims.clinical.forms.cliniclistactionsummary;
import ims.framework.delegates.*;
abstract public class Handlers implements ims.framework.UILogic, IFormUILogicCode, ims.framework.interfaces.IClearInfo
{
abstract protected void bindcmbAppOutcomeLookup();
abstract protected void defaultcmbAppOutcomeLookupValue();
abstract protected void bindcmbActionLookup();
abstract protected void defaultcmbActionLookupValue();
abstract protected void onMessageBoxClosed(int messageBoxId, ims.framework.enumerations.DialogResult result) throws ims.framework.exceptions.PresentationLogicException;
abstract protected void onFormOpen(Object[] args) throws ims.framework.exceptions.PresentationLogicException;
abstract protected void onFormDialogClosed(ims.framework.FormName formName, ims.framework.enumerations.DialogResult result) throws ims.framework.exceptions.PresentationLogicException;
abstract protected void oncmbAppOutcomeValueSet(Object value);
abstract protected void onCmbHospitalValueChanged() throws ims.framework.exceptions.PresentationLogicException;
abstract protected void onBtnTaskCompleteClick() throws ims.framework.exceptions.PresentationLogicException;
abstract protected void onBtnViewOutcomeClick() throws ims.framework.exceptions.PresentationLogicException;
abstract protected void oncmbActionValueSet(Object value);
abstract protected void onCmbActionValueChanged() throws ims.framework.exceptions.PresentationLogicException;
abstract protected void onGrdResultsGridHeaderClicked(int column) throws ims.framework.exceptions.PresentationLogicException;
abstract protected void onGrdResultsSelectionChanged() throws ims.framework.exceptions.PresentationLogicException;
abstract protected void onDteDateValueChanged() throws ims.framework.exceptions.PresentationLogicException;
abstract protected void onCmbClinicValueChanged() throws ims.framework.exceptions.PresentationLogicException;
abstract protected void onImbClearClick() throws ims.framework.exceptions.PresentationLogicException;
abstract protected void onImbSearchClick() throws ims.framework.exceptions.PresentationLogicException;
abstract protected void onContextMenuItemClick(int menuItemID, ims.framework.Control sender) throws ims.framework.exceptions.PresentationLogicException;
public final void setContext(ims.framework.UIEngine engine, GenForm form)
{
this.engine = engine;
this.form = form;
this.form.setMessageBoxClosedEvent(new MessageBoxClosed()
{
private static final long serialVersionUID = 1L;
public void handle(int messageBoxId, ims.framework.enumerations.DialogResult result) throws ims.framework.exceptions.PresentationLogicException
{
onMessageBoxClosed(messageBoxId, result);
}
});
this.form.setFormOpenEvent(new FormOpen()
{
private static final long serialVersionUID = 1L;
public void handle(Object[] args) throws ims.framework.exceptions.PresentationLogicException
{
bindLookups();
onFormOpen(args);
}
});
this.form.setFormDialogClosedEvent(new FormDialogClosed()
{
private static final long serialVersionUID = 1L;
public void handle(ims.framework.FormName formName, ims.framework.enumerations.DialogResult result) throws ims.framework.exceptions.PresentationLogicException
{
onFormDialogClosed(formName, result);
}
});
this.form.cmbAppOutcome().setValueSetEvent(new ComboBoxValueSet()
{
private static final long serialVersionUID = 1L;
public void handle(Object value)
{
oncmbAppOutcomeValueSet(value);
}
});
this.form.cmbHospital().setValueChangedEvent(new ValueChanged()
{
private static final long serialVersionUID = 1L;
public void handle() throws ims.framework.exceptions.PresentationLogicException
{
onCmbHospitalValueChanged();
}
});
this.form.btnTaskComplete().setClickEvent(new Click()
{
private static final long serialVersionUID = 1L;
public void handle() throws ims.framework.exceptions.PresentationLogicException
{
onBtnTaskCompleteClick();
}
});
this.form.btnViewOutcome().setClickEvent(new Click()
{
private static final long serialVersionUID = 1L;
public void handle() throws ims.framework.exceptions.PresentationLogicException
{
onBtnViewOutcomeClick();
}
});
this.form.cmbAction().setValueSetEvent(new ComboBoxValueSet()
{
private static final long serialVersionUID = 1L;
public void handle(Object value)
{
oncmbActionValueSet(value);
}
});
this.form.cmbAction().setValueChangedEvent(new ValueChanged()
{
private static final long serialVersionUID = 1L;
public void handle() throws ims.framework.exceptions.PresentationLogicException
{
onCmbActionValueChanged();
}
});
this.form.grdResults().setGridHeaderClickedEvent(new GridHeaderClicked()
{
private static final long serialVersionUID = 1L;
public void handle(int column) throws ims.framework.exceptions.PresentationLogicException
{
onGrdResultsGridHeaderClicked(column);
}
});
this.form.grdResults().setSelectionChangedEvent(new GridSelectionChanged()
{
private static final long serialVersionUID = 1L;
public void handle(ims.framework.enumerations.MouseButton mouseButton) throws ims.framework.exceptions.PresentationLogicException
{
onGrdResultsSelectionChanged();
}
});
this.form.dteDate().setValueChangedEvent(new ValueChanged()
{
private static final long serialVersionUID = 1L;
public void handle() throws ims.framework.exceptions.PresentationLogicException
{
onDteDateValueChanged();
}
});
this.form.cmbClinic().setValueChangedEvent(new ValueChanged()
{
private static final long serialVersionUID = 1L;
public void handle() throws ims.framework.exceptions.PresentationLogicException
{
onCmbClinicValueChanged();
}
});
this.form.imbClear().setClickEvent(new Click()
{
private static final long serialVersionUID = 1L;
public void handle() throws ims.framework.exceptions.PresentationLogicException
{
onImbClearClick();
}
});
this.form.imbSearch().setClickEvent(new Click()
{
private static final long serialVersionUID = 1L;
public void handle() throws ims.framework.exceptions.PresentationLogicException
{
onImbSearchClick();
}
});
this.form.getContextMenus().Clinical.getClinicListActionSummaryMenuADD_TO_WAITING_LISTItem().setClickEvent(new ims.framework.delegates.MenuItemClick()
{
private static final long serialVersionUID = 1L;
public void handle(ims.framework.Control sender) throws ims.framework.exceptions.PresentationLogicException
{
onContextMenuItemClick(GenForm.ContextMenus.ClinicalNamespace.ClinicListActionSummaryMenu.ADD_TO_WAITING_LIST, sender);
}
});
this.form.getContextMenus().Clinical.getClinicListActionSummaryMenuADD_TO_BOOKED_LISTItem().setClickEvent(new ims.framework.delegates.MenuItemClick()
{
private static final long serialVersionUID = 1L;
public void handle(ims.framework.Control sender) throws ims.framework.exceptions.PresentationLogicException
{
onContextMenuItemClick(GenForm.ContextMenus.ClinicalNamespace.ClinicListActionSummaryMenu.ADD_TO_BOOKED_LIST, sender);
}
});
this.form.getContextMenus().Clinical.getClinicListActionSummaryMenuADD_TO_PLANNED_LISTItem().setClickEvent(new ims.framework.delegates.MenuItemClick()
{
private static final long serialVersionUID = 1L;
public void handle(ims.framework.Control sender) throws ims.framework.exceptions.PresentationLogicException
{
onContextMenuItemClick(GenForm.ContextMenus.ClinicalNamespace.ClinicListActionSummaryMenu.ADD_TO_PLANNED_LIST, sender);
}
});
this.form.getContextMenus().Clinical.getClinicListActionSummaryMenuBOOK_APPOINTMENTItem().setClickEvent(new ims.framework.delegates.MenuItemClick()
{
private static final long serialVersionUID = 1L;
public void handle(ims.framework.Control sender) throws ims.framework.exceptions.PresentationLogicException
{
onContextMenuItemClick(GenForm.ContextMenus.ClinicalNamespace.ClinicListActionSummaryMenu.BOOK_APPOINTMENT, sender);
}
});
}
protected void bindLookups()
{
bindcmbAppOutcomeLookup();
bindcmbActionLookup();
}
protected void rebindAllLookups()
{
bindcmbAppOutcomeLookup();
bindcmbActionLookup();
}
protected void defaultAllLookupValues()
{
defaultcmbAppOutcomeLookupValue();
defaultcmbActionLookupValue();
}
public void free()
{
this.engine = null;
this.form = null;
}
public abstract void clearContextInformation();
protected ims.framework.UIEngine engine;
protected GenForm form;
}
| agpl-3.0 |
open-health-hub/openMAXIMS | openmaxims_workspace/ICP/src/ims/icp/forms/activatestagephases/BaseAccessLogic.java | 3507 | //#############################################################################
//# #
//# Copyright (C) <2014> <IMS MAXIMS> #
//# #
//# This program is free software: you can redistribute it and/or modify #
//# it under the terms of the GNU Affero General Public License as #
//# published by the Free Software Foundation, either version 3 of the #
//# License, or (at your option) any later version. #
//# #
//# This program is distributed in the hope that it will be useful, #
//# but WITHOUT ANY WARRANTY; without even the implied warranty of #
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//# GNU Affero General Public License for more details. #
//# #
//# You should have received a copy of the GNU Affero General Public License #
//# along with this program. If not, see <http://www.gnu.org/licenses/>. #
//# #
//#############################################################################
//#EOH
// This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751)
// Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved.
// WARNING: DO NOT MODIFY the content of this file
package ims.icp.forms.activatestagephases;
import java.io.Serializable;
import ims.framework.Context;
import ims.framework.FormName;
import ims.framework.FormAccessLogic;
public class BaseAccessLogic extends FormAccessLogic implements Serializable
{
private static final long serialVersionUID = 1L;
public final void setContext(Context context, FormName formName)
{
form = new CurrentForm(new GlobalContext(context), new CurrentForms());
engine = new CurrentEngine(formName);
}
public boolean isAccessible()
{
if(!form.getGlobalContext().ICP.getPatientICPRecordIsNotNull())
return false;
return true;
}
public boolean isReadOnly()
{
return false;
}
public CurrentEngine engine;
public CurrentForm form;
public final static class CurrentForm implements Serializable
{
private static final long serialVersionUID = 1L;
CurrentForm(GlobalContext globalcontext, CurrentForms forms)
{
this.globalcontext = globalcontext;
this.forms = forms;
}
public final GlobalContext getGlobalContext()
{
return globalcontext;
}
public final CurrentForms getForms()
{
return forms;
}
private GlobalContext globalcontext;
private CurrentForms forms;
}
public final static class CurrentEngine implements Serializable
{
private static final long serialVersionUID = 1L;
CurrentEngine(FormName formName)
{
this.formName = formName;
}
public final FormName getFormName()
{
return formName;
}
private FormName formName;
}
public static final class CurrentForms implements Serializable
{
private static final long serialVersionUID = 1L;
protected final class LocalFormName extends FormName
{
private static final long serialVersionUID = 1L;
protected LocalFormName(int value)
{
super(value);
}
}
private CurrentForms()
{
}
}
}
| agpl-3.0 |
open-health-hub/openMAXIMS | openmaxims_workspace/DomainObjects/src/ims/choose_book/domain/objects/SdsRequest.java | 17453 | //#############################################################################
//# #
//# Copyright (C) <2014> <IMS MAXIMS> #
//# #
//# This program is free software: you can redistribute it and/or modify #
//# it under the terms of the GNU Affero General Public License as #
//# published by the Free Software Foundation, either version 3 of the #
//# License, or (at your option) any later version. #
//# #
//# This program is distributed in the hope that it will be useful, #
//# but WITHOUT ANY WARRANTY; without even the implied warranty of #
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//# GNU Affero General Public License for more details. #
//# #
//# You should have received a copy of the GNU Affero General Public License #
//# along with this program. If not, see <http://www.gnu.org/licenses/>. #
//# #
//#############################################################################
//#EOH
/*
* This code was generated
* Copyright (C) 1995-2004 IMS MAXIMS plc. All rights reserved.
* IMS Development Environment (version 1.80 build 5007.25751)
* WARNING: DO NOT MODIFY the content of this file
* Generated: 16/04/2014, 12:34
*
*/
package ims.choose_book.domain.objects;
/**
*
* @author Barbara Worwood
* Generated.
*/
public class SdsRequest extends ims.domain.DomainObject implements ims.domain.SystemInformationRetainer, java.io.Serializable {
public static final int CLASSID = 1069100015;
private static final long serialVersionUID = 1069100015L;
public static final String CLASSVERSION = "${ClassVersion}";
@Override
public boolean shouldCapQuery()
{
return true;
}
/** Spine Data Services Referral ID e.g. GP */
private String referrerSdsId;
/** Spine Data Services Referral Role Id */
private String referrerSdsRoleId;
/** Spine Data Services Referral Organisation Id e.g. Practice */
private String referrerSdsOrgId;
/** Date and Time Request was placed */
private java.util.Date dateTimeRequested;
/** Date and Time the PDS was last checked for access */
private java.util.Date dateTimeLastChecked;
/** Active */
private Boolean active;
/** Any relevant comments */
private String comments;
/** Appointment associated with this request */
private Integer appointment;
/** SystemInformation */
private ims.domain.SystemInformation systemInformation = new ims.domain.SystemInformation();
public SdsRequest (Integer id, int ver)
{
super(id, ver);
}
public SdsRequest ()
{
super();
}
public SdsRequest (Integer id, int ver, Boolean includeRecord)
{
super(id, ver, includeRecord);
}
public Class getRealDomainClass()
{
return ims.choose_book.domain.objects.SdsRequest.class;
}
public String getReferrerSdsId() {
return referrerSdsId;
}
public void setReferrerSdsId(String referrerSdsId) {
if ( null != referrerSdsId && referrerSdsId.length() > 50 ) {
throw new ims.domain.exceptions.DomainRuntimeException("MaxLength ($MaxLength) exceeded for referrerSdsId. Tried to set value: "+
referrerSdsId);
}
this.referrerSdsId = referrerSdsId;
}
public String getReferrerSdsRoleId() {
return referrerSdsRoleId;
}
public void setReferrerSdsRoleId(String referrerSdsRoleId) {
if ( null != referrerSdsRoleId && referrerSdsRoleId.length() > 50 ) {
throw new ims.domain.exceptions.DomainRuntimeException("MaxLength ($MaxLength) exceeded for referrerSdsRoleId. Tried to set value: "+
referrerSdsRoleId);
}
this.referrerSdsRoleId = referrerSdsRoleId;
}
public String getReferrerSdsOrgId() {
return referrerSdsOrgId;
}
public void setReferrerSdsOrgId(String referrerSdsOrgId) {
if ( null != referrerSdsOrgId && referrerSdsOrgId.length() > 50 ) {
throw new ims.domain.exceptions.DomainRuntimeException("MaxLength ($MaxLength) exceeded for referrerSdsOrgId. Tried to set value: "+
referrerSdsOrgId);
}
this.referrerSdsOrgId = referrerSdsOrgId;
}
public java.util.Date getDateTimeRequested() {
return dateTimeRequested;
}
public void setDateTimeRequested(java.util.Date dateTimeRequested) {
this.dateTimeRequested = dateTimeRequested;
}
public java.util.Date getDateTimeLastChecked() {
return dateTimeLastChecked;
}
public void setDateTimeLastChecked(java.util.Date dateTimeLastChecked) {
this.dateTimeLastChecked = dateTimeLastChecked;
}
public Boolean isActive() {
return active;
}
public void setActive(Boolean active) {
this.active = active;
}
public String getComments() {
return comments;
}
public void setComments(String comments) {
if ( null != comments && comments.length() > 255 ) {
throw new ims.domain.exceptions.DomainRuntimeException("MaxLength ($MaxLength) exceeded for comments. Tried to set value: "+
comments);
}
this.comments = comments;
}
public Integer getAppointment() {
return appointment;
}
public void setAppointment(Integer appointment) {
this.appointment = appointment;
}
public ims.domain.SystemInformation getSystemInformation() {
if (systemInformation == null) systemInformation = new ims.domain.SystemInformation();
return systemInformation;
}
/**
* isConfigurationObject
* Taken from the Usage property of the business object, this method will return
* a boolean indicating whether this is a configuration object or not
* Configuration = true, Instantiation = false
*/
public static boolean isConfigurationObject()
{
if ( "Instantiation".equals("Configuration") )
return true;
else
return false;
}
public int getClassId() {
return CLASSID;
}
public String getClassVersion()
{
return CLASSVERSION;
}
public String toAuditString()
{
StringBuffer auditStr = new StringBuffer();
auditStr.append("\r\n*referrerSdsId* :");
auditStr.append(referrerSdsId);
auditStr.append("; ");
auditStr.append("\r\n*referrerSdsRoleId* :");
auditStr.append(referrerSdsRoleId);
auditStr.append("; ");
auditStr.append("\r\n*referrerSdsOrgId* :");
auditStr.append(referrerSdsOrgId);
auditStr.append("; ");
auditStr.append("\r\n*dateTimeRequested* :");
auditStr.append(dateTimeRequested);
auditStr.append("; ");
auditStr.append("\r\n*dateTimeLastChecked* :");
auditStr.append(dateTimeLastChecked);
auditStr.append("; ");
auditStr.append("\r\n*active* :");
auditStr.append(active);
auditStr.append("; ");
auditStr.append("\r\n*comments* :");
auditStr.append(comments);
auditStr.append("; ");
auditStr.append("\r\n*appointment* :");
auditStr.append(appointment);
auditStr.append("; ");
return auditStr.toString();
}
public String toXMLString()
{
return toXMLString(new java.util.HashMap());
}
public String toXMLString(java.util.HashMap domMap)
{
StringBuffer sb = new StringBuffer();
sb.append("<class type=\"" + this.getClass().getName() + "\" ");
sb.append(" id=\"" + this.getId() + "\"");
sb.append(" source=\"" + ims.configuration.EnvironmentConfig.getImportExportSourceName() + "\" ");
sb.append(" classVersion=\"" + this.getClassVersion() + "\" ");
sb.append(" component=\"" + this.getIsComponentClass() + "\" >");
if (domMap.get(this) == null)
{
domMap.put(this, this);
sb.append(this.fieldsToXMLString(domMap));
}
sb.append("</class>");
String keyClassName = "SdsRequest";
String externalSource = ims.configuration.EnvironmentConfig.getImportExportSourceName();
ims.configuration.ImportedObject impObj = (ims.configuration.ImportedObject)domMap.get(keyClassName + "_" + externalSource + "_" + this.getId());
if (impObj == null)
{
impObj = new ims.configuration.ImportedObject();
impObj.setExternalId(this.getId());
impObj.setExternalSource(externalSource);
impObj.setDomainObject(this);
impObj.setLocalId(this.getId());
impObj.setClassName(keyClassName);
domMap.put(keyClassName + "_" + externalSource + "_" + this.getId(), impObj);
}
return sb.toString();
}
public String fieldsToXMLString(java.util.HashMap domMap)
{
StringBuffer sb = new StringBuffer();
if (this.getReferrerSdsId() != null)
{
sb.append("<referrerSdsId>");
sb.append(ims.framework.utils.StringUtils.encodeXML(this.getReferrerSdsId().toString()));
sb.append("</referrerSdsId>");
}
if (this.getReferrerSdsRoleId() != null)
{
sb.append("<referrerSdsRoleId>");
sb.append(ims.framework.utils.StringUtils.encodeXML(this.getReferrerSdsRoleId().toString()));
sb.append("</referrerSdsRoleId>");
}
if (this.getReferrerSdsOrgId() != null)
{
sb.append("<referrerSdsOrgId>");
sb.append(ims.framework.utils.StringUtils.encodeXML(this.getReferrerSdsOrgId().toString()));
sb.append("</referrerSdsOrgId>");
}
if (this.getDateTimeRequested() != null)
{
sb.append("<dateTimeRequested>");
sb.append(new ims.framework.utils.DateTime(this.getDateTimeRequested()).toString(ims.framework.utils.DateTimeFormat.MILLI));
sb.append("</dateTimeRequested>");
}
if (this.getDateTimeLastChecked() != null)
{
sb.append("<dateTimeLastChecked>");
sb.append(new ims.framework.utils.DateTime(this.getDateTimeLastChecked()).toString(ims.framework.utils.DateTimeFormat.MILLI));
sb.append("</dateTimeLastChecked>");
}
if (this.isActive() != null)
{
sb.append("<active>");
sb.append(ims.framework.utils.StringUtils.encodeXML(this.isActive().toString()));
sb.append("</active>");
}
if (this.getComments() != null)
{
sb.append("<comments>");
sb.append(ims.framework.utils.StringUtils.encodeXML(this.getComments().toString()));
sb.append("</comments>");
}
if (this.getAppointment() != null)
{
sb.append("<appointment>");
sb.append(ims.framework.utils.StringUtils.encodeXML(this.getAppointment().toString()));
sb.append("</appointment>");
}
return sb.toString();
}
public static java.util.List fromListXMLString(org.dom4j.Element el, ims.domain.DomainFactory factory, java.util.List list, java.util.HashMap domMap) throws Exception
{
if (list == null)
list = new java.util.ArrayList();
fillListFromXMLString(list, el, factory, domMap);
return list;
}
public static java.util.Set fromSetXMLString(org.dom4j.Element el, ims.domain.DomainFactory factory, java.util.Set set, java.util.HashMap domMap) throws Exception
{
if (set == null)
set = new java.util.HashSet();
fillSetFromXMLString(set, el, factory, domMap);
return set;
}
private static void fillSetFromXMLString(java.util.Set set, org.dom4j.Element el, ims.domain.DomainFactory factory, java.util.HashMap domMap) throws Exception
{
if (el == null)
return;
java.util.List cl = el.elements("class");
int size = cl.size();
java.util.Set newSet = new java.util.HashSet();
for(int i=0; i<size; i++)
{
org.dom4j.Element itemEl = (org.dom4j.Element)cl.get(i);
SdsRequest domainObject = getSdsRequestfromXML(itemEl, factory, domMap);
if (domainObject == null)
{
continue;
}
//Trying to avoid the hibernate collection being marked as dirty via its public interface methods. (like add)
if (!set.contains(domainObject))
set.add(domainObject);
newSet.add(domainObject);
}
java.util.Set removedSet = new java.util.HashSet();
java.util.Iterator iter = set.iterator();
//Find out which objects need to be removed
while (iter.hasNext())
{
ims.domain.DomainObject o = (ims.domain.DomainObject)iter.next();
if ((o == null || o.getIsRIE() == null || !o.getIsRIE().booleanValue()) && !newSet.contains(o))
{
removedSet.add(o);
}
}
iter = removedSet.iterator();
//Remove the unwanted objects
while (iter.hasNext())
{
set.remove(iter.next());
}
}
private static void fillListFromXMLString(java.util.List list, org.dom4j.Element el, ims.domain.DomainFactory factory, java.util.HashMap domMap) throws Exception
{
if (el == null)
return;
java.util.List cl = el.elements("class");
int size = cl.size();
for(int i=0; i<size; i++)
{
org.dom4j.Element itemEl = (org.dom4j.Element)cl.get(i);
SdsRequest domainObject = getSdsRequestfromXML(itemEl, factory, domMap);
if (domainObject == null)
{
continue;
}
int domIdx = list.indexOf(domainObject);
if (domIdx == -1)
{
list.add(i, domainObject);
}
else if (i != domIdx && i < list.size())
{
Object tmp = list.get(i);
list.set(i, list.get(domIdx));
list.set(domIdx, tmp);
}
}
//Remove all ones in domList where index > voCollection.size() as these should
//now represent the ones removed from the VO collection. No longer referenced.
int i1=list.size();
while (i1 > size)
{
list.remove(i1-1);
i1=list.size();
}
}
public static SdsRequest getSdsRequestfromXML(String xml, ims.domain.DomainFactory factory, java.util.HashMap domMap) throws Exception
{
org.dom4j.Document doc = new org.dom4j.io.SAXReader().read(new org.xml.sax.InputSource(xml));
return getSdsRequestfromXML(doc.getRootElement(), factory, domMap);
}
public static SdsRequest getSdsRequestfromXML(org.dom4j.Element el, ims.domain.DomainFactory factory, java.util.HashMap domMap) throws Exception
{
if (el == null)
return null;
String className = el.attributeValue("type");
if (!SdsRequest.class.getName().equals(className))
{
Class clz = Class.forName(className);
if (!SdsRequest.class.isAssignableFrom(clz))
throw new Exception("Element of type = " + className + " cannot be imported using the SdsRequest class");
String shortClassName = className.substring(className.lastIndexOf(".")+1);
String methodName = "get" + shortClassName + "fromXML";
java.lang.reflect.Method m = clz.getMethod(methodName, new Class[]{org.dom4j.Element.class, ims.domain.DomainFactory.class, java.util.HashMap.class});
return (SdsRequest)m.invoke(null, new Object[]{el, factory, domMap});
}
String impVersion = el.attributeValue("classVersion");
if(!impVersion.equals(SdsRequest.CLASSVERSION))
{
throw new Exception("Incompatible class structure found. Cannot import instance.");
}
SdsRequest ret = null;
int extId = Integer.parseInt(el.attributeValue("id"));
String externalSource = el.attributeValue("source");
ret = (SdsRequest)factory.getImportedDomainObject(SdsRequest.class, externalSource, extId);
if (ret == null)
{
ret = new SdsRequest();
}
String keyClassName = "SdsRequest";
ims.configuration.ImportedObject impObj = (ims.configuration.ImportedObject)domMap.get(keyClassName + "_" + externalSource + "_" + extId);
if (impObj != null)
{
return (SdsRequest)impObj.getDomainObject();
}
else
{
impObj = new ims.configuration.ImportedObject();
impObj.setExternalId(extId);
impObj.setExternalSource(externalSource);
impObj.setDomainObject(ret);
domMap.put(keyClassName + "_" + externalSource + "_" + extId, impObj);
}
fillFieldsfromXML(el, factory, ret, domMap);
return ret;
}
public static void fillFieldsfromXML(org.dom4j.Element el, ims.domain.DomainFactory factory, SdsRequest obj, java.util.HashMap domMap) throws Exception
{
org.dom4j.Element fldEl;
fldEl = el.element("referrerSdsId");
if(fldEl != null)
{
obj.setReferrerSdsId(new String(fldEl.getTextTrim()));
}
fldEl = el.element("referrerSdsRoleId");
if(fldEl != null)
{
obj.setReferrerSdsRoleId(new String(fldEl.getTextTrim()));
}
fldEl = el.element("referrerSdsOrgId");
if(fldEl != null)
{
obj.setReferrerSdsOrgId(new String(fldEl.getTextTrim()));
}
fldEl = el.element("dateTimeRequested");
if(fldEl != null)
{
obj.setDateTimeRequested(new java.text.SimpleDateFormat("yyyyMMddHHmmssSSS").parse(fldEl.getTextTrim()));
}
fldEl = el.element("dateTimeLastChecked");
if(fldEl != null)
{
obj.setDateTimeLastChecked(new java.text.SimpleDateFormat("yyyyMMddHHmmssSSS").parse(fldEl.getTextTrim()));
}
fldEl = el.element("active");
if(fldEl != null)
{
obj.setActive(new Boolean(fldEl.getTextTrim()));
}
fldEl = el.element("comments");
if(fldEl != null)
{
obj.setComments(new String(fldEl.getTextTrim()));
}
fldEl = el.element("appointment");
if(fldEl != null)
{
obj.setAppointment(new Integer(fldEl.getTextTrim()));
}
}
public static String[] getCollectionFields()
{
return new String[]{
};
}
public static class FieldNames
{
public static final String ID = "id";
public static final String ReferrerSdsId = "referrerSdsId";
public static final String ReferrerSdsRoleId = "referrerSdsRoleId";
public static final String ReferrerSdsOrgId = "referrerSdsOrgId";
public static final String DateTimeRequested = "dateTimeRequested";
public static final String DateTimeLastChecked = "dateTimeLastChecked";
public static final String Active = "active";
public static final String Comments = "comments";
public static final String Appointment = "appointment";
}
}
| agpl-3.0 |
open-health-hub/openMAXIMS | openmaxims_workspace/Therapies/src/ims/therapies/forms/adaptations/Logic.java | 15806 | //#############################################################################
//# #
//# Copyright (C) <2014> <IMS MAXIMS> #
//# #
//# This program is free software: you can redistribute it and/or modify #
//# it under the terms of the GNU Affero General Public License as #
//# published by the Free Software Foundation, either version 3 of the #
//# License, or (at your option) any later version. #
//# #
//# This program is distributed in the hope that it will be useful, #
//# but WITHOUT ANY WARRANTY; without even the implied warranty of #
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//# GNU Affero General Public License for more details. #
//# #
//# You should have received a copy of the GNU Affero General Public License #
//# along with this program. If not, see <http://www.gnu.org/licenses/>. #
//# #
//#############################################################################
//#EOH
// This code was generated by Sean Nesbitt using IMS Development Environment (version 1.39 build 2173.29356)
// Copyright (C) 1995-2005 IMS MAXIMS plc. All rights reserved.
package ims.therapies.forms.adaptations;
import ims.framework.Control;
import ims.framework.cn.data.TreeNode;
import ims.framework.enumerations.FormMode;
import ims.framework.exceptions.FormOpenException;
import ims.framework.exceptions.PresentationLogicException;
import ims.therapies.vo.AdaptationsVoCollection;
import ims.therapies.vo.AdaptationsVo;
import ims.domain.exceptions.StaleObjectException;
import ims.spinalinjuries.vo.lookups.Adaptation;
public class Logic extends BaseLogic
{
public void updateControlsState()
{
form.getContextMenus().getLIPNewItem().setText("New");
if (form.getMode().equals(FormMode.EDIT))
{
form.getContextMenus().getLIPNewItem().setVisible(false);
form.getContextMenus().getLIPUpdateItem().setVisible(false);
form.btnUpdate().setVisible(false);
}
else
{
if (form.grdList().getSelectedRowIndex()>=0)
{
form.getContextMenus().getLIPNewItem().setVisible(true);
form.getContextMenus().getLIPUpdateItem().setVisible(true);
if (form.grdList().getSelectedRowIndex()>=0)
form.btnUpdate().setVisible(true);
else
form.btnUpdate().setVisible(false);
}
else
{
form.getContextMenus().getLIPNewItem().setVisible(true);
form.getContextMenus().getLIPUpdateItem().setVisible(false);
form.btnUpdate().setVisible(false);
}
}
}
public void clearInstanceControls()
{
this.form.ctnDetail().comboBoxAdapt1().setValue(null);
this.form.ctnDetail().comboBoxAdapt2().setValue(null);
this.form.ctnDetail().comboBoxFunded().setValue(null);
this.form.ctnDetail().comboBoxLoan().setValue(null);
this.form.ctnDetail().comboBoxSuppliedFor().setValue(null);
this.form.ctnDetail().comboBoxSupplier().setValue(null);
this.form.ctnDetail().dateRequired().setValue(null);
this.form.ctnDetail().dateSupplied().setValue(null);
}
/**
* populates the screen from data returned from domain call
* <p>
* @return void
*/
protected void populateListControl(AdaptationsVoCollection voCollAdaptation)
{
clear();
if (voCollAdaptation != null)
{
GenForm.grdListRow row = null;
GenForm.grdListRow rowChild = null;
AdaptationsVo voAdaptation = null;
AdaptationsVo vogrdAdaptation = null;
for (int i =0; i < voCollAdaptation.size();i++)
{
voAdaptation = voCollAdaptation.get(i);
rowChild = null;
//search for category
for(int j=0;j<form.grdList().getRows().size();j++)
{
vogrdAdaptation = (AdaptationsVo)form.grdList().getRows().get(j).getValue();
if ((vogrdAdaptation != null) && (vogrdAdaptation.getItemCategory().equals(voAdaptation.getItemCategory())))
{
//found category
rowChild = form.grdList().getRows().get(j).getRows().newRow();
break;
}
}
if (rowChild == null)
{
row = form.grdList().getRows().newRow();
if (voAdaptation.getItemCategoryIsNotNull())
row.setColAdaptations(voAdaptation.getItemCategory().getIItemText());
row.setExpanded(true);
row.setSelectable(false);
row.setValue(voAdaptation);
row.setSelectable(false);
rowChild = row.getRows().newRow();
}
rowChild.setColAdaptations(voAdaptation.getItemTypeIsNotNull()?voAdaptation.getItemType().getIItemText():"");
rowChild.setColSupplier(voAdaptation.getSupplier());
rowChild.setColDateRequired(voAdaptation.getDateRequired());
rowChild.setColDateSupplied(voAdaptation.getDateSupplied());
rowChild.setColSuppliedfor(voAdaptation.getSuppliedFor());
rowChild.setColLoan(voAdaptation.getLoan());
rowChild.setColFundedby(voAdaptation.getFundedByIsNotNull()?voAdaptation.getFundedBy().getIItemText():"");
rowChild.setValue(voAdaptation);
rowChild.setSelectable(true);
}
}
}
protected void loadAdaptationCategories()
{
TreeNode[] coll = ims.spinalinjuries.vo.lookups.LookupHelper.getAdaptation(domain.getLookupService()).getRootNodes();
this.form.ctnDetail().comboBoxAdapt1().clear();
if(coll != null)
{
for(int i=0;i<coll.length;i++)
{
Adaptation item = (Adaptation)coll[i];
if(item.isActive())
form.ctnDetail().comboBoxAdapt1().newRow(item, item.getText());
}
}
}
/**
* populates the data to be stored from the screen into local context selected record
* @return void
*/
public AdaptationsVo populateInstanceData()
{
AdaptationsVo voAdaptation = form.getLocalContext().getSelectedRecord();
if (voAdaptation == null)
voAdaptation = new AdaptationsVo();
voAdaptation.setDateRequired(form.ctnDetail().dateRequired().getValue());
voAdaptation.setDateSupplied(form.ctnDetail().dateSupplied().getValue());
voAdaptation.setFundedBy(form.ctnDetail().comboBoxFunded().getValue());
voAdaptation.setItemCategory(form.ctnDetail().comboBoxAdapt1().getValue());
voAdaptation.setItemType(form.ctnDetail().comboBoxAdapt2().getValue());
voAdaptation.setLoan(form.ctnDetail().comboBoxLoan().getValue());
voAdaptation.setSuppliedFor(form.ctnDetail().comboBoxSuppliedFor().getValue());
voAdaptation.setSupplier(form.ctnDetail().comboBoxSupplier().getValue());
if (!voAdaptation.getClinicalContactIsNotNull())
voAdaptation.setClinicalContact(form.getGlobalContext().Core.getCurrentClinicalContact());
return voAdaptation;
}
/**
* displays the Family History record specified by FamilyHistoryVo
* @param voFamHist
*/
public void populateInstanceControl(ims.vo.ValueObject refVo)
{
clearInstanceControls();
if (refVo != null)
{
AdaptationsVo voAdaptation = (AdaptationsVo)refVo;
if (voAdaptation.getItemCategoryIsNotNull())
{
//if (form.ctnDetail().comboBoxAdapt1().size() == 0)
form.ctnDetail().comboBoxAdapt1().newRow(voAdaptation.getItemCategory(),voAdaptation.getItemCategory().toString());
form.ctnDetail().comboBoxAdapt1().setValue(voAdaptation.getItemCategory());
//loadChildAdaptations();
if(voAdaptation.getItemType() != null)
form.ctnDetail().comboBoxAdapt2().newRow(voAdaptation.getItemType(), voAdaptation.getItemType().toString());
form.ctnDetail().comboBoxAdapt2().setValue(voAdaptation.getItemType());
}
else
form.ctnDetail().comboBoxAdapt1().clear();
form.ctnDetail().comboBoxSupplier().setValue(voAdaptation.getSupplierIsNotNull() ? voAdaptation.getSupplier(): null);
form.ctnDetail().dateRequired().setValue(voAdaptation.getDateRequiredIsNotNull() ? voAdaptation.getDateRequired() : null);
form.ctnDetail().dateSupplied().setValue(voAdaptation.getDateSuppliedIsNotNull() ? voAdaptation.getDateSupplied() : null);
form.ctnDetail().comboBoxSuppliedFor().setValue(voAdaptation.getSuppliedForIsNotNull() ? voAdaptation.getSuppliedFor() : null);
form.ctnDetail().comboBoxLoan().setValue(voAdaptation.getLoanIsNotNull() ? voAdaptation.getLoan(): null);
form.ctnDetail().comboBoxFunded().setValue(voAdaptation.getFundedByIsNotNull() ? voAdaptation.getFundedBy(): null);
form.getLocalContext().setSelectedRecord(voAdaptation);
form.grdList().setValue(form.getLocalContext().getSelectedRecord());
form.ctnDetail().setCollapsed(false);
}
}
/**
* checks before allowing an new record to be created
* @return void
*/
public boolean allowNew()
{
return true;
}
/**
* checks before allowing an update
* @return void
*/
public boolean allowUpdate()
{
return (form.getLocalContext().getSelectedRecordIsNotNull());
}
/**
* clear list and instance controls
* @return void
*/
public void clear()
{
form.grdList().getRows().clear();
clearInstanceControls();
}
public boolean save() throws PresentationLogicException
{
AdaptationsVo voAdaptation = populateInstanceData();
//set clinical contact
if (!voAdaptation.getClinicalContactIsNotNull())
voAdaptation.setClinicalContact(form.getGlobalContext().Core.getCurrentClinicalContact());
voAdaptation.setCareContext(form.getGlobalContext().Core.getCurrentCareContext());
//validate Vo
String[] arrErrors = voAdaptation.validate(validateUIRules());
if(arrErrors != null)
{
arrErrors = SearchErrS(arrErrors);
engine.showErrors(arrErrors);
return false;
}
try
{
form.getLocalContext().setSelectedRecord(domain.save(voAdaptation));
}
catch(StaleObjectException e)
{
engine.showMessage(ims.configuration.gen.ConfigFlag.UI.STALE_OBJECT_MESSAGE.getValue());
open();
return false;
}
return true;
}
private String[] SearchErrS(String[] arg)
{
for(int i = 0;i<arg.length;i++)
{
if(arg[i] == "ItemCategory is mandatory")
arg[i] = "Adaptation is mandatory";
}
return arg;
}
/**
*
* @return void
*/
public void initialize() throws FormOpenException
{
if (ims.spinalinjuries.vo.lookups.LookupHelper.getAdaptation(domain.getLookupService()).size() == 0)
throw new FormOpenException("The Adaptation lookup must first be populated before this form can be used. ");
form.getLocalContext().setSelectedRecord(null);
}
public void newInstance() throws PresentationLogicException
{
if (allowNew())
{
// initalise the screen for a new record
form.getLocalContext().setSelectedRecord(new AdaptationsVo());
clearInstanceControls();
loadAdaptationCategories();
form.ctnDetail().setCollapsed(false);
//set the form mode
form.setMode(FormMode.EDIT);
//set any control status specific this form
}
}
/**
* called from context menus and update button for initiating an update
* @return void
*/
public void updateInstance()
{
if (allowUpdate())
{
loadAdaptationCategories();
populateInstanceControl(form.grdList().getValue());
loadChildAdaptations();
form.setMode(FormMode.EDIT);
}
}
public void open() throws PresentationLogicException
{
if (form.getGlobalContext().Core.getCurrentCareContextIsNotNull())
populateListControl(domain.listByCareContext(form.getGlobalContext().Core.getCurrentCareContext()));
//set selection back
if (form.getLocalContext().getSelectedRecordIsNotNull())
{
//need to get timestamp from record retrieved from List call.
GenForm.grdListRow row = form.grdList().getRowByValue(form.getLocalContext().getSelectedRecord());
if (row != null && row.getValue() != null)
{
form.getLocalContext().setSelectedRecord((AdaptationsVo)row.getValue());
form.grdList().setValue(form.getLocalContext().getSelectedRecord());
populateInstanceControl(form.grdList().getValue());
}
else
clearInstanceControls();
updateControlsState();
}
else
form.ctnDetail().setCollapsed(true);
form.setMode(FormMode.VIEW);
}
/*
* @see ims.clinical.forms.familyhistory.Handlers#onFormOpen()
*/
protected void onFormOpen() throws PresentationLogicException
{
initialize();
open();
}
/*
* updates the context menus and other dependant screen controls
* @see ims.clinical.forms.familyhistory.Handlers#onFormModeChanged()
*/
protected void onFormModeChanged()
{
updateControlsState();
}
/*
* @see ims.clinical.forms.familyhistory.Handlers#onGridDetailsSelectionChanged()
*/
protected void onGrdListSelectionChanged() throws ims.framework.exceptions.PresentationLogicException
{
//Display Panel and detail
form.getLocalContext().setSelectedRecord((AdaptationsVo)form.grdList().getValue());
populateInstanceControl(form.grdList().getValue());
updateControlsState();
}
/*
* @see ims.clinical.forms.familyhistory.Handlers#onContextMenuItemClick(int, ims.framework.Control)
*/
protected void onContextMenuItemClick(int menuItemID, Control sender) throws PresentationLogicException
{
if (menuItemID == form.getContextMenus().getLIPNewItem().getID())
newInstance();
else if (menuItemID == form.getContextMenus().getLIPUpdateItem().getID())
updateInstance();
}
protected void onBCancelClick() throws ims.framework.exceptions.PresentationLogicException
{
open();
}
protected void onComboBoxAdapt1ValueChanged() throws ims.framework.exceptions.PresentationLogicException
{
form.ctnDetail().comboBoxAdapt2().clear();
loadChildAdaptations();
}
private void loadChildAdaptations()
{
if (this.form.ctnDetail().comboBoxAdapt1().getValue() == null)
return;
if (this.form.ctnDetail().comboBoxAdapt1().getValue().getChildInstances() != null)
{
for(int x = 0; x < this.form.ctnDetail().comboBoxAdapt1().getValue().getChildInstances().size(); x++)
{
this.form.ctnDetail().comboBoxAdapt2().newRow((Adaptation)this.form.ctnDetail().comboBoxAdapt1().getValue().getChildInstances().get(x),this.form.ctnDetail().comboBoxAdapt1().getValue().getChildInstances().get(x).toString());
}
}
}
/* (non-Javadoc)
* @see ims.therapies.forms.adaptations.Handlers#oncomboBoxAdapt1ValueSet(java.lang.Object)
*/
protected void oncomboBoxAdapt1ValueSet(Object value)
{
this.form.ctnDetail().comboBoxAdapt2().clear();
if (value == null)
return;
if (this.form.ctnDetail().comboBoxAdapt1().getValue().getChildInstances() != null)
{
for(int x = 0; x < this.form.ctnDetail().comboBoxAdapt1().getValue().getChildInstances().size(); x++)
{
this.form.ctnDetail().comboBoxAdapt2().newRow((Adaptation)this.form.ctnDetail().comboBoxAdapt1().getValue().getChildInstances().get(x),this.form.ctnDetail().comboBoxAdapt1().getValue().getChildInstances().get(x).toString());
}
}
}
/*
* @see ims.clinical.forms.familyhistory.Handlers#onBtnSaveClick()
*/
protected void onBtnSaveClick() throws ims.framework.exceptions.PresentationLogicException
{
if (save())
open();
}
/*
* @see ims.clinical.forms.familyhistory.Handlers#onBtnCancelClick()
*/
protected void onBtnCancelClick() throws ims.framework.exceptions.PresentationLogicException
{
open();
}
/*
* @see ims.clinical.forms.familyhistory.Handlers#onBtnUpdateClick()
*/
protected void onBtnUpdateClick() throws PresentationLogicException
{
updateInstance();
}
/*
* @see ims.clinical.forms.familyhistory.Handlers#onBtnNewClick()
*/
protected void onBtnNewClick() throws PresentationLogicException
{
newInstance();
}
}
| agpl-3.0 |
open-health-hub/openMAXIMS | openmaxims_workspace/Nursing/src/ims/nursing/forms/skinreviewdialog/Logic.java | 17502 | //#############################################################################
//# #
//# Copyright (C) <2014> <IMS MAXIMS> #
//# #
//# This program is free software: you can redistribute it and/or modify #
//# it under the terms of the GNU Affero General Public License as #
//# published by the Free Software Foundation, either version 3 of the #
//# License, or (at your option) any later version. #
//# #
//# This program is distributed in the hope that it will be useful, #
//# but WITHOUT ANY WARRANTY; without even the implied warranty of #
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//# GNU Affero General Public License for more details. #
//# #
//# You should have received a copy of the GNU Affero General Public License #
//# along with this program. If not, see <http://www.gnu.org/licenses/>. #
//# #
//#############################################################################
//#EOH
// This code was generated by Callum Wells using IMS Development Environment (version 1.20 build 40805.900)
// Copyright (C) 1995-2004 IMS MAXIMS plc. All rights reserved.
package ims.nursing.forms.skinreviewdialog;
import ims.nursing.vo.SkinAssessment;
import ims.nursing.vo.SkinAssessmentFindings;
import ims.nursing.vo.SkinAssessmentReview;
import ims.framework.enumerations.DialogResult;
import ims.framework.utils.DateTime;
import ims.nursing.vo.lookups.SkinWoundType;
public class Logic extends BaseLogic
{
protected void onFormOpen() throws ims.framework.exceptions.FormOpenException
{
if(screenOpenedFromReview())
{
//set the details from SkinReview
populateControlsFromReviewVO();
}
else
{
//set the details from SkinChart
populateControlsFromFindingVO();
form.checkBoxDiscontinueAssessment().setVisible(false);
form.labelDiscontinue().setVisible(false);
}
}
protected void onBCancelClick() throws ims.framework.exceptions.PresentationLogicException
{
clearGlobalContext();
engine.close(DialogResult.CANCEL);
}
protected void onBSaveClick() throws ims.framework.exceptions.PresentationLogicException
{
boolean closeDialog = false;
if ((form.grpInfection().getValue() != null && form.grpInfection().getValue().equals(GenForm.grpInfectionEnumeration.radioButtonInfectionYes)) && (form.grpSwab().getValue() != null && !form.grpSwab().getValue().equals(GenForm.grpSwabEnumeration.radioButtonSwabYes)))
{
engine.showMessage("If an infection is suspected, 'Swab Taken' must be set to Yes "); //wdev-12411
return;
}
if ((form.grpInfection().getValue() != null && form.grpInfection().getValue().equals(GenForm.grpInfectionEnumeration.radioButtonInfectionYes)) && (form.grpTraced().getValue() != null && !form.grpTraced().getValue().equals(GenForm.grpTracedEnumeration.radioButtonTracedYes)))
{
engine.showMessage("If an infection is suspected, 'Wound Traced' must be set to Yes ");
return;
}
if(screenOpenedFromReview())
closeDialog = populateReviewVO();
else
closeDialog = populateFindingVO();
if(closeDialog)
{
clearGlobalContext();
engine.close(DialogResult.OK);
}
}
private void clearGlobalContext()
{
form.getGlobalContext().COE.SkinBodyChart.setReviewDialog(new Boolean(false));
}
private void populateControlsFromFindingVO()
{
SkinAssessmentFindings findingVO = form.getGlobalContext().COE.SkinBodyChart.getFindingsVO();
SkinAssessment skinAssessment = form.getGlobalContext().COE.SkinBodyChart.getSelectedSkinAssessment();
if(skinAssessment != null)
{
//Date/Time
if(skinAssessment.getDateTimeInitiated() != null)
{
form.dteReviewDate().setValue(skinAssessment.getDateTimeInitiated().getDate());
form.timReviewTime().setValue(skinAssessment.getDateTimeInitiated().getTime());
}
//HCP
if(skinAssessment.getHcpInitiated() != null)
form.txtHCP().setValue(skinAssessment.getHcpInitiated().toString());
}
//Finding
if(findingVO.getWoundType() != null)
form.txtFinding().setValue(findingVO.getWoundType().getText());
//Site
form.textBoxSite().setValue(findingVO.getSiteName());
//Site Details
form.textBoxSiteDetails().setValue(findingVO.getSiteDetails());
//How Long
form.textBoxHowLong().setValue(findingVO.getHowLongIsItPresent());
//Pressure Sore Grade - display when we have the Wound Type - Pressure Sore
if(findingVO.getWoundType() != null && findingVO.getWoundType().equals(SkinWoundType.PRESSURESORE))
form.cmbPressureGrade().setValue(findingVO.getPressureSoreGrade());
else
setVisiblePressureSore(false);
//Length
form.decBoxLength().setValue(findingVO.getLength());
//Width
form.decBoxWidth().setValue(findingVO.getWidth());
//Depth
form.decBoxDepth().setValue(findingVO.getDepth());
//Wound Bed
form.cmbWoundBed().setValue(findingVO.getWoundBed());
//Surrounding Skin
form.cmbSurroundingSkin().setValue(findingVO.getSurroundingSkin());
//Exudate Amount
form.cmbExudateAmount().setValue(findingVO.getExudateAmount());
//Exudate Type
form.cmbExudateType().setValue(findingVO.getExudateType());
//Odour
form.cmbOdour().setValue(findingVO.getOdour());
//Pain
form.cmbPain().setValue(findingVO.getPain());
//Infection Suspected
if(findingVO.getInfectionSuspected() != null)
{
if(findingVO.getInfectionSuspected().booleanValue())
form.grpInfection().setValue(GenForm.grpInfectionEnumeration.radioButtonInfectionYes);
else
form.grpInfection().setValue(GenForm.grpInfectionEnumeration.radioButtonInfectionNo);
}
//Swab taken
if(findingVO.getSwabTaken() != null)
{
if(findingVO.getSwabTaken().booleanValue())
form.grpSwab().setValue(GenForm.grpSwabEnumeration.radioButtonSwabYes);
else
form.grpSwab().setValue(GenForm.grpSwabEnumeration.radioButtonSwabNo);
}
//Wound Traced
if(findingVO.getWoundTraced() != null)
{
if(findingVO.getWoundTraced().booleanValue())
form.grpTraced().setValue(GenForm.grpTracedEnumeration.radioButtonTracedYes);
else
form.grpTraced().setValue(GenForm.grpTracedEnumeration.radioButtonTracedNo);
}
//Cleansed With
form.cmbCleansedWith().setValue(findingVO.getCleansedWith());
//Primary Dressing
form.cmbPrimary().setValue(findingVO.getPrimaryDressing());
//Secondary Dressing
form.cmbSecondary().setValue(findingVO.getSecondaryDressing());
//Frequency of Change
form.cmbFrequency().setValue(findingVO.getFrequencyOfChange());
//Comment
form.textBoxComment().setValue(findingVO.getComment());
//Discontinue
if(findingVO.getIsDiscontinuedAssess() != null && findingVO.getIsDiscontinuedAssess().booleanValue())
form.checkBoxDiscontinueAssessment().setValue(true);
}
private void populateControlsFromReviewVO()
{
SkinAssessmentFindings findingVO = form.getGlobalContext().COE.SkinBodyChart.getFindingsVO();
SkinAssessmentReview reviewVO = form.getGlobalContext().COE.SkinBodyChart.getReviewVO();
//Populated from findingVO---------------------------------------
//Date/Time
if(reviewVO.getDateTimeReview() != null)
{
form.dteReviewDate().setValue(reviewVO.getDateTimeReview().getDate());
form.timReviewTime().setValue(reviewVO.getDateTimeReview().getTime());
}
//HCP
if(reviewVO.getHCPReview() != null)
form.txtHCP().setValue(reviewVO.getHCPReview().toString());
//Finding
if(findingVO.getWoundType() != null)
form.txtFinding().setValue(findingVO.getWoundType().getText());
//Site
form.textBoxSite().setValue(findingVO.getSiteName());
//Discontinue
if(findingVO.getIsDiscontinuedAssess() != null && findingVO.getIsDiscontinuedAssess().booleanValue())
form.checkBoxDiscontinueAssessment().setValue(true);
//How Long
setVisibleHowLongPresent(false);
//form.textBoxHowLong().setValue(findingVO.getHowLongIsItPresent());
//---------------------------------------------------------------
//Site Details
form.textBoxSiteDetails().setValue(reviewVO.getSiteDetails());
//Pressure Sore Grade - display when we have the Wound Type - Pressure Sore
if(findingVO.getWoundType() != null && findingVO.getWoundType().equals(SkinWoundType.PRESSURESORE))
form.cmbPressureGrade().setValue(reviewVO.getPressureSoreGrade());
else
setVisiblePressureSore(false);
//Length
form.decBoxLength().setValue(reviewVO.getLength());
//Width
form.decBoxWidth().setValue(reviewVO.getWidth());
//Depth
form.decBoxDepth().setValue(reviewVO.getDepth());
//Wound Bed
form.cmbWoundBed().setValue(reviewVO.getWoundBed());
//Surrounding Skin
form.cmbSurroundingSkin().setValue(reviewVO.getSurroundingSkin());
//Exudate Amount
form.cmbExudateAmount().setValue(reviewVO.getExudateAmount());
//Exudate Type
form.cmbExudateType().setValue(reviewVO.getExudateType());
//Odour
form.cmbOdour().setValue(reviewVO.getOdour());
//Pain
form.cmbPain().setValue(reviewVO.getPain());
//Infection Suspected
if(reviewVO.getInfectionSuspected() != null)
{
if(reviewVO.getInfectionSuspected().booleanValue())
form.grpInfection().setValue(GenForm.grpInfectionEnumeration.radioButtonInfectionYes);
else
form.grpInfection().setValue(GenForm.grpInfectionEnumeration.radioButtonInfectionNo);
}
//Swab taken
if(reviewVO.getSwabTaken() != null)
{
if(reviewVO.getSwabTaken().booleanValue())
form.grpSwab().setValue(GenForm.grpSwabEnumeration.radioButtonSwabYes);
else
form.grpSwab().setValue(GenForm.grpSwabEnumeration.radioButtonSwabNo);
}
//Wound Traced
if(reviewVO.getWoundTraced() != null)
{
if(reviewVO.getWoundTraced().booleanValue())
form.grpTraced().setValue(GenForm.grpTracedEnumeration.radioButtonTracedYes);
else
form.grpTraced().setValue(GenForm.grpTracedEnumeration.radioButtonTracedNo);
}
//Cleansed With
form.cmbCleansedWith().setValue(reviewVO.getCleansedWith());
//Primary Dressing
form.cmbPrimary().setValue(reviewVO.getPrimaryDressing());
//Secondary Dressing
form.cmbSecondary().setValue(reviewVO.getSecondaryDressing());
//Frequency of Change
form.cmbFrequency().setValue(reviewVO.getFrequencyOfChange());
//Comment
form.textBoxComment().setValue(reviewVO.getComment());
}
public boolean populateReviewVO()
{
// Do extra checking if necessary...
SkinAssessmentFindings findingVO = form.getGlobalContext().COE.SkinBodyChart.getFindingsVO();
SkinAssessmentReview reviewVO = form.getGlobalContext().COE.SkinBodyChart.getReviewVO();
//Date & Time
if(form.dteReviewDate().getValue() == null)
{
engine.showMessage("Please enter a Date");
return false;
}
if(form.timReviewTime().getValue() == null)
{
engine.showMessage("Please enter a Time");
return false;
}
reviewVO.setDateTimeReview(new DateTime(form.dteReviewDate().getValue(), form.timReviewTime().getValue()));
//Site Details
reviewVO.setSiteDetails(form.textBoxSiteDetails().getValue());
//How Long - now the attribute is in findingVO
//reviewVO.setHowLongIsItPresent(form.textBoxHowLong().getValue());
//Pressure Sore Grade
reviewVO.setPressureSoreGrade(form.cmbPressureGrade().getValue());
//Length
reviewVO.setLength(form.decBoxLength().getValue());
//Width
reviewVO.setWidth(form.decBoxWidth().getValue());
//Depth
reviewVO.setDepth(form.decBoxDepth().getValue());
//Wound Bed
reviewVO.setWoundBed(form.cmbWoundBed().getValue());
//Surrounding Skin
reviewVO.setSurroundingSkin(form.cmbSurroundingSkin().getValue());
//Exudate Amount
reviewVO.setExudateAmount(form.cmbExudateAmount().getValue());
//Exudate Type
reviewVO.setExudateType(form.cmbExudateType().getValue());
//Odour
reviewVO.setOdour(form.cmbOdour().getValue());
//Pain
reviewVO.setPain(form.cmbPain().getValue());
//Infection Suspected
if(form.grpInfection().getValue() != null)
{
if(form.grpInfection().getValue().equals(GenForm.grpInfectionEnumeration.radioButtonInfectionYes))
reviewVO.setInfectionSuspected(new Boolean(true));
else if(form.grpInfection().getValue().equals(GenForm.grpInfectionEnumeration.radioButtonInfectionNo))
reviewVO.setInfectionSuspected(new Boolean(false));
}
//Swab taken
if(form.grpSwab().getValue() != null)
{
if(form.grpSwab().getValue().equals(GenForm.grpSwabEnumeration.radioButtonSwabYes))
reviewVO.setSwabTaken(new Boolean(true));
else if (form.grpSwab().getValue().equals(GenForm.grpSwabEnumeration.radioButtonSwabNo))
reviewVO.setSwabTaken(new Boolean(false));
}
//Wound Traced
if(form.grpTraced() != null)
{
if(form.grpTraced().getValue().equals(GenForm.grpTracedEnumeration.radioButtonTracedYes))
reviewVO.setWoundTraced(new Boolean(true));
if(form.grpTraced().getValue().equals(GenForm.grpTracedEnumeration.radioButtonTracedNo))
reviewVO.setWoundTraced(new Boolean(false));
}
//Cleansed With
reviewVO.setCleansedWith(form.cmbCleansedWith().getValue());
//Primary Dressing
reviewVO.setPrimaryDressing(form.cmbPrimary().getValue());
//Secondary Dressing
reviewVO.setSecondaryDressing(form.cmbSecondary().getValue());
//Frequency of Change
reviewVO.setFrequencyOfChange(form.cmbFrequency().getValue());
//Comment
reviewVO.setComment(form.textBoxComment().getValue());
//Discontinue
if(form.checkBoxDiscontinueAssessment().getValue())
findingVO.setIsDiscontinuedAssess(new Boolean (true));
else
findingVO.setIsDiscontinuedAssess(new Boolean (false));
//Set the VO back to the context
form.getGlobalContext().COE.SkinBodyChart.setFindingsVO(findingVO);
form.getGlobalContext().COE.SkinBodyChart.setReviewVO(reviewVO);
return true;
}
public boolean populateFindingVO()
{
//Do extra checking if necessary
SkinAssessmentFindings findingVO = form.getGlobalContext().COE.SkinBodyChart.getFindingsVO();
//Site Details
findingVO.setSiteDetails(form.textBoxSiteDetails().getValue());
//How Long
findingVO.setHowLongIsItPresent(form.textBoxHowLong().getValue());
//Pressure Sore Grade
findingVO.setPressureSoreGrade(form.cmbPressureGrade().getValue());
//Length
findingVO.setLength(form.decBoxLength().getValue());
//Width
findingVO.setWidth(form.decBoxWidth().getValue());
//Depth
findingVO.setDepth(form.decBoxDepth().getValue());
//Wound Bed
findingVO.setWoundBed(form.cmbWoundBed().getValue());
//Surrounding Skin
findingVO.setSurroundingSkin(form.cmbSurroundingSkin().getValue());
//Exudate Amount
findingVO.setExudateAmount(form.cmbExudateAmount().getValue());
//Exudate Type
findingVO.setExudateType(form.cmbExudateType().getValue());
//Odour
findingVO.setOdour(form.cmbOdour().getValue());
//Pain
findingVO.setPain(form.cmbPain().getValue());
//Infection Suspected
if(form.grpInfection().getValue() != null)
{
if(form.grpInfection().getValue().equals(GenForm.grpInfectionEnumeration.radioButtonInfectionYes))
findingVO.setInfectionSuspected(new Boolean(true));
else if(form.grpInfection().getValue().equals(GenForm.grpInfectionEnumeration.radioButtonInfectionNo))
findingVO.setInfectionSuspected(new Boolean(false));
}
//Swab taken
if(form.grpSwab().getValue() != null)
{
if(form.grpSwab().getValue().equals(GenForm.grpSwabEnumeration.radioButtonSwabYes))
findingVO.setSwabTaken(new Boolean(true));
else if (form.grpSwab().getValue().equals(GenForm.grpSwabEnumeration.radioButtonSwabNo))
findingVO.setSwabTaken(new Boolean(false));
}
//Wound Traced
if(form.grpTraced() != null)
{
if(form.grpTraced().getValue().equals(GenForm.grpTracedEnumeration.radioButtonTracedYes))
findingVO.setWoundTraced(new Boolean(true));
if(form.grpTraced().getValue().equals(GenForm.grpTracedEnumeration.radioButtonTracedNo))
findingVO.setWoundTraced(new Boolean(false));
}
//Cleansed With
findingVO.setCleansedWith(form.cmbCleansedWith().getValue());
//Primary Dressing
findingVO.setPrimaryDressing(form.cmbPrimary().getValue());
//Secondary Dressing
findingVO.setSecondaryDressing(form.cmbSecondary().getValue());
//Frequency of Change
findingVO.setFrequencyOfChange(form.cmbFrequency().getValue());
//Comment
findingVO.setComment(form.textBoxComment().getValue());
//Discontinue
if(form.checkBoxDiscontinueAssessment().getValue())
findingVO.setIsDiscontinuedAssess(new Boolean (true));
else
findingVO.setIsDiscontinuedAssess(new Boolean (false));
//Set the VO back to the context
form.getGlobalContext().COE.SkinBodyChart.setFindingsVO(findingVO);
return true;
}
private boolean screenOpenedFromReview()
{
if(form.getGlobalContext().COE.SkinBodyChart.getReviewDialog() != null &&
form.getGlobalContext().COE.SkinBodyChart.getReviewDialog().booleanValue())
return true;
return false;
}
private void setVisiblePressureSore(boolean bValue)
{
form.labelPressureSore().setVisible(bValue);
form.cmbPressureGrade().setVisible(bValue);
}
private void setVisibleHowLongPresent(boolean bValue)
{
form.textBoxHowLong().setVisible(bValue);
form.labelHowLongPresent().setVisible(bValue);
}
}
| agpl-3.0 |
wesley1001/orbeon-forms | src/main/java/org/orbeon/oxf/transformer/xupdate/statement/Choose.java | 2318 | /**
* Copyright (C) 2010 Orbeon, Inc.
*
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU Lesser General Public License as published by the Free Software Foundation; either version
* 2.1 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* The full text of the license is available at http://www.gnu.org/copyleft/lesser.html
*/
package org.orbeon.oxf.transformer.xupdate.statement;
import org.jaxen.NamespaceContext;
import org.orbeon.oxf.transformer.xupdate.*;
import org.orbeon.oxf.xml.dom4j.LocationData;
import javax.xml.transform.URIResolver;
import java.util.Collections;
public class Choose extends Statement {
private String[] tests;
private NamespaceContext[] namespaceContexts;
private Statement[][] statements;
private Statement[] otherwise;
public Choose(LocationData locationData, String[] tests, NamespaceContext[] namespaceContexts,
Statement[][] statements, Statement[] otherwise) {
super(locationData);
this.tests = tests;
this.namespaceContexts = namespaceContexts;
this.statements = statements;
this.otherwise = otherwise;
}
public Object execute(URIResolver uriResolver, Object context, VariableContextImpl variableContext, DocumentContext documentContext) {
// Evaluate successive tests
for (int i = 0; i < tests.length; i++) {
Boolean success = (Boolean) Utils.evaluate(uriResolver, context,
variableContext, documentContext, getLocationData(), "boolean(" + tests[i] + ")", namespaceContexts[i]);
if (success.booleanValue()) {
return Utils.execute(uriResolver, context, variableContext, documentContext, statements[i]);
}
}
// If everything fails, evaluate otherwise
if (otherwise != null) {
return Utils.execute(uriResolver, context, variableContext, documentContext, otherwise);
} else {
return Collections.EMPTY_LIST;
}
}
}
| lgpl-2.1 |
anddann/soot | tutorial/guide/examples/intermediate_representation/src/dk/brics/soot/intermediate/representation/SomeMethodCall.java | 281 | package dk.brics.soot.intermediate.representation;
public class SomeMethodCall extends MethodCall {
public SomeMethodCall(Method target, Variable[] args) {
super(target, args);
}
@Override
public <T> T process(StatementProcessor<T> v) {
return v.dispatch(this);
}
}
| lgpl-2.1 |
yersan/wildfly-core | jmx/src/main/java/org/jboss/as/jmx/model/ResourceAccessControlUtil.java | 6437 | /*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.jmx.model;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ACCESS_CONTROL;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ADDRESS;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ATTRIBUTES;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.DEFAULT;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.EXCEPTIONS;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.EXECUTE;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.INHERITED;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OPERATIONS;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OUTCOME;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.READ;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.READ_RESOURCE_DESCRIPTION_OPERATION;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.RESULT;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUCCESS;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.WRITE;
import javax.management.InstanceNotFoundException;
import javax.management.ObjectName;
import org.jboss.as.controller.ModelController;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.operations.common.Util;
import org.jboss.as.controller.operations.global.ReadResourceDescriptionHandler;
import org.jboss.as.jmx.logging.JmxLogger;
import org.jboss.dmr.ModelNode;
/**
*
* @author <a href="kabir.khan@jboss.com">Kabir Khan</a>
*/
class ResourceAccessControlUtil {
private static final ResourceAccessControl NOT_ADDRESSABLE;
static {
ModelNode notAddressable = new ModelNode();
notAddressable.get(ADDRESS).set(false);
notAddressable.protect();
NOT_ADDRESSABLE = new ResourceAccessControl(notAddressable);
}
private final ModelController controller;
ResourceAccessControlUtil(ModelController controller) {
this.controller = controller;
}
ResourceAccessControl getResourceAccessWithInstanceNotFoundExceptionIfNotAccessible(ObjectName name, PathAddress address, boolean operations) throws InstanceNotFoundException {
ResourceAccessControl accessControl = getResourceAccess(address, operations);
if (!accessControl.isAccessibleResource()) {
throw JmxLogger.ROOT_LOGGER.mbeanNotFound(name);
}
return accessControl;
}
ResourceAccessControl getResourceAccess(PathAddress address, boolean operations) {
ModelNode op = Util.createOperation(READ_RESOURCE_DESCRIPTION_OPERATION, address);
op.get(ACCESS_CONTROL).set(ReadResourceDescriptionHandler.AccessControl.TRIM_DESCRIPTONS.toModelNode());
if (operations) {
op.get(OPERATIONS).set(true);
op.get(INHERITED).set(false);
}
ModelNode result = controller.execute(op, null, ModelController.OperationTransactionControl.COMMIT, null);
if (!result.get(OUTCOME).asString().equals(SUCCESS)) {
return NOT_ADDRESSABLE;
} else {
final ModelNode accessControl = result.get(RESULT, ACCESS_CONTROL);
ModelNode useAccessControl = null;
if (accessControl.hasDefined(EXCEPTIONS) && !accessControl.get(EXCEPTIONS).keys().isEmpty()) {
String key = address.toModelNode().asString();
ModelNode exception = accessControl.get(EXCEPTIONS, key);
if (exception.isDefined()) {
useAccessControl = exception;
}
}
if (useAccessControl == null) {
useAccessControl = accessControl.get(DEFAULT);
}
return new ResourceAccessControl(useAccessControl);
}
}
static class ResourceAccessControl {
private final ModelNode accessControl;
ResourceAccessControl(ModelNode modelNode){
this.accessControl = modelNode;
}
boolean isAccessibleResource() {
if (accessControl.hasDefined(ADDRESS) && !accessControl.get(ADDRESS).asBoolean()) {
return false;
}
return true;
}
public boolean isReadableAttribute(String attribute) {
ModelNode node = accessControl.get(ATTRIBUTES, attribute, READ);
if (!node.isDefined()) {
//Should not happen but return false just in case
return false;
}
return node.asBoolean();
}
public boolean isWritableAttribute(String attribute) {
ModelNode node = accessControl.get(ATTRIBUTES, attribute, WRITE);
if (!node.isDefined()) {
//Should not happen but return false just in case
return false;
}
return node.asBoolean();
}
public boolean isExecutableOperation(String operation) {
ModelNode node = accessControl.get(OPERATIONS, operation, EXECUTE);
if (!node.isDefined()) {
//Should not happen but return false just in case
return false;
}
return node.asBoolean();
}
}
}
| lgpl-2.1 |
alienth/opentsdb | test/query/expression/TestAlias.java | 11248 | // This file is part of OpenTSDB.
// Copyright (C) 2015 The OpenTSDB Authors.
//
// This program is free software: you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 2.1 of the License, or (at your
// option) any later version. This program is distributed in the hope that it
// will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser
// General Public License for more details. You should have received a copy
// of the GNU Lesser General Public License along with this program. If not,
// see <http://www.gnu.org/licenses/>.
package net.opentsdb.query.expression;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.opentsdb.core.DataPoint;
import net.opentsdb.core.DataPoints;
import net.opentsdb.core.SeekableView;
import net.opentsdb.core.SeekableViewsForTest;
import net.opentsdb.core.TSQuery;
import org.hbase.async.Bytes.ByteMap;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import com.stumbleupon.async.Deferred;
@RunWith(PowerMockRunner.class)
@PowerMockIgnore({"javax.management.*", "javax.xml.*",
"ch.qos.*", "org.slf4j.*",
"com.sum.*", "org.xml.*"})
@PrepareForTest({ TSQuery.class })
public class TestAlias {
private static long START_TIME = 1356998400000L;
private static int INTERVAL = 60000;
private static int NUM_POINTS = 5;
private static String METRIC = "sys.cpu";
private TSQuery data_query;
private SeekableView view;
private DataPoints dps;
private DataPoints[] group_bys;
private List<DataPoints[]> query_results;
private List<String> params;
private Alias func;
private Map<String, String> tags;
private ByteMap<byte[]> tag_uids;
@Before
public void before() throws Exception {
view = SeekableViewsForTest.generator(START_TIME, INTERVAL,
NUM_POINTS, true, 1, 1);
data_query = mock(TSQuery.class);
when(data_query.startTime()).thenReturn(START_TIME);
when(data_query.endTime()).thenReturn(START_TIME + (INTERVAL * NUM_POINTS));
tags = new HashMap<String, String>(2);
tags.put("host", "web01");
tags.put("dc", "lga");
tag_uids = new ByteMap<byte[]>();
tag_uids.put(new byte[] { 0, 0, 1 }, new byte[] { 0, 0, 1 });
tag_uids.put(new byte[] { 0, 0, 2 }, new byte[] { 0, 0, 2 });
dps = PowerMockito.mock(DataPoints.class);
when(dps.iterator()).thenReturn(view);
when(dps.metricName()).thenReturn(METRIC);
when(dps.getTagsAsync()).thenReturn(Deferred.fromResult(tags));
when(dps.getTagUids()).thenReturn(tag_uids);
group_bys = new DataPoints[] { dps };
query_results = new ArrayList<DataPoints[]>(1);
query_results.add(group_bys);
params = new ArrayList<String>(1);
func = new Alias();
}
@Test
public void evaluateGroupByLong() throws Exception {
SeekableView view2 = SeekableViewsForTest.generator(START_TIME, INTERVAL,
NUM_POINTS, true, 10, 1);
DataPoints dps2 = PowerMockito.mock(DataPoints.class);
when(dps2.iterator()).thenReturn(view2);
when(dps2.metricName()).thenReturn("sys.mem");
group_bys = new DataPoints[] { dps, dps2 };
query_results.clear();
query_results.add(group_bys);
params.add("My Alias");
final DataPoints[] results = func.evaluate(data_query, query_results, params);
assertEquals(2, results.length);
assertEquals("My Alias", results[0].metricName());
assertEquals("My Alias", results[1].metricName());
long ts = START_TIME;
long v = 1;
for (DataPoint dp : results[0]) {
assertEquals(ts, dp.timestamp());
assertTrue(dp.isInteger());
assertEquals(v, dp.longValue());
ts += INTERVAL;
v += 1;
}
ts = START_TIME;
v = 10;
for (DataPoint dp : results[1]) {
assertEquals(ts, dp.timestamp());
assertTrue(dp.isInteger());
assertEquals(v, dp.longValue());
ts += INTERVAL;
v += 1;
}
}
@Test
public void evaluateGroupByDouble() throws Exception {
SeekableView view2 = SeekableViewsForTest.generator(START_TIME, INTERVAL,
NUM_POINTS, false, 10, 1);
DataPoints dps2 = PowerMockito.mock(DataPoints.class);
when(dps2.iterator()).thenReturn(view2);
when(dps2.metricName()).thenReturn("sys.mem");
group_bys = new DataPoints[] { dps, dps2 };
query_results.clear();
query_results.add(group_bys);
params.add("My Alias");
final DataPoints[] results = func.evaluate(data_query, query_results, params);
assertEquals(2, results.length);
assertEquals("My Alias", results[0].metricName());
assertEquals("My Alias", results[1].metricName());
long ts = START_TIME;
double v = 1;
for (DataPoint dp : results[0]) {
assertEquals(ts, dp.timestamp());
assertTrue(dp.isInteger());
assertEquals((long)v, dp.longValue());
ts += INTERVAL;
v += 1;
}
ts = START_TIME;
v = 10;
for (DataPoint dp : results[1]) {
assertEquals(ts, dp.timestamp());
assertFalse(dp.isInteger());
assertEquals(v, dp.doubleValue(), 0.001);
ts += INTERVAL;
v += 1;
}
}
@Test
public void evaluateSubQuerySeries() throws Exception {
SeekableView view2 = SeekableViewsForTest.generator(START_TIME, INTERVAL,
NUM_POINTS, true, -10, -1);
DataPoints dps2 = PowerMockito.mock(DataPoints.class);
when(dps2.iterator()).thenReturn(view2);
when(dps2.metricName()).thenReturn("sys.mem");
group_bys = new DataPoints[] { dps, dps2 };
query_results.clear();
query_results.add(group_bys);
params.add("My Alias");
final DataPoints[] results = func.evaluate(data_query, query_results, params);
assertEquals(2, results.length);
assertEquals("My Alias", results[0].metricName());
assertEquals("My Alias", results[1].metricName());
long ts = START_TIME;
long v = 1;
for (DataPoint dp : results[0]) {
assertEquals(ts, dp.timestamp());
assertTrue(dp.isInteger());
assertEquals(v, dp.longValue());
ts += INTERVAL;
v += 1;
}
ts = START_TIME;
v = 10;
for (DataPoint dp : results[1]) {
assertEquals(ts, dp.timestamp());
assertTrue(dp.isInteger());
assertEquals(v, dp.longValue());
ts += INTERVAL;
v += 1;
}
}
@Test
public void evaluateWithTags() throws Exception {
SeekableView view2 = SeekableViewsForTest.generator(START_TIME, INTERVAL,
NUM_POINTS, true, 10, 1);
DataPoints dps2 = PowerMockito.mock(DataPoints.class);
when(dps2.iterator()).thenReturn(view2);
when(dps2.metricName()).thenReturn("sys.mem");
when(dps2.getTagsAsync()).thenReturn(Deferred.fromResult(tags));
when(dps2.getTagUids()).thenReturn(tag_uids);
group_bys = new DataPoints[] { dps, dps2 };
query_results.clear();
query_results.add(group_bys);
params.add("My Alias.@host.@dc");
final DataPoints[] results = func.evaluate(data_query, query_results, params);
assertEquals(2, results.length);
assertEquals("My Alias.web01.lga", results[0].metricName());
assertEquals("My Alias.web01.lga", results[1].metricName());
}
@Test
public void evaluateWithATag() throws Exception {
SeekableView view2 = SeekableViewsForTest.generator(START_TIME, INTERVAL,
NUM_POINTS, true, 10, 1);
DataPoints dps2 = PowerMockito.mock(DataPoints.class);
when(dps2.iterator()).thenReturn(view2);
when(dps2.metricName()).thenReturn("sys.mem");
when(dps2.getTagsAsync()).thenReturn(Deferred.fromResult(tags));
when(dps2.getTagUids()).thenReturn(tag_uids);
group_bys = new DataPoints[] { dps, dps2 };
query_results.clear();
query_results.add(group_bys);
params.add("My Alias.@dc");
final DataPoints[] results = func.evaluate(data_query, query_results, params);
assertEquals(2, results.length);
assertEquals("My Alias.lga", results[0].metricName());
assertEquals("My Alias.lga", results[1].metricName());
}
@Test
public void evaluateWithTagsJoined() throws Exception {
SeekableView view2 = SeekableViewsForTest.generator(START_TIME, INTERVAL,
NUM_POINTS, true, 10, 1);
DataPoints dps2 = PowerMockito.mock(DataPoints.class);
when(dps2.iterator()).thenReturn(view2);
when(dps2.metricName()).thenReturn("sys.mem");
when(dps2.getTagsAsync()).thenReturn(Deferred.fromResult(tags));
when(dps2.getTagUids()).thenReturn(tag_uids);
group_bys = new DataPoints[] { dps, dps2 };
query_results.clear();
query_results.add(group_bys);
params.add("My Alias");
params.add("@host");
params.add("@dc");
params.add("@none");
final DataPoints[] results = func.evaluate(data_query, query_results, params);
assertEquals(2, results.length);
assertEquals("My Alias,web01,lga,@none", results[0].metricName());
assertEquals("My Alias,web01,lga,@none", results[1].metricName());
}
@Test (expected = IllegalArgumentException.class)
public void evaluateNullQuery() throws Exception {
params.add("1");
func.evaluate(null, query_results, params);
}
@Test
public void evaluateNullResults() throws Exception {
params.add("1");
final DataPoints[] results = func.evaluate(data_query, null, params);
assertEquals(0, results.length);
}
@Test (expected = IllegalArgumentException.class)
public void evaluateNullParams() throws Exception {
func.evaluate(data_query, query_results, null);
}
@Test
public void evaluateEmptyResults() throws Exception {
final DataPoints[] results = func.evaluate(data_query,
Collections.<DataPoints[]>emptyList(), params);
assertEquals(0, results.length);
}
@Test (expected = IllegalArgumentException.class)
public void evaluateEmptyParams() throws Exception {
func.evaluate(data_query, query_results, null);
}
@Test
public void writeStringField() throws Exception {
assertEquals("alias(m)", func.writeStringField(params, "m"));
params.add("MyAlias");
assertEquals("alias(m,MyAlias)", func.writeStringField(params, "m"));
params.clear();
params.add("Alias");
params.add("@host");
assertEquals("alias(m,Alias,@host)", func.writeStringField(params, "m"));
params.clear();
assertEquals("alias(null)", func.writeStringField(params, null));
assertEquals("alias()", func.writeStringField(params, ""));
assertEquals("alias(inner_expression)",
func.writeStringField(null, "inner_expression"));
}
}
| lgpl-2.1 |
MatthiasMann/EnderIO | src/main/java/crazypants/enderio/machine/transceiver/PacketSendRecieveChannel.java | 2193 | package crazypants.enderio.machine.transceiver;
import io.netty.buffer.ByteBuf;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.nbt.NBTTagCompound;
import com.enderio.core.common.network.MessageTileEntity;
import com.enderio.core.common.network.NetworkUtil;
import cpw.mods.fml.common.network.simpleimpl.IMessage;
import cpw.mods.fml.common.network.simpleimpl.IMessageHandler;
import cpw.mods.fml.common.network.simpleimpl.MessageContext;
public class PacketSendRecieveChannel extends MessageTileEntity<TileTransceiver> implements IMessageHandler<PacketSendRecieveChannel, IMessage> {
private boolean isSend;
private boolean isAdd;
private Channel channel;
public PacketSendRecieveChannel() {
}
public PacketSendRecieveChannel(TileTransceiver te, boolean isSend, boolean isAdd, Channel channel) {
super(te);
this.isSend = isSend;
this.isAdd = isAdd;
this.channel = channel;
}
@Override
public void toBytes(ByteBuf buf) {
super.toBytes(buf);
buf.writeBoolean(isSend);
buf.writeBoolean(isAdd);
NBTTagCompound tag = new NBTTagCompound();
channel.writeToNBT(tag);
NetworkUtil.writeNBTTagCompound(tag, buf);
}
@Override
public void fromBytes(ByteBuf buf) {
super.fromBytes(buf);
isSend = buf.readBoolean();
isAdd = buf.readBoolean();
NBTTagCompound tag = NetworkUtil.readNBTTagCompound(buf);
channel = Channel.readFromNBT(tag);
}
@Override
public IMessage onMessage(PacketSendRecieveChannel message, MessageContext ctx) {
EntityPlayer player = ctx.getServerHandler().playerEntity;
TileTransceiver tile = message.getTileEntity(player.worldObj);
Channel channel = message.channel;
boolean isSend = message.isSend;
boolean isAdd = message.isAdd;
if (tile != null && channel != null) {
if(isSend) {
if(isAdd) {
tile.addSendChanel(channel);
} else {
tile.removeSendChanel(channel);
}
} else {
if(isAdd) {
tile.addRecieveChanel(channel);
} else {
tile.removeRecieveChanel(channel);
}
}
}
return null;
}
}
| unlicense |
vdr007/ThriftyPaxos | src/applications/h2/src/main/org/h2/command/ddl/CreateIndex.java | 3558 | /*
* Copyright 2004-2014 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.command.ddl;
import org.h2.api.ErrorCode;
import org.h2.command.CommandInterface;
import org.h2.engine.Constants;
import org.h2.engine.Database;
import org.h2.engine.Right;
import org.h2.engine.Session;
import org.h2.index.IndexType;
import org.h2.message.DbException;
import org.h2.schema.Schema;
import org.h2.table.IndexColumn;
import org.h2.table.Table;
/**
* This class represents the statement
* CREATE INDEX
*/
public class CreateIndex extends SchemaCommand {
private String tableName;
private String indexName;
private IndexColumn[] indexColumns;
private boolean primaryKey, unique, hash, spatial;
private boolean ifNotExists;
private String comment;
public CreateIndex(Session session, Schema schema) {
super(session, schema);
}
public void setIfNotExists(boolean ifNotExists) {
this.ifNotExists = ifNotExists;
}
public void setTableName(String tableName) {
this.tableName = tableName;
}
public void setIndexName(String indexName) {
this.indexName = indexName;
}
public void setIndexColumns(IndexColumn[] columns) {
this.indexColumns = columns;
}
@Override
public int update() {
if (!transactional) {
session.commit(true);
}
Database db = session.getDatabase();
boolean persistent = db.isPersistent();
Table table = getSchema().getTableOrView(session, tableName);
if (getSchema().findIndex(session, indexName) != null) {
if (ifNotExists) {
return 0;
}
throw DbException.get(ErrorCode.INDEX_ALREADY_EXISTS_1, indexName);
}
session.getUser().checkRight(table, Right.ALL);
table.lock(session, true, true);
if (!table.isPersistIndexes()) {
persistent = false;
}
int id = getObjectId();
if (indexName == null) {
if (primaryKey) {
indexName = table.getSchema().getUniqueIndexName(session,
table, Constants.PREFIX_PRIMARY_KEY);
} else {
indexName = table.getSchema().getUniqueIndexName(session,
table, Constants.PREFIX_INDEX);
}
}
IndexType indexType;
if (primaryKey) {
if (table.findPrimaryKey() != null) {
throw DbException.get(ErrorCode.SECOND_PRIMARY_KEY);
}
indexType = IndexType.createPrimaryKey(persistent, hash);
} else if (unique) {
indexType = IndexType.createUnique(persistent, hash);
} else {
indexType = IndexType.createNonUnique(persistent, hash, spatial);
}
IndexColumn.mapColumns(indexColumns, table);
table.addIndex(session, indexName, id, indexColumns, indexType, create,
comment);
return 0;
}
public void setPrimaryKey(boolean b) {
this.primaryKey = b;
}
public void setUnique(boolean b) {
this.unique = b;
}
public void setHash(boolean b) {
this.hash = b;
}
public void setSpatial(boolean b) {
this.spatial = b;
}
public void setComment(String comment) {
this.comment = comment;
}
@Override
public int getType() {
return CommandInterface.CREATE_INDEX;
}
}
| apache-2.0 |
beobal/cassandra | test/unit/org/apache/cassandra/db/ColumnsTest.java | 20913 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.cassandra.db;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;
import java.util.function.Predicate;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterators;
import com.google.common.collect.Lists;
import org.apache.cassandra.cql3.ColumnIdentifier;
import org.apache.cassandra.db.commitlog.CommitLog;
import org.apache.cassandra.db.marshal.BytesType;
import org.junit.AfterClass;
import org.junit.Test;
import org.junit.Assert;
import org.apache.cassandra.config.DatabaseDescriptor;
import org.apache.cassandra.db.marshal.AbstractType;
import org.apache.cassandra.db.marshal.SetType;
import org.apache.cassandra.db.marshal.UTF8Type;
import org.apache.cassandra.io.util.DataInputBuffer;
import org.apache.cassandra.io.util.DataOutputBuffer;
import org.apache.cassandra.schema.ColumnMetadata;
import org.apache.cassandra.schema.MockSchema;
import org.apache.cassandra.schema.TableMetadata;
import org.apache.cassandra.utils.btree.BTreeSet;
import static org.apache.cassandra.utils.ByteBufferUtil.bytes;
public class ColumnsTest
{
static
{
DatabaseDescriptor.daemonInitialization();
CommitLog.instance.start();
}
private static final TableMetadata TABLE_METADATA = MockSchema.newCFS().metadata();
@Test
public void testDeserializeCorruption() throws IOException
{
ColumnsCheck check = randomSmall(1, 0, 3, 0);
Columns superset = check.columns;
List<ColumnMetadata> minus1 = new ArrayList<>(check.definitions);
minus1.remove(3);
Columns minus2 = check.columns
.without(check.columns.getSimple(3))
.without(check.columns.getSimple(2));
try (DataOutputBuffer out = new DataOutputBuffer())
{
// serialize a subset
Columns.serializer.serializeSubset(minus1, superset, out);
try (DataInputBuffer in = new DataInputBuffer(out.toByteArray()))
{
Columns.serializer.deserializeSubset(minus2, in);
Assert.assertFalse(true);
}
catch (IOException e)
{
}
}
}
// this tests most of our functionality, since each subset we perform
// reasonably comprehensive tests of basic functionality against
@Test
public void testContainsWithoutAndMergeTo()
{
for (ColumnsCheck randomColumns : randomSmall(true))
testContainsWithoutAndMergeTo(randomColumns);
}
private void testContainsWithoutAndMergeTo(ColumnsCheck input)
{
// pick some arbitrary groupings of columns to remove at-once (to avoid factorial complexity)
// whatever is left after each removal, we perform this logic on again, recursively
List<List<ColumnMetadata>> removeGroups = shuffleAndGroup(Lists.newArrayList(input.definitions));
for (List<ColumnMetadata> defs : removeGroups)
{
ColumnsCheck subset = input.remove(defs);
// test contents after .without
subset.assertContents();
// test .contains
assertSubset(input.columns, subset.columns);
// test .mergeTo
Columns otherSubset = input.columns;
for (ColumnMetadata def : subset.definitions)
{
otherSubset = otherSubset.without(def);
assertContents(otherSubset.mergeTo(subset.columns), input.definitions);
}
testContainsWithoutAndMergeTo(subset);
}
}
private void assertSubset(Columns superset, Columns subset)
{
Assert.assertTrue(superset.containsAll(superset));
Assert.assertTrue(superset.containsAll(subset));
Assert.assertFalse(subset.containsAll(superset));
}
@Test
public void testSerialize() throws IOException
{
testSerialize(Columns.NONE, Collections.emptyList());
for (ColumnsCheck randomColumns : randomSmall(false))
testSerialize(randomColumns.columns, randomColumns.definitions);
}
private void testSerialize(Columns columns, List<ColumnMetadata> definitions) throws IOException
{
try (DataOutputBuffer out = new DataOutputBuffer())
{
Columns.serializer.serialize(columns, out);
Assert.assertEquals(Columns.serializer.serializedSize(columns), out.buffer().remaining());
Columns deserialized = Columns.serializer.deserializeRegulars(new DataInputBuffer(out.buffer(), false), mock(columns));
Assert.assertEquals(columns, deserialized);
Assert.assertEquals(columns.hashCode(), deserialized.hashCode());
assertContents(deserialized, definitions);
}
}
@Test
public void testSerializeSmallSubset() throws IOException
{
for (ColumnsCheck randomColumns : randomSmall(true))
testSerializeSubset(randomColumns);
}
@Test
public void testSerializeHugeSubset() throws IOException
{
for (ColumnsCheck randomColumns : randomHuge())
testSerializeSubset(randomColumns);
}
@Test
public void testContainsAllWithLargeNumberOfColumns()
{
List<String> names = new ArrayList<>();
for (int i = 0; i < 50; i++)
names.add("regular_" + i);
List<ColumnMetadata> defs = new ArrayList<>();
addRegular(names, defs);
Columns columns = Columns.from(new HashSet<>(defs));
defs = new ArrayList<>();
addRegular(names.subList(0, 8), defs);
Columns subset = Columns.from(new HashSet<>(defs));
Assert.assertTrue(columns.containsAll(subset));
}
@Test
public void testStaticColumns()
{
testColumns(ColumnMetadata.Kind.STATIC);
}
@Test
public void testRegularColumns()
{
testColumns(ColumnMetadata.Kind.REGULAR);
}
private void testColumns(ColumnMetadata.Kind kind)
{
List<ColumnMetadata> definitions = ImmutableList.of(
def("a", UTF8Type.instance, kind),
def("b", SetType.getInstance(UTF8Type.instance, true), kind),
def("c", UTF8Type.instance, kind),
def("d", SetType.getInstance(UTF8Type.instance, true), kind),
def("e", UTF8Type.instance, kind),
def("f", SetType.getInstance(UTF8Type.instance, true), kind),
def("g", UTF8Type.instance, kind),
def("h", SetType.getInstance(UTF8Type.instance, true), kind)
);
Columns columns = Columns.from(definitions);
// test simpleColumnCount()
Assert.assertEquals(4, columns.simpleColumnCount());
// test simpleColumns()
List<ColumnMetadata> simpleColumnsExpected =
ImmutableList.of(definitions.get(0), definitions.get(2), definitions.get(4), definitions.get(6));
List<ColumnMetadata> simpleColumnsActual = new ArrayList<>();
Iterators.addAll(simpleColumnsActual, columns.simpleColumns());
Assert.assertEquals(simpleColumnsExpected, simpleColumnsActual);
// test complexColumnCount()
Assert.assertEquals(4, columns.complexColumnCount());
// test complexColumns()
List<ColumnMetadata> complexColumnsExpected =
ImmutableList.of(definitions.get(1), definitions.get(3), definitions.get(5), definitions.get(7));
List<ColumnMetadata> complexColumnsActual = new ArrayList<>();
Iterators.addAll(complexColumnsActual, columns.complexColumns());
Assert.assertEquals(complexColumnsExpected, complexColumnsActual);
// test size()
Assert.assertEquals(8, columns.size());
// test selectOrderIterator()
List<ColumnMetadata> columnsExpected = definitions;
List<ColumnMetadata> columnsActual = new ArrayList<>();
Iterators.addAll(columnsActual, columns.selectOrderIterator());
Assert.assertEquals(columnsExpected, columnsActual);
}
private void testSerializeSubset(ColumnsCheck input) throws IOException
{
testSerializeSubset(input.columns, input.columns, input.definitions);
testSerializeSubset(input.columns, Columns.NONE, Collections.emptyList());
List<List<ColumnMetadata>> removeGroups = shuffleAndGroup(Lists.newArrayList(input.definitions));
for (List<ColumnMetadata> defs : removeGroups)
{
Collections.sort(defs);
ColumnsCheck subset = input.remove(defs);
testSerializeSubset(input.columns, subset.columns, subset.definitions);
}
}
private void testSerializeSubset(Columns superset, Columns subset, List<ColumnMetadata> subsetDefinitions) throws IOException
{
try (DataOutputBuffer out = new DataOutputBuffer())
{
Columns.serializer.serializeSubset(subset, superset, out);
Assert.assertEquals(Columns.serializer.serializedSubsetSize(subset, superset), out.buffer().remaining());
Columns deserialized = Columns.serializer.deserializeSubset(superset, new DataInputBuffer(out.buffer(), false));
Assert.assertEquals(subset, deserialized);
Assert.assertEquals(subset.hashCode(), deserialized.hashCode());
assertContents(deserialized, subsetDefinitions);
}
}
private static void assertContents(Columns columns, List<ColumnMetadata> defs)
{
Assert.assertEquals(defs, Lists.newArrayList(columns));
boolean hasSimple = false, hasComplex = false;
int firstComplexIdx = 0;
int i = 0;
Iterator<ColumnMetadata> simple = columns.simpleColumns();
Iterator<ColumnMetadata> complex = columns.complexColumns();
Iterator<ColumnMetadata> all = columns.iterator();
Predicate<ColumnMetadata> predicate = columns.inOrderInclusionTester();
for (ColumnMetadata def : defs)
{
Assert.assertEquals(def, all.next());
Assert.assertTrue(columns.contains(def));
Assert.assertTrue(predicate.test(def));
if (def.isSimple())
{
hasSimple = true;
Assert.assertEquals(i, columns.simpleIdx(def));
Assert.assertEquals(def, columns.getSimple(i));
Assert.assertEquals(def, simple.next());
++firstComplexIdx;
}
else
{
Assert.assertFalse(simple.hasNext());
hasComplex = true;
Assert.assertEquals(i - firstComplexIdx, columns.complexIdx(def));
Assert.assertEquals(def, columns.getComplex(i - firstComplexIdx));
Assert.assertEquals(def, complex.next());
}
i++;
}
Assert.assertEquals(defs.isEmpty(), columns.isEmpty());
Assert.assertFalse(simple.hasNext());
Assert.assertFalse(complex.hasNext());
Assert.assertFalse(all.hasNext());
Assert.assertEquals(hasSimple, columns.hasSimple());
Assert.assertEquals(hasComplex, columns.hasComplex());
// check select order
if (!columns.hasSimple() || !columns.getSimple(0).kind.isPrimaryKeyKind())
{
List<ColumnMetadata> selectOrderDefs = new ArrayList<>(defs);
Collections.sort(selectOrderDefs, (a, b) -> a.name.bytes.compareTo(b.name.bytes));
List<ColumnMetadata> selectOrderColumns = new ArrayList<>();
Iterators.addAll(selectOrderColumns, columns.selectOrderIterator());
Assert.assertEquals(selectOrderDefs, selectOrderColumns);
}
}
private static <V> List<List<V>> shuffleAndGroup(List<V> list)
{
// first shuffle
ThreadLocalRandom random = ThreadLocalRandom.current();
for (int i = 0 ; i < list.size() - 1 ; i++)
{
int j = random.nextInt(i, list.size());
V v = list.get(i);
list.set(i, list.get(j));
list.set(j, v);
}
// then group (logarithmically, to ensure our recursive functions don't explode the state space)
List<List<V>> result = new ArrayList<>();
for (int i = 0 ; i < list.size() ;)
{
List<V> group = new ArrayList<>();
int maxCount = list.size() - i;
int count = maxCount <= 2 ? maxCount : random.nextInt(1, maxCount);
for (int j = 0 ; j < count ; j++)
group.add(list.get(i + j));
i += count;
result.add(group);
}
return result;
}
@AfterClass
public static void cleanup()
{
MockSchema.cleanup();
}
private static class ColumnsCheck
{
final Columns columns;
final List<ColumnMetadata> definitions;
private ColumnsCheck(Columns columns, List<ColumnMetadata> definitions)
{
this.columns = columns;
this.definitions = definitions;
}
private ColumnsCheck(List<ColumnMetadata> definitions)
{
this.columns = Columns.from(BTreeSet.of(definitions));
this.definitions = definitions;
}
ColumnsCheck remove(List<ColumnMetadata> remove)
{
Columns subset = columns;
for (ColumnMetadata def : remove)
subset = subset.without(def);
Assert.assertEquals(columns.size() - remove.size(), subset.size());
List<ColumnMetadata> remainingDefs = Lists.newArrayList(columns);
remainingDefs.removeAll(remove);
return new ColumnsCheck(subset, remainingDefs);
}
void assertContents()
{
ColumnsTest.assertContents(columns, definitions);
}
}
private static List<ColumnsCheck> randomHuge()
{
List<ColumnsCheck> result = new ArrayList<>();
ThreadLocalRandom random = ThreadLocalRandom.current();
result.add(randomHuge(random.nextInt(64, 128), 0, 0, 0));
result.add(randomHuge(0, random.nextInt(64, 128), 0, 0));
result.add(randomHuge(0, 0, random.nextInt(64, 128), 0));
result.add(randomHuge(0, 0, 0, random.nextInt(64, 128)));
result.add(randomHuge(random.nextInt(64, 128), random.nextInt(64, 128), 0, 0));
result.add(randomHuge(0, random.nextInt(64, 128), random.nextInt(64, 128), 0));
result.add(randomHuge(0, 0, random.nextInt(64, 128), random.nextInt(64, 128)));
result.add(randomHuge(random.nextInt(64, 128), random.nextInt(64, 128), random.nextInt(64, 128), 0));
result.add(randomHuge(0, random.nextInt(64, 128), random.nextInt(64, 128), random.nextInt(64, 128)));
result.add(randomHuge(random.nextInt(64, 128), random.nextInt(64, 128), random.nextInt(64, 128), random.nextInt(64, 128)));
return result;
}
private static List<ColumnsCheck> randomSmall(boolean permitMultiplePartitionKeys)
{
List<ColumnsCheck> random = new ArrayList<>();
for (int i = 1 ; i <= 3 ; i++)
{
int pkCount = permitMultiplePartitionKeys ? i - 1 : 1;
if (permitMultiplePartitionKeys)
random.add(randomSmall(i, i - 1, i - 1, i - 1));
random.add(randomSmall(0, 0, i, i)); // both kinds of regular, no PK
random.add(randomSmall(pkCount, i, i - 1, i - 1)); // PK + clustering, few or none regular
random.add(randomSmall(pkCount, i - 1, i, i - 1)); // PK + few or none clustering, some regular, few or none complex
random.add(randomSmall(pkCount, i - 1, i - 1, i)); // PK + few or none clustering or regular, some complex
}
return random;
}
private static ColumnsCheck randomSmall(int pkCount, int clCount, int regularCount, int complexCount)
{
List<String> names = new ArrayList<>();
for (char c = 'a' ; c <= 'z' ; c++)
names .add(Character.toString(c));
List<ColumnMetadata> result = new ArrayList<>();
addPartition(select(names, pkCount), result);
addClustering(select(names, clCount), result);
addRegular(select(names, regularCount), result);
addComplex(select(names, complexCount), result);
Collections.sort(result);
return new ColumnsCheck(result);
}
private static List<String> select(List<String> names, int count)
{
List<String> result = new ArrayList<>();
ThreadLocalRandom random = ThreadLocalRandom.current();
for (int i = 0 ; i < count ; i++)
{
int v = random.nextInt(names.size());
result.add(names.get(v));
names.remove(v);
}
return result;
}
private static ColumnsCheck randomHuge(int pkCount, int clCount, int regularCount, int complexCount)
{
List<ColumnMetadata> result = new ArrayList<>();
Set<String> usedNames = new HashSet<>();
addPartition(names(pkCount, usedNames), result);
addClustering(names(clCount, usedNames), result);
addRegular(names(regularCount, usedNames), result);
addComplex(names(complexCount, usedNames), result);
Collections.sort(result);
return new ColumnsCheck(result);
}
private static List<String> names(int count, Set<String> usedNames)
{
List<String> names = new ArrayList<>();
StringBuilder builder = new StringBuilder();
ThreadLocalRandom random = ThreadLocalRandom.current();
for (int i = 0 ; i < count ; i++)
{
builder.setLength(0);
for (int j = 0 ; j < 3 || usedNames.contains(builder.toString()) ; j++)
builder.append((char) random.nextInt('a', 'z' + 1));
String name = builder.toString();
names.add(name);
usedNames.add(name);
}
return names;
}
private static void addPartition(List<String> names, List<ColumnMetadata> results)
{
for (String name : names)
results.add(ColumnMetadata.partitionKeyColumn(TABLE_METADATA, bytes(name), UTF8Type.instance, 0));
}
private static void addClustering(List<String> names, List<ColumnMetadata> results)
{
int i = 0;
for (String name : names)
results.add(ColumnMetadata.clusteringColumn(TABLE_METADATA, bytes(name), UTF8Type.instance, i++));
}
private static void addRegular(List<String> names, List<ColumnMetadata> results)
{
for (String name : names)
results.add(ColumnMetadata.regularColumn(TABLE_METADATA, bytes(name), UTF8Type.instance));
}
private static void addComplex(List<String> names, List<ColumnMetadata> results)
{
for (String name : names)
results.add(ColumnMetadata.regularColumn(TABLE_METADATA, bytes(name), SetType.getInstance(UTF8Type.instance, true)));
}
private static ColumnMetadata def(String name, AbstractType<?> type, ColumnMetadata.Kind kind)
{
return new ColumnMetadata(TABLE_METADATA, bytes(name), type, ColumnMetadata.NO_POSITION, kind);
}
private static TableMetadata mock(Columns columns)
{
if (columns.isEmpty())
return TABLE_METADATA;
TableMetadata.Builder builder = TableMetadata.builder(TABLE_METADATA.keyspace, TABLE_METADATA.name);
boolean hasPartitionKey = false;
for (ColumnMetadata def : columns)
{
switch (def.kind)
{
case PARTITION_KEY:
builder.addPartitionKeyColumn(def.name, def.type);
hasPartitionKey = true;
break;
case CLUSTERING:
builder.addClusteringColumn(def.name, def.type);
break;
case REGULAR:
builder.addRegularColumn(def.name, def.type);
break;
}
}
if (!hasPartitionKey)
builder.addPartitionKeyColumn("219894021498309239rufejsfjdksfjheiwfhjes", UTF8Type.instance);
return builder.build();
}
}
| apache-2.0 |
scbrady/kafka-rest | src/test/java/io/confluent/kafkarest/integration/AvroProducerTest.java | 7736 | /**
* Copyright 2015 Confluent Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
package io.confluent.kafkarest.integration;
import com.fasterxml.jackson.databind.JsonNode;
import org.apache.avro.Schema;
import org.junit.Before;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import io.confluent.kafka.serializers.KafkaAvroDecoder;
import io.confluent.kafkarest.TestUtils;
import io.confluent.kafkarest.Versions;
import io.confluent.kafkarest.entities.AvroProduceRecord;
import io.confluent.kafkarest.entities.AvroTopicProduceRecord;
import io.confluent.kafkarest.entities.Partition;
import io.confluent.kafkarest.entities.PartitionOffset;
import io.confluent.kafkarest.entities.PartitionProduceRequest;
import io.confluent.kafkarest.entities.PartitionReplica;
import io.confluent.kafkarest.entities.ProduceRecord;
import io.confluent.kafkarest.entities.ProduceResponse;
import io.confluent.kafkarest.entities.TopicProduceRecord;
import io.confluent.kafkarest.entities.TopicProduceRequest;
import kafka.utils.VerifiableProperties;
import scala.collection.JavaConversions;
import static io.confluent.kafkarest.TestUtils.assertOKResponse;
import static org.junit.Assert.assertEquals;
// This test is much lighter than the Binary one which exercises all variants. Since binary
// covers most code paths well, this just tries to exercise Avro-specific parts.
public class AvroProducerTest extends ClusterTestHarness {
private static final String topicName = "topic1";
private static final List<Partition> partitions = Arrays.asList(
new Partition(0, 0, Arrays.asList(
new PartitionReplica(0, true, true),
new PartitionReplica(1, false, false)
))
);
private KafkaAvroDecoder avroDecoder;
// This test assumes that AvroConverterTest is good enough and testing one primitive type for
// keys and one complex type for records is sufficient.
private static final String keySchemaStr = "{\"name\":\"int\",\"type\": \"int\"}";
private static final String valueSchemaStr = "{\"type\": \"record\", "
+ "\"name\":\"test\","
+ "\"fields\":[{"
+ " \"name\":\"field\", "
+ " \"type\": \"int\""
+ "}]}";
private static final Schema valueSchema = new Schema.Parser().parse(valueSchemaStr);
private final static JsonNode[] testKeys = {
TestUtils.jsonTree("1"),
TestUtils.jsonTree("2"),
TestUtils.jsonTree("3"),
TestUtils.jsonTree("4")
};
private final static JsonNode[] testValues = {
TestUtils.jsonTree("{\"field\": 1}"),
TestUtils.jsonTree("{\"field\": 2}"),
TestUtils.jsonTree("{\"field\": 3}"),
TestUtils.jsonTree("{\"field\": 4}"),
};
// Produce to topic inputs & results
private final List<AvroTopicProduceRecord> topicRecordsWithPartitionsAndKeys = Arrays.asList(
new AvroTopicProduceRecord(testKeys[0], testValues[0], 0),
new AvroTopicProduceRecord(testKeys[1], testValues[1], 1),
new AvroTopicProduceRecord(testKeys[2], testValues[2], 1),
new AvroTopicProduceRecord(testKeys[3], testValues[3], 2)
);
private final List<PartitionOffset> partitionOffsetsWithPartitionsAndKeys = Arrays.asList(
new PartitionOffset(0, 0L, null, null),
new PartitionOffset(0, 1L, null, null),
new PartitionOffset(1, 0L, null, null),
new PartitionOffset(1, 1L, null, null)
);
// Produce to partition inputs & results
private final List<AvroProduceRecord> partitionRecordsOnlyValues = Arrays.asList(
new AvroProduceRecord(testValues[0]),
new AvroProduceRecord(testValues[1]),
new AvroProduceRecord(testValues[2]),
new AvroProduceRecord(testValues[3])
);
private final List<PartitionOffset> producePartitionOffsetOnlyValues = Arrays.asList(
new PartitionOffset(0, 0L, null, null),
new PartitionOffset(0, 1L, null, null),
new PartitionOffset(0, 2L, null, null),
new PartitionOffset(0, 3L, null, null)
);
public AvroProducerTest() {
super(1, true);
}
@Before
@Override
public void setUp() throws Exception {
super.setUp();
final int numPartitions = 3;
final int replicationFactor = 1;
kafka.utils.TestUtils.createTopic(zkClient, topicName, numPartitions, replicationFactor,
JavaConversions.asScalaIterable(this.servers).toSeq(),
new Properties());
Properties props = new Properties();
props.setProperty("schema.registry.url", schemaRegConnect);
avroDecoder = new KafkaAvroDecoder(new VerifiableProperties(props));
}
private <K, V> void testProduceToTopic(List<? extends TopicProduceRecord> records,
List<PartitionOffset> offsetResponses) {
TopicProduceRequest payload = new TopicProduceRequest();
payload.setRecords(records);
payload.setKeySchema(keySchemaStr);
payload.setValueSchema(valueSchemaStr);
Response response = request("/topics/" + topicName)
.post(Entity.entity(payload, Versions.KAFKA_V1_JSON_AVRO));
assertOKResponse(response, Versions.KAFKA_MOST_SPECIFIC_DEFAULT);
final ProduceResponse produceResponse = response.readEntity(ProduceResponse.class);
TestUtils.assertPartitionOffsetsEqual(offsetResponses, produceResponse.getOffsets());
TestUtils.assertTopicContains(zkConnect, topicName,
payload.getRecords(), null,
avroDecoder, avroDecoder, false);
assertEquals(produceResponse.getKeySchemaId(), (Integer) 1);
assertEquals(produceResponse.getValueSchemaId(), (Integer) 2);
}
@Test
public void testProduceToTopicWithPartitionsAndKeys() {
testProduceToTopic(topicRecordsWithPartitionsAndKeys, partitionOffsetsWithPartitionsAndKeys);
}
private <K, V> void testProduceToPartition(List<? extends ProduceRecord<K, V>> records,
List<PartitionOffset> offsetResponse) {
PartitionProduceRequest payload = new PartitionProduceRequest();
payload.setRecords(records);
payload.setValueSchema(valueSchemaStr);
Response response = request("/topics/" + topicName + "/partitions/0")
.post(Entity.entity(payload, Versions.KAFKA_V1_JSON_AVRO));
assertOKResponse(response, Versions.KAFKA_MOST_SPECIFIC_DEFAULT);
final ProduceResponse poffsetResponse
= response.readEntity(ProduceResponse.class);
assertEquals(offsetResponse, poffsetResponse.getOffsets());
TestUtils.assertTopicContains(zkConnect, topicName,
payload.getRecords(), (Integer) 0,
avroDecoder, avroDecoder, false);
assertEquals((Integer) 1, poffsetResponse.getValueSchemaId());
}
@Test
public void testProduceToPartitionOnlyValues() {
testProduceToPartition(partitionRecordsOnlyValues, producePartitionOffsetOnlyValues);
}
}
| apache-2.0 |
rmetzger/flink | flink-connectors/flink-connector-kinesis/src/main/java/org/apache/flink/streaming/connectors/kinesis/RandomKinesisPartitioner.java | 1522 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.flink.streaming.connectors.kinesis;
import org.apache.flink.annotation.PublicEvolving;
import java.util.UUID;
/**
* A {@link KinesisPartitioner} that maps an arbitrary input {@code element} to a random partition
* ID.
*
* @param <T> The input element type.
*/
@PublicEvolving
public final class RandomKinesisPartitioner<T> extends KinesisPartitioner<T> {
@Override
public String getPartitionId(T element) {
return UUID.randomUUID().toString();
}
@Override
public boolean equals(Object o) {
return o instanceof RandomKinesisPartitioner;
}
@Override
public int hashCode() {
return RandomKinesisPartitioner.class.hashCode();
}
}
| apache-2.0 |
eclipse/gemini.blueprint | integration-tests/tests/src/test/java/org/eclipse/gemini/blueprint/iandt/tcclManagement/ServiceTcclTest.java | 6377 | /******************************************************************************
* Copyright (c) 2006, 2010 VMware Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Apache License v2.0 which accompanies this distribution.
* The Eclipse Public License is available at
* http://www.eclipse.org/legal/epl-v10.html and the Apache License v2.0
* is available at http://www.opensource.org/licenses/apache2.0.php.
* You may elect to redistribute this code under either of these licenses.
*
* Contributors:
* VMware Inc.
*****************************************************************************/
package org.eclipse.gemini.blueprint.iandt.tcclManagement;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.List;
import org.eclipse.gemini.blueprint.iandt.BaseIntegrationTest;
import org.osgi.framework.AdminPermission;
import org.osgi.framework.ServiceReference;
import org.eclipse.gemini.blueprint.iandt.tccl.TCCLService;
/**
* Test for TCCL handling from the server side. This test checks that the service provider has always priority no matter
* the client setting.
*
* @author Costin Leau
*
*/
public class ServiceTcclTest extends BaseIntegrationTest {
private static final String CLIENT_RESOURCE =
"/org/eclipse/gemini/blueprint/iandt/tcclManagement/client-resource.properties";
private static final String SERVICE_RESOURCE =
"/org/eclipse/gemini/blueprint/iandt/tccl/internal/internal-resource.file";
private static final String SERVICE_PUBLIC_RESOURCE = "/org/eclipse/gemini/blueprint/iandt/tccl/service-resource.file";
private static final String CLIENT_CLASS = "org.eclipse.gemini.blueprint.iandt.tcclManagement.ServiceTcclTest";
private static final String SERVICE_CLASS =
"org.eclipse.gemini.blueprint.iandt.tccl.internal.PrivateTCCLServiceImplementation";
private static final String SERVICE_PUBLIC_CLASS = "org.eclipse.gemini.blueprint.iandt.tccl.TCCLService";
protected String[] getConfigLocations() {
return new String[] { "/org/eclipse/gemini/blueprint/iandt/tcclManagement/service-context.xml" };
}
protected String[] getTestBundlesNames() {
return new String[] { "org.eclipse.gemini.blueprint.iandt,tccl.intf," + getSpringDMVersion(),
"org.eclipse.gemini.blueprint.iandt,tccl," + getSpringDMVersion() };
}
public void testSanity() throws Exception {
ServiceReference[] refs =
bundleContext.getServiceReferences("org.eclipse.gemini.blueprint.iandt.tccl.TCCLService",
"(tccl=service-provider)");
System.out.println(bundleContext.getService(refs[0]));
}
public void testServiceProviderTCCLAndUnmanagedClient() throws Exception {
ClassLoader loader = Thread.currentThread().getContextClassLoader();
TCCLService tccl = getUnmanagedTCCL();
assertNotSame("service provide CL hasn't been set", loader, tccl.getTCCL());
}
public void testServiceProviderTCCLWithUnmanagedClientWithNullClassLoader() throws Exception {
ClassLoader previous = Thread.currentThread().getContextClassLoader();
try {
Thread.currentThread().setContextClassLoader(null);
ClassLoader cl = getUnmanagedTCCL().getTCCL();
assertNotNull("service provide CL hasn't been set", cl);
} finally {
Thread.currentThread().setContextClassLoader(previous);
}
}
public void testServiceProviderTCCLAndUnmanagedClientWithPredefinedClassLoader() throws Exception {
URLClassLoader dummyCL = new URLClassLoader(new URL[0]);
ClassLoader previous = Thread.currentThread().getContextClassLoader();
try {
Thread.currentThread().setContextClassLoader(dummyCL);
ClassLoader cl = getUnmanagedTCCL().getTCCL();
assertNotSame(dummyCL, cl);
} finally {
Thread.currentThread().setContextClassLoader(previous);
}
}
public void testServiceProviderTCCLWithClientTCCLOnClasses() throws Exception {
failToLoadClass(getClientTCCL().getTCCL(), CLIENT_CLASS);
}
public void testServiceProviderTCCLWithClientTCCLOnResources() throws Exception {
assertNull(getClientTCCL().getTCCL().getResource(CLIENT_RESOURCE));
}
public void testServiceProviderTCCLWithClientTCCLWithServiceClasses() throws Exception {
ClassLoader cl = getClientTCCL().getTCCL();
cl.loadClass(SERVICE_PUBLIC_CLASS);
cl.loadClass(SERVICE_CLASS);
}
public void testServiceProviderTCCLWithClientTCCLWithServiceResource() throws Exception {
assertNotNull(getClientTCCL().getTCCL().getResource(SERVICE_PUBLIC_CLASS.replace(".", "/").concat(".class")));
assertNotNull(getClientTCCL().getTCCL().getResource(SERVICE_RESOURCE));
}
public void testServiceProvidedTCCLOnClasses() throws Exception {
ClassLoader cl = getServiceProviderTCCL().getTCCL();
cl.loadClass(SERVICE_PUBLIC_CLASS);
cl.loadClass(SERVICE_CLASS);
}
public void testServiceProvidedTCCLOnResources() throws Exception {
assertNotNull(getServiceProviderTCCL().getTCCL().getResource(SERVICE_RESOURCE));
}
public void testServiceProviderTCCLOnClientClasses() throws Exception {
failToLoadClass(getServiceProviderTCCL().getTCCL(), CLIENT_CLASS);
}
public void testServiceProviderTCCLOnClientResources() throws Exception {
assertNull(getServiceProviderTCCL().getTCCL().getResource(CLIENT_RESOURCE));
}
private void failToLoadClass(ClassLoader cl, String className) {
try {
cl.loadClass(className);
fail("shouldn't be able to load class " + className);
} catch (ClassNotFoundException cnfe) {
// expected
}
}
private TCCLService getUnmanagedTCCL() {
return (TCCLService) applicationContext.getBean("unmanaged");
}
private TCCLService getServiceProviderTCCL() {
return (TCCLService) applicationContext.getBean("service-provider");
}
private TCCLService getClientTCCL() {
return (TCCLService) applicationContext.getBean("client");
}
// provide permission for loading class using the service bundle
protected List getTestPermissions() {
List perms = super.getTestPermissions();
perms.add(new AdminPermission("(name=org.eclipse.gemini.blueprint.iandt.tccl)", AdminPermission.CLASS));
perms.add(new AdminPermission("(name=org.eclipse.gemini.blueprint.iandt.tccl)", AdminPermission.RESOURCE));
return perms;
}
} | apache-2.0 |
gstevey/gradle | subprojects/messaging/src/main/java/org/gradle/internal/remote/internal/hub/StreamFailureHandler.java | 984 | /*
* Copyright 2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.internal.remote.internal.hub;
/**
* A handler for messages that fail while streaming to the peer, either on the sending side or on the receiving side
*/
public interface StreamFailureHandler {
/**
* Called when notification of a streaming failure is received on an incoming channel.
*/
void handleStreamFailure(Throwable t);
}
| apache-2.0 |