repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
gytis/narayana
qa/tests/src/org/jboss/jbossts/qa/OTSServerClients/Client11.java
3491
/* * JBoss, Home of Professional Open Source * Copyright 2007, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. * See the copyright.txt in the distribution for a * full listing of individual contributors. * This copyrighted material is made available to anyone wishing to use, * modify, copy, or redistribute it subject to the terms and conditions * of the GNU Lesser General Public License, v. 2.1. * This program is distributed in the hope that it will be useful, but WITHOUT A * 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, * v.2.1 along with this distribution; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. * * (C) 2005-2006, * @author JBoss Inc. */ // // Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003 // // Arjuna Technologies Ltd., // Newcastle upon Tyne, // Tyne and Wear, // UK. // package org.jboss.jbossts.qa.OTSServerClients; /* * Copyright (C) 1999-2001 by HP Bluestone Software, Inc. All rights Reserved. * * HP Arjuna Labs, * Newcastle upon Tyne, * Tyne and Wear, * UK. * * $Id: Client11.java,v 1.2 2003/06/26 11:44:17 rbegg Exp $ */ /* * Try to get around the differences between Ansi CPP and * K&R cpp with concatenation. */ /* * Copyright (C) 1999-2001 by HP Bluestone Software, Inc. All rights Reserved. * * HP Arjuna Labs, * Newcastle upon Tyne, * Tyne and Wear, * UK. * * $Id: Client11.java,v 1.2 2003/06/26 11:44:17 rbegg Exp $ */ import org.jboss.jbossts.qa.Utils.OAInterface; import org.jboss.jbossts.qa.Utils.ORBInterface; import org.jboss.jbossts.qa.Utils.ORBServices; import org.omg.CosTransactions.Control; import org.omg.CosTransactions.Status; import org.omg.CosTransactions.TransactionFactory; import org.omg.CosTransactions.TransactionFactoryHelper; public class Client11 { public static void main(String[] args) { try { ORBInterface.initORB(args, null); OAInterface.initOA(); TransactionFactory transactionFactory = null; String[] transactionFactoryParams = new String[1]; transactionFactoryParams[0] = ORBServices.otsKind; transactionFactory = TransactionFactoryHelper.narrow(ORBServices.getService(ORBServices.transactionService, transactionFactoryParams)); int numberOfControls = Integer.parseInt(args[args.length - 1]); boolean correct = true; Control[] controls = new Control[numberOfControls]; for (int index = 0; correct && (index < controls.length); index++) { controls[index] = transactionFactory.create(0); correct = correct && (controls[index].get_coordinator().get_status() == Status.StatusActive); } for (int index = 0; correct && (index < controls.length); index++) { controls[index].get_terminator().commit(false); } if (correct) { System.out.println("Passed"); } else { System.out.println("Failed"); } } catch (Exception exception) { System.out.println("Failed"); System.err.println("Client11.main: " + exception); exception.printStackTrace(System.err); } try { OAInterface.shutdownOA(); ORBInterface.shutdownORB(); } catch (Exception exception) { System.err.println("Client11.main: " + exception); exception.printStackTrace(System.err); } } }
lgpl-2.1
andre-nunes/fenixedu-academic
src/main/java/org/fenixedu/academic/task/SeparateSecondCycle.java
7736
/** * Copyright © 2002 Instituto Superior Técnico * * This file is part of FenixEdu Academic. * * FenixEdu Academic is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * FenixEdu Academic 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 FenixEdu Academic. If not, see <http://www.gnu.org/licenses/>. */ package org.fenixedu.academic.task; import java.util.List; import java.util.Locale; import org.fenixedu.academic.domain.DegreeCurricularPlan; import org.fenixedu.academic.domain.StudentCurricularPlan; import org.fenixedu.academic.domain.degree.DegreeType; import org.fenixedu.academic.domain.degree.degreeCurricularPlan.DegreeCurricularPlanState; import org.fenixedu.academic.domain.student.Registration; import org.fenixedu.academic.domain.student.SeparationCyclesManagement; import org.fenixedu.academic.domain.student.Student; import org.fenixedu.academic.domain.studentCurriculum.CycleCurriculumGroup; import org.fenixedu.bennu.scheduler.CronTask; import org.fenixedu.bennu.scheduler.annotation.Task; import org.fenixedu.commons.i18n.I18N; import pt.ist.fenixframework.Atomic; import pt.ist.fenixframework.Atomic.TxMode; //TODO remove in next major @Deprecated @Task(englishTitle = "SeparateSecondCycle", readOnly = true) public class SeparateSecondCycle extends CronTask { @Override public void runTask() { I18N.setLocale(new Locale("pt", "PT")); for (final DegreeCurricularPlan degreeCurricularPlan : getDegreeCurricularPlans()) { getLogger().info("Processing DCP: " + degreeCurricularPlan.getName()); for (final StudentCurricularPlan studentCurricularPlan : degreeCurricularPlan.getStudentCurricularPlansSet()) { if (studentCurricularPlan.isActive() && canSeparate(studentCurricularPlan)) { if (studentAlreadyHasNewRegistration(studentCurricularPlan) && canRepeateSeparate(studentCurricularPlan)) { getLogger() .info("1 - Repeating separate for: " + studentCurricularPlan.getRegistration().getStudent().getNumber()); try { separateByStudentNumberProcedure(studentCurricularPlan.getRegistration().getStudent(), studentCurricularPlan.getDegreeCurricularPlan()); } catch (Exception e) { //abort transaction and continue getLogger().error("Repeating separate student", e); } } else { getLogger().info( "Separating Student: " + studentCurricularPlan.getRegistration().getStudent().getNumber()); try { separateStudentProcedure(studentCurricularPlan); } catch (Exception e) { //abort transaction and continue getLogger().error("Separating students with rules", e); } } } else if (studentCurricularPlan.hasRegistration() && studentCurricularPlan.getRegistration().isConcluded()) { if (canRepeateSeparate(studentCurricularPlan)) { getLogger() .info("2 - Repeating separate for: " + studentCurricularPlan.getRegistration().getStudent().getNumber()); try { separateByStudentNumberProcedure(studentCurricularPlan.getRegistration().getStudent(), studentCurricularPlan.getDegreeCurricularPlan()); } catch (Exception e) { //abort transaction and continue getLogger().error("Repeating separate student", e); } } } } } } private boolean studentAlreadyHasNewRegistration(final StudentCurricularPlan studentCurricularPlan) { final Student student = studentCurricularPlan.getRegistration().getStudent(); return student.hasRegistrationFor(studentCurricularPlan.getSecondCycle().getDegreeCurricularPlanOfDegreeModule()); } private boolean canSeparate(final StudentCurricularPlan studentCurricularPlan) { return hasFirstCycleConcluded(studentCurricularPlan) && hasExternalSecondCycle(studentCurricularPlan); } private boolean canRepeateSeparate(final StudentCurricularPlan studentCurricularPlan) { return hasFirstCycleConcluded(studentCurricularPlan) && hasExternalSecondCycleAndNewRegistration(studentCurricularPlan); } private List<DegreeCurricularPlan> getDegreeCurricularPlans() { return DegreeCurricularPlan.readByDegreeTypesAndState( DegreeType.oneOf(DegreeType::isBolonhaDegree, DegreeType::isIntegratedMasterDegree), DegreeCurricularPlanState.ACTIVE); } private boolean hasFirstCycleConcluded(final StudentCurricularPlan studentCurricularPlan) { final CycleCurriculumGroup firstCycle = studentCurricularPlan.getFirstCycle(); return firstCycle != null && firstCycle.isConcluded(); } private boolean hasExternalSecondCycle(final StudentCurricularPlan studentCurricularPlan) { final CycleCurriculumGroup secondCycle = studentCurricularPlan.getSecondCycle(); return secondCycle != null && secondCycle.isExternal() && secondCycle.hasAnyCurriculumLines(); } private boolean hasExternalSecondCycleAndNewRegistration(final StudentCurricularPlan studentCurricularPlan) { final CycleCurriculumGroup secondCycle = studentCurricularPlan.getSecondCycle(); if (secondCycle != null && secondCycle.isExternal() && secondCycle.hasAnyCurriculumLines()) { final Student student = studentCurricularPlan.getRegistration().getStudent(); return student.hasActiveRegistrationFor(secondCycle.getDegreeCurricularPlanOfDegreeModule()); } return false; } @Atomic(mode = TxMode.WRITE) private void separateStudentProcedure(StudentCurricularPlan studentCurricularPlan) { new SeparationCyclesManagement().separateSecondCycle(studentCurricularPlan); } @Atomic(mode = TxMode.WRITE) private void separateByStudentNumberProcedure(Student student, DegreeCurricularPlan dcp) { final Registration registration = student.getMostRecentRegistration(dcp); new SeparateByStudentNumber().separateSecondCycle(registration.getLastStudentCurricularPlan()); } private class SeparateByStudentNumber extends SeparationCyclesManagement { @Override public Registration separateSecondCycle(StudentCurricularPlan studentCurricularPlan) { // do not check if can separate // the state of the registration can change during the execution of this long script and thus at least this validation has to be made // to prevent wrong creations of new registrations if (canRepeateSeparate(studentCurricularPlan)) { return createNewSecondCycle(studentCurricularPlan); } return null; } } }
lgpl-3.0
JNPA/fenixedu-academic
src/main/java/org/fenixedu/academic/ui/renderers/providers/accounting/postingRules/gratuity/SpecializationDegreeGratuityPRTypeProvider.java
2214
/** * Copyright © 2002 Instituto Superior Técnico * * This file is part of FenixEdu Academic. * * FenixEdu Academic is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * FenixEdu Academic 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 FenixEdu Academic. If not, see <http://www.gnu.org/licenses/>. */ package org.fenixedu.academic.ui.renderers.providers.accounting.postingRules.gratuity; import java.util.Arrays; import org.fenixedu.academic.domain.accounting.postingRules.gratuity.SpecializationDegreeGratuityByAmountPerEctsPR; import pt.ist.fenixWebFramework.renderers.DataProvider; import pt.ist.fenixWebFramework.renderers.components.converters.BiDirectionalConverter; import pt.ist.fenixWebFramework.renderers.components.converters.Converter; public class SpecializationDegreeGratuityPRTypeProvider implements DataProvider { @Override public Object provide(Object source, Object currentValue) { return Arrays.asList(SpecializationDegreeGratuityByAmountPerEctsPR.class); } @Override public Converter getConverter() { return new BiDirectionalConverter() { /** * */ private static final long serialVersionUID = 1L; @Override public String deserialize(Object target) { return ((Class<?>) target).getName(); } @Override public Object convert(Class type, Object target) { try { return Class.forName((String) target); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } }; } }
lgpl-3.0
wso2/siddhi
modules/siddhi-query-api/src/main/java/io/siddhi/query/api/exception/UnsupportedAttributeTypeException.java
984
/* * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package io.siddhi.query.api.exception; /** * Exception thrown when unsupported attribute type assigned to an attribute */ public class UnsupportedAttributeTypeException extends SiddhiAppValidationException { public UnsupportedAttributeTypeException(String message) { super(message); } }
apache-2.0
llpj/gag
src/com/google/gag/annotation/remark/ObligatoryQuote.java
993
/** * Copyright 2010 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.gag.annotation.remark; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import com.google.gag.enumeration.Source; @Documented @Retention(RetentionPolicy.RUNTIME) public @interface ObligatoryQuote { String quote(); Source source(); String other() default ""; String citation() default ""; }
apache-2.0
deniskovalenko/mosby
viewstate-dagger1/src/main/java/com/hannesdorfmann/mosby/dagger1/viewstate/Dagger1MvpViewStateActivity.java
2399
/* * Copyright 2015 Hannes Dorfmann. * * 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.hannesdorfmann.mosby.dagger1.viewstate; import android.app.Application; import com.hannesdorfmann.mosby.dagger1.Injector; import com.hannesdorfmann.mosby.mvp.MvpPresenter; import com.hannesdorfmann.mosby.mvp.MvpView; import com.hannesdorfmann.mosby.mvp.viewstate.MvpViewStateActivity; import dagger.ObjectGraph; /** * A {@link MvpViewStateActivity} with dagger1 support by implementing {@link Injector}. * * <p> * Does not automatically inject itself dependencies. To do so please override {@link * #injectDependencies()} * </p> * * @author Hannes Dorfmann * @since 1.0.0 */ public abstract class Dagger1MvpViewStateActivity<V extends MvpView, P extends MvpPresenter<V>> extends MvpViewStateActivity<V, P> implements Injector { /** * Returns daggers object graph. As default {@link Dagger1MvpViewStateActivity} assumes that your * {@link * Application} implements {@link Injector} and that one will be accessed. If you want to do your * own thing override this method. However, injecting should not be done in this method but in * {@link #injectDependencies()} * * @see #injectDependencies() */ @Override public ObjectGraph getObjectGraph() { if (getApplication() == null) { throw new NullPointerException("Application is null"); } if (!(getApplication() instanceof Injector)) { throw new IllegalArgumentException("You are using " + this.getClass() + " for injecting Dagger." + " This requires that your Application implements " + Injector.class.getCanonicalName() + ". Alternatively you can override getObjectGraph() in your Activity to fit your needs"); } Injector appInjector = (Injector) getApplication(); return appInjector.getObjectGraph(); } }
apache-2.0
IllusionRom-deprecated/android_platform_tools_idea
platform/xdebugger-impl/src/com/intellij/xdebugger/impl/evaluate/EvaluationInputComponent.java
1109
/* * Copyright 2000-2009 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.xdebugger.impl.evaluate; import com.intellij.xdebugger.impl.ui.XDebuggerEditorBase; import javax.swing.*; /** * @author nik */ public abstract class EvaluationInputComponent { private final String myTitle; protected EvaluationInputComponent(String title) { myTitle = title; } public String getTitle() { return myTitle; } protected abstract XDebuggerEditorBase getInputEditor(); public abstract void addComponent(JPanel contentPanel, JPanel resultPanel); }
apache-2.0
apurtell/hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-applications/hadoop-yarn-services/hadoop-yarn-services-core/src/main/java/org/apache/hadoop/yarn/service/api/records/KerberosPrincipal.java
4753
/* * 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.yarn.service.api.records; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import org.apache.hadoop.classification.InterfaceAudience; import org.apache.hadoop.classification.InterfaceStability; import javax.xml.bind.annotation.XmlElement; import java.io.Serializable; import java.util.Objects; /** * The kerberos principal of the service. */ @InterfaceAudience.Public @InterfaceStability.Unstable @ApiModel(description = "The kerberos principal of the service.") @JsonInclude(JsonInclude.Include.NON_NULL) public class KerberosPrincipal implements Serializable { private static final long serialVersionUID = -6431667195287650037L; @JsonProperty("principal_name") @XmlElement(name = "principal_name") private String principalName = null; @JsonProperty("keytab") @XmlElement(name = "keytab") private String keytab = null; public KerberosPrincipal principalName(String principalName) { this.principalName = principalName; return this; } /** * The principal name of the service. * * @return principalName **/ @ApiModelProperty(value = "The principal name of the service.") public String getPrincipalName() { return principalName; } public void setPrincipalName(String principalName) { this.principalName = principalName; } public KerberosPrincipal keytab(String keytab) { this.keytab = keytab; return this; } /** * The URI of the kerberos keytab. It supports hadoop supported schemes * like \&quot;hdfs\&quot; \&quot;file\&quot; \&quot;s3\&quot; * \&quot;viewfs\&quot; etc.If the URI starts with \&quot; * hdfs://\&quot; scheme, it indicates the path on hdfs where the keytab is * stored. The keytab will be localized by YARN and made available to AM in * its local directory. If the URI starts with \&quot;file://\&quot; * scheme, it indicates a path on the local host presumbaly installed by * admins upfront. * * @return keytab **/ @ApiModelProperty(value = "The URI of the kerberos keytab. It supports" + " Hadoop supported filesystem types like \"hdfs\", \"file\"," + " \"viewfs\", \"s3\" etc.If the URI starts with \"hdfs://\" scheme, " + "it indicates the path on hdfs where the keytab is stored. The " + "keytab will be localized by YARN and made available to AM in its local" + " directory. If the URI starts with \"file://\" scheme, it indicates a " + "path on the local host where the keytab is presumbaly installed by " + "admins upfront. ") public String getKeytab() { return keytab; } public void setKeytab(String keytab) { this.keytab = keytab; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } KerberosPrincipal kerberosPrincipal = (KerberosPrincipal) o; return Objects.equals(this.principalName, kerberosPrincipal .principalName) && Objects.equals(this.keytab, kerberosPrincipal.keytab); } @Override public int hashCode() { return Objects.hash(principalName, keytab); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class KerberosPrincipal {\n") .append(" principalName: ").append(toIndentedString(principalName)) .append("\n") .append(" keytab: ").append(toIndentedString(keytab)).append("\n") .append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
apache-2.0
jwren/intellij-community
python/testSrc/com/jetbrains/python/PyOptimizeImportsTest.java
11363
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.python; import com.intellij.codeInsight.actions.OptimizeImportsAction; import com.intellij.ide.DataManager; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.codeStyle.CommonCodeStyleSettings; import com.jetbrains.python.fixtures.PyTestCase; import com.jetbrains.python.formatter.PyCodeStyleSettings; import com.jetbrains.python.psi.LanguageLevel; import com.jetbrains.python.psi.PyImportStatementBase; import com.jetbrains.python.psi.impl.PyFileImpl; import org.jetbrains.annotations.NotNull; import java.util.List; public class PyOptimizeImportsTest extends PyTestCase { @NotNull private PyCodeStyleSettings getPythonCodeStyleSettings() { return getCodeStyleSettings().getCustomSettings(PyCodeStyleSettings.class); } public void testSimple() { doTest(); } public void testOneOfMultiple() { doTest(); } public void testImportStar() { doTest(); } public void testImportStarOneOfMultiple() { doTest(); } public void testTryExcept() { doTest(); } public void testFromFuture() { doTest(); } public void testUnresolved() { // PY-2201 doTest(); } public void testSuppressed() { // PY-5228 doTest(); } public void testSplit() { doTest(); } public void testOrderByType() { runWithAdditionalFileInLibDir( "sys.py", "", (__) -> runWithAdditionalFileInLibDir( "datetime.py", "", (___) -> doTest() ) ); } // PY-12018 public void testAlphabeticalOrder() { runWithAdditionalFileInLibDir( "sys.py", "", (__) -> runWithAdditionalFileInLibDir( "datetime.py", "", (___) -> doTest() ) ); } public void testInsertBlankLines() { // PY-8355 runWithAdditionalFileInLibDir( "sys.py", "", (__) -> runWithAdditionalFileInLibDir( "datetime.py", "", (___) -> doTest() ) ); } // PY-16351 public void testNoExtraBlankLineAfterImportBlock() { doMultiFileTest(); } // PY-18521 public void testImportsFromTypingUnusedInTypeComments() { doTest(); } // PY-18970 public void testLibraryRootInsideProject() { final String testName = getTestName(true); myFixture.copyDirectoryToProject(testName, ""); final VirtualFile libDir = myFixture.findFileInTempDir("lib"); assertNotNull(libDir); runWithAdditionalClassEntryInSdkRoots(libDir, () -> { myFixture.configureByFile("main.py"); OptimizeImportsAction.actionPerformedImpl(DataManager.getInstance().getDataContext(myFixture.getEditor().getContentComponent())); myFixture.checkResultByFile(testName + "/main.after.py"); }); } // PY-22656 public void testPyiStubInInterpreterPaths() { final String testName = getTestName(true); myFixture.copyDirectoryToProject(testName, ""); runWithAdditionalClassEntryInSdkRoots(testName + "/stubs", () -> { myFixture.configureByFile("main.py"); OptimizeImportsAction.actionPerformedImpl(DataManager.getInstance().getDataContext(myFixture.getEditor().getContentComponent())); myFixture.checkResultByFile(testName + "/main.after.py"); }); } // PY-18792 public void testDisableAlphabeticalOrder() { getPythonCodeStyleSettings().OPTIMIZE_IMPORTS_SORT_IMPORTS = false; runWithAdditionalFileInLibDir( "sys.py", "", (__) -> runWithAdditionalFileInLibDir( "datetime.py", "", (___) -> doTest() ) ); } // PY-18792, PY-19292 public void testOrderNamesInsideFromImport() { getPythonCodeStyleSettings().OPTIMIZE_IMPORTS_SORT_NAMES_IN_FROM_IMPORTS = true; doTest(); } // PY-18792, PY-19292 public void testOrderNamesInsightFromImportDoesntAffectAlreadyOrderedImports() { getPythonCodeStyleSettings().OPTIMIZE_IMPORTS_SORT_NAMES_IN_FROM_IMPORTS = true; doTest(); } // PY-18792, PY-14176 public void testJoinFromImportsForSameSource() { getPythonCodeStyleSettings().OPTIMIZE_IMPORTS_JOIN_FROM_IMPORTS_WITH_SAME_SOURCE = true; doTest(); } // PY-18792, PY-14176 public void testJoinFromImportsForSameSourceAndSortNames() { getPythonCodeStyleSettings().OPTIMIZE_IMPORTS_JOIN_FROM_IMPORTS_WITH_SAME_SOURCE = true; getPythonCodeStyleSettings().OPTIMIZE_IMPORTS_SORT_NAMES_IN_FROM_IMPORTS = true; doTest(); } // PY-18792, PY-14176 public void testJoinFromImportsDoesntAffectSingleImports() { getPythonCodeStyleSettings().OPTIMIZE_IMPORTS_JOIN_FROM_IMPORTS_WITH_SAME_SOURCE = true; doTest(); } // PY-18792, PY-14176 public void testJoinFromImportsIgnoresStarImports() { getPythonCodeStyleSettings().OPTIMIZE_IMPORTS_JOIN_FROM_IMPORTS_WITH_SAME_SOURCE = true; doTest(); } // PY-18792, PY-14176 public void testJoinFromImportsAndRelativeImports() { getPythonCodeStyleSettings().OPTIMIZE_IMPORTS_JOIN_FROM_IMPORTS_WITH_SAME_SOURCE = true; doTest(); } // PY-18792 public void testSortImportsByNameFirstWithinGroup() { getPythonCodeStyleSettings().OPTIMIZE_IMPORTS_SORT_BY_TYPE_FIRST = false; doTest(); } // PY-20159 public void testCaseInsensitiveOrderOfImports() { getPythonCodeStyleSettings().OPTIMIZE_IMPORTS_CASE_INSENSITIVE_ORDER = true; doTest(); } // PY-20159 public void testCaseInsensitiveOrderOfNamesInsideFromImports() { getPythonCodeStyleSettings().OPTIMIZE_IMPORTS_SORT_NAMES_IN_FROM_IMPORTS = true; getPythonCodeStyleSettings().OPTIMIZE_IMPORTS_CASE_INSENSITIVE_ORDER = true; doTest(); } // PY-19674 public void testUnresolvedRelativeImportsShouldBeInProjectGroup() { final String testName = getTestName(true); myFixture.copyDirectoryToProject(testName, ""); myFixture.configureByFile("pkg/main.py"); OptimizeImportsAction.actionPerformedImpl(DataManager.getInstance().getDataContext(myFixture.getEditor().getContentComponent())); myFixture.checkResultByFile(testName + "/pkg/main.after.py"); } public void testExtractImportBlockWithIntermediateComments() { myFixture.configureByFile(getTestName(true) + ".py"); final PyFileImpl file = assertInstanceOf(myFixture.getFile(), PyFileImpl.class); final List<PyImportStatementBase> block = file.getImportBlock(); assertSize(2, block); } public void testExtractImportBlockNoWhitespaceAtEnd() { myFixture.configureByFile(getTestName(true) + ".py"); final PyFileImpl file = assertInstanceOf(myFixture.getFile(), PyFileImpl.class); final List<PyImportStatementBase> block = file.getImportBlock(); assertSize(2, block); } // PY-19836 public void testSameNameImportedWithDifferentAliasesInline() { getPythonCodeStyleSettings().OPTIMIZE_IMPORTS_SORT_NAMES_IN_FROM_IMPORTS = true; doTest(); } // PY-19836 public void testSameNameImportedWithDifferentAliases() { doTest(); } // PY-19836 public void testSameModuleImportedWithDifferentAliases() { doTest(); } // PY-18972 public void testReferencesInFStringLiterals() { runWithLanguageLevel( LanguageLevel.PYTHON36, () -> runWithAdditionalFileInLibDir( "sys.py", "", (__) -> runWithAdditionalFileInLibDir( "datetime.py", "", (___) -> doTest() ) ) ); } // PY-22355 public void testParenthesesAndTrailingCommaInFromImports() { getPythonCodeStyleSettings().OPTIMIZE_IMPORTS_JOIN_FROM_IMPORTS_WITH_SAME_SOURCE = true; getPythonCodeStyleSettings().FROM_IMPORT_WRAPPING = CommonCodeStyleSettings.WRAP_ALWAYS; getPythonCodeStyleSettings().FROM_IMPORT_PARENTHESES_FORCE_IF_MULTILINE = true; getPythonCodeStyleSettings().FROM_IMPORT_NEW_LINE_AFTER_LEFT_PARENTHESIS = true; getPythonCodeStyleSettings().FROM_IMPORT_NEW_LINE_BEFORE_RIGHT_PARENTHESIS = true; getPythonCodeStyleSettings().FROM_IMPORT_TRAILING_COMMA_IF_MULTILINE = true; doTest(); } // PY-19837 public void testCommentsHandling() { getPythonCodeStyleSettings().OPTIMIZE_IMPORTS_JOIN_FROM_IMPORTS_WITH_SAME_SOURCE = true; getPythonCodeStyleSettings().OPTIMIZE_IMPORTS_SORT_NAMES_IN_FROM_IMPORTS = true; doTest(); } // PY-19837 public void testKeepLicenseComment() { getPythonCodeStyleSettings().OPTIMIZE_IMPORTS_JOIN_FROM_IMPORTS_WITH_SAME_SOURCE = true; doTest(); } // PY-23035 public void testCommentsInsideParenthesesInCombinedFromImports() { getPythonCodeStyleSettings().OPTIMIZE_IMPORTS_JOIN_FROM_IMPORTS_WITH_SAME_SOURCE = true; doTest(); } // PY-23086 public void testTrailingCommentsInCombinedFromImports() { getPythonCodeStyleSettings().OPTIMIZE_IMPORTS_JOIN_FROM_IMPORTS_WITH_SAME_SOURCE = true; doTest(); } // PY-23104 public void testMultilineImportElementsInCombinedFromImports() { getPythonCodeStyleSettings().OPTIMIZE_IMPORTS_JOIN_FROM_IMPORTS_WITH_SAME_SOURCE = true; doTest(); } // PY-23125 public void testStackDanglingCommentsAtEnd() { doTest(); } // PY-23578 public void testBlankLineBetweenDocstringAndFirstImportPreserved() { doTest(); } // PY-23636 public void testBlankLineBetweenEncodingDeclarationAndFirstImportPreserved() { doTest(); } // PY-25567 public void testExistingParenthesesInReorderedFromImport() { getPythonCodeStyleSettings().OPTIMIZE_IMPORTS_SORT_NAMES_IN_FROM_IMPORTS = true; doTest(); } // PY-25567 public void testExistingParenthesesInCombinedFromImports() { getPythonCodeStyleSettings().OPTIMIZE_IMPORTS_JOIN_FROM_IMPORTS_WITH_SAME_SOURCE = true; doTest(); } // PY-20100 public void testSplittingOfFromImports() { getPythonCodeStyleSettings().OPTIMIZE_IMPORTS_ALWAYS_SPLIT_FROM_IMPORTS = true; doTest(); } // PY-23475 public void testModuleLevelDunder() { getPythonCodeStyleSettings().OPTIMIZE_IMPORTS_JOIN_FROM_IMPORTS_WITH_SAME_SOURCE = true; doTest(); } // PY-23475 public void testModuleLevelDunderWithImportFromFutureAbove() { getPythonCodeStyleSettings().OPTIMIZE_IMPORTS_JOIN_FROM_IMPORTS_WITH_SAME_SOURCE = true; doTest(); } // PY-23475 public void testModuleLevelDunderWithImportFromFutureBelow() { doTest(); } // PY-23475 public void testImportFromFutureWithRegularImports() { doTest(); } private void doMultiFileTest() { final String testName = getTestName(true); myFixture.copyDirectoryToProject(testName, ""); myFixture.configureByFile("main.py"); OptimizeImportsAction.actionPerformedImpl(DataManager.getInstance().getDataContext(myFixture.getEditor().getContentComponent())); myFixture.checkResultByFile(testName + "/main.after.py"); } private void doTest() { myFixture.configureByFile(getTestName(true) + ".py"); OptimizeImportsAction.actionPerformedImpl(DataManager.getInstance().getDataContext(myFixture.getEditor().getContentComponent())); myFixture.checkResultByFile(getTestName(true) + ".after.py"); } @Override protected String getTestDataPath() { return super.getTestDataPath() + "/optimizeImports"; } }
apache-2.0
nmcl/scratch
graalvm/transactions/fork/narayana/XTS/WS-T/dev/src/com/arjuna/webservices11/wsba/client/WSBAClient.java
12983
package com.arjuna.webservices11.wsba.client; import com.arjuna.webservices11.util.PrivilegedServiceFactory; import com.arjuna.webservices11.util.PrivilegedServiceHelper; import com.arjuna.webservices11.wsaddr.AddressingHelper; import org.jboss.ws.api.addressing.MAP; import org.oasis_open.docs.ws_tx.wsba._2006._06.*; import javax.xml.ws.BindingProvider; import javax.xml.ws.soap.AddressingFeature; import javax.xml.ws.wsaddressing.W3CEndpointReference; import java.util.Map; /** * Created by IntelliJ IDEA. * User: adinn * Date: Oct 7, 2007 * Time: 3:14:28 PM * To change this template use File | Settings | File Templates. */ public class WSBAClient { // TODO -- do we really need a thread local here or can we just use one service? /** * thread local which maintains a per thread participant completion coordinator service instance */ private static ThreadLocal<BusinessAgreementWithParticipantCompletionCoordinatorService> participantCompletionCoordinatorService = new ThreadLocal<BusinessAgreementWithParticipantCompletionCoordinatorService>(); /** * thread local which maintains a per thread participant completion participant service instance */ private static ThreadLocal<BusinessAgreementWithParticipantCompletionParticipantService> participantCompletionParticipantService = new ThreadLocal<BusinessAgreementWithParticipantCompletionParticipantService>(); /** * thread local which maintains a per thread coordinator completion coordinator service instance */ private static ThreadLocal<BusinessAgreementWithCoordinatorCompletionCoordinatorService> coordinatorCompletionCoordinatorService = new ThreadLocal<BusinessAgreementWithCoordinatorCompletionCoordinatorService>(); /** * thread local which maintains a per thread coordinator completion participant service instance */ private static ThreadLocal<BusinessAgreementWithCoordinatorCompletionParticipantService> coordinatorCompletionParticipantService = new ThreadLocal<BusinessAgreementWithCoordinatorCompletionParticipantService>(); /** * fetch a participant completion coordinator service unique to the current thread * @return */ private static synchronized BusinessAgreementWithParticipantCompletionCoordinatorService getParticipantCompletionCoordinatorService() { if (participantCompletionCoordinatorService.get() == null) { participantCompletionCoordinatorService.set(PrivilegedServiceFactory.getInstance( BusinessAgreementWithParticipantCompletionCoordinatorService.class).getService()); } return participantCompletionCoordinatorService.get(); } /** * fetch a participant completion participant service unique to the current thread * @return */ private static synchronized BusinessAgreementWithParticipantCompletionParticipantService getParticipantCompletionParticipantService() { if (participantCompletionParticipantService.get() == null) { participantCompletionParticipantService.set(PrivilegedServiceFactory.getInstance( BusinessAgreementWithParticipantCompletionParticipantService.class).getService()); } return participantCompletionParticipantService.get(); } /** * fetch a coordinator completion coordinator service unique to the current thread * @return */ private static synchronized BusinessAgreementWithCoordinatorCompletionCoordinatorService getCoordinatorCompletionCoordinatorService() { if (coordinatorCompletionCoordinatorService.get() == null) { coordinatorCompletionCoordinatorService.set(PrivilegedServiceFactory.getInstance( BusinessAgreementWithCoordinatorCompletionCoordinatorService.class).getService()); } return coordinatorCompletionCoordinatorService.get(); } /** * fetch a coordinator completion participant service unique to the current thread * @return */ private static synchronized BusinessAgreementWithCoordinatorCompletionParticipantService getCoordinatorCompletionParticipantService() { if (coordinatorCompletionParticipantService.get() == null) { coordinatorCompletionParticipantService.set(PrivilegedServiceFactory.getInstance( BusinessAgreementWithCoordinatorCompletionParticipantService.class).getService()); } return coordinatorCompletionParticipantService.get(); } // get ports where we HAVE an endpoint to create the port from public static BusinessAgreementWithParticipantCompletionCoordinatorPortType getParticipantCompletionCoordinatorPort(W3CEndpointReference endpointReference, String action, MAP map) { final BusinessAgreementWithParticipantCompletionCoordinatorService service = getParticipantCompletionCoordinatorService(); final BusinessAgreementWithParticipantCompletionCoordinatorPortType port = PrivilegedServiceHelper.getInstance().getPort(service, endpointReference, BusinessAgreementWithParticipantCompletionCoordinatorPortType.class, new AddressingFeature(true, true)); BindingProvider bindingProvider = (BindingProvider)port; configureEndpointPort(bindingProvider, action, map); return port; } public static BusinessAgreementWithParticipantCompletionParticipantPortType getParticipantCompletionParticipantPort(W3CEndpointReference endpointReference, String action, MAP map) { final BusinessAgreementWithParticipantCompletionParticipantService service = getParticipantCompletionParticipantService(); final BusinessAgreementWithParticipantCompletionParticipantPortType port = PrivilegedServiceHelper.getInstance().getPort(service, endpointReference, BusinessAgreementWithParticipantCompletionParticipantPortType.class, new AddressingFeature(true, true)); BindingProvider bindingProvider = (BindingProvider)port; configureEndpointPort(bindingProvider, action, map); return port; } public static BusinessAgreementWithCoordinatorCompletionCoordinatorPortType getCoordinatorCompletionCoordinatorPort(W3CEndpointReference endpointReference, String action, MAP map) { final BusinessAgreementWithCoordinatorCompletionCoordinatorService service = getCoordinatorCompletionCoordinatorService(); final BusinessAgreementWithCoordinatorCompletionCoordinatorPortType port = PrivilegedServiceHelper.getInstance().getPort(service, endpointReference, BusinessAgreementWithCoordinatorCompletionCoordinatorPortType.class, new AddressingFeature(true, true)); BindingProvider bindingProvider = (BindingProvider)port; configureEndpointPort(bindingProvider, action, map); return port; } public static BusinessAgreementWithCoordinatorCompletionParticipantPortType getCoordinatorCompletionParticipantPort(W3CEndpointReference endpointReference, String action, MAP map) { final BusinessAgreementWithCoordinatorCompletionParticipantService service = getCoordinatorCompletionParticipantService(); final BusinessAgreementWithCoordinatorCompletionParticipantPortType port = PrivilegedServiceHelper.getInstance().getPort(service, endpointReference, BusinessAgreementWithCoordinatorCompletionParticipantPortType.class, new AddressingFeature(true, true)); BindingProvider bindingProvider = (BindingProvider)port; configureEndpointPort(bindingProvider, action, map); return port; } // get ports where we have NO endpoint to create the port from public static BusinessAgreementWithParticipantCompletionCoordinatorPortType getParticipantCompletionCoordinatorPort(String action, MAP map) { final BusinessAgreementWithParticipantCompletionCoordinatorService service = getParticipantCompletionCoordinatorService(); final BusinessAgreementWithParticipantCompletionCoordinatorPortType port = PrivilegedServiceHelper.getInstance().getPort(service, BusinessAgreementWithParticipantCompletionCoordinatorPortType.class, new AddressingFeature(true, true)); BindingProvider bindingProvider = (BindingProvider)port; configurePort(bindingProvider, action, map); return port; } public static BusinessAgreementWithParticipantCompletionParticipantPortType getParticipantCompletionParticipantPort(String action, MAP map) { final BusinessAgreementWithParticipantCompletionParticipantService service = getParticipantCompletionParticipantService(); final BusinessAgreementWithParticipantCompletionParticipantPortType port = PrivilegedServiceHelper.getInstance().getPort(service, BusinessAgreementWithParticipantCompletionParticipantPortType.class, new AddressingFeature(true, true)); BindingProvider bindingProvider = (BindingProvider)port; configurePort(bindingProvider, action, map); return port; } public static BusinessAgreementWithCoordinatorCompletionParticipantPortType getCoordinatorCompletionParticipantPort(String action, MAP map) { final BusinessAgreementWithCoordinatorCompletionParticipantService service = getCoordinatorCompletionParticipantService(); final BusinessAgreementWithCoordinatorCompletionParticipantPortType port = PrivilegedServiceHelper.getInstance().getPort(service, BusinessAgreementWithCoordinatorCompletionParticipantPortType.class, new AddressingFeature(true, true)); BindingProvider bindingProvider = (BindingProvider)port; configurePort(bindingProvider, action, map); return port; } public static BusinessAgreementWithCoordinatorCompletionCoordinatorPortType getCoordinatorCompletionCoordinatorPort(String action, MAP map) { final BusinessAgreementWithCoordinatorCompletionCoordinatorService service = getCoordinatorCompletionCoordinatorService(); final BusinessAgreementWithCoordinatorCompletionCoordinatorPortType port = PrivilegedServiceHelper.getInstance().getPort(service, BusinessAgreementWithCoordinatorCompletionCoordinatorPortType.class, new AddressingFeature(true, true)); BindingProvider bindingProvider = (BindingProvider)port; configurePort(bindingProvider, action, map); return port; } private static void configureEndpointPort(BindingProvider bindingProvider, String action, MAP map) { /* * we no longer have to add the JaxWS WSAddressingClientHandler because we can specify the WSAddressing feature List<Handler> customHandlerChain = new ArrayList<Handler>(); customHandlerChain.add(new WSAddressingClientHandler()); bindingProvider.getBinding().setHandlerChain(customHandlerChain); */ Map<String, Object> requestContext = bindingProvider.getRequestContext(); MAP requestMap = AddressingHelper.outboundMap(requestContext); map.setAction(action); AddressingHelper.installCallerProperties(map, requestMap); AddressingHelper.configureRequestContext(requestContext, requestMap.getTo(), action); } private static void configurePort(BindingProvider bindingProvider, String action, MAP map) { /* * we no longer have to add the JaxWS WSAddressingClientHandler because we can specify the WSAddressing feature List<Handler> customHandlerChain = new ArrayList<Handler>(); customHandlerChain.add(new WSAddressingClientHandler()); bindingProvider.getBinding().setHandlerChain(customHandlerChain); */ Map<String, Object> requestContext = bindingProvider.getRequestContext(); map.setAction(action); AddressingHelper.configureRequestContext(requestContext, map, map.getTo(), action); } }
apache-2.0
shrinkwrap/resolver
maven/impl-maven-archive/src/it/jar-without-resources/src/main/java/test/nested/NestedJarClass.java
438
package test.nested; import java.nio.charset.Charset; import org.apache.commons.codec.binary.Base64; import test.JarClass; // this file greets in Base64 public class NestedJarClass extends JarClass { public static final String GREETINGS = "Hello from MavenImporter imported nested class"; @Override public String greet() { return Base64.encodeBase64String(GREETINGS.getBytes(Charset.defaultCharset())); } }
apache-2.0
jwren/intellij-community
plugins/ui-designer/src/com/intellij/uiDesigner/designSurface/HorzInsertFeedbackPainter.java
1163
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.uiDesigner.designSurface; import com.intellij.util.ui.PlatformColors; import java.awt.*; class HorzInsertFeedbackPainter implements FeedbackPainter { public static HorzInsertFeedbackPainter INSTANCE = new HorzInsertFeedbackPainter(); @Override public void paintFeedback(Graphics2D g2d, Rectangle rc) { g2d.setColor(PlatformColors.BLUE); g2d.setStroke(new BasicStroke(1.5f)); int midY = (int)rc.getCenterY(); int right = rc.x + rc.width - 1; int bottom = rc.y + rc.height - 1; g2d.drawLine(rc.x, rc.y, GridInsertLocation.INSERT_ARROW_SIZE, midY); g2d.drawLine(rc.x, bottom, GridInsertLocation.INSERT_ARROW_SIZE, midY); g2d.drawLine(GridInsertLocation.INSERT_ARROW_SIZE, midY, right - GridInsertLocation.INSERT_ARROW_SIZE, midY); g2d.drawLine(right, rc.y, rc.x+rc.width-GridInsertLocation.INSERT_ARROW_SIZE, midY); g2d.drawLine(right, bottom, right-GridInsertLocation.INSERT_ARROW_SIZE, midY); } }
apache-2.0
vpapaioannou/Musketeer
src/translation/hadoop_templates/JoinMapVariables.java
40
private boolean is_left_rel = false;
apache-2.0
kristinehahn/drill
contrib/storage-hive/core/src/test/java/org/apache/drill/exec/store/hive/HiveTestDataGenerator.java
15184
/** * 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.drill.exec.store.hive; import java.io.File; import java.io.PrintWriter; import java.sql.Date; import java.sql.Timestamp; import java.util.Map; import org.apache.commons.io.FileUtils; import org.apache.drill.BaseTestQuery; import org.apache.drill.common.exceptions.DrillException; import org.apache.drill.exec.store.StoragePluginRegistry; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.hive.conf.HiveConf; import org.apache.hadoop.hive.conf.HiveConf.ConfVars; import org.apache.hadoop.hive.ql.Driver; import org.apache.hadoop.hive.ql.session.SessionState; import com.google.common.collect.Maps; import static org.apache.drill.BaseTestQuery.getTempDir; import static org.apache.drill.exec.hive.HiveTestUtilities.executeQuery; public class HiveTestDataGenerator { private static final String HIVE_TEST_PLUGIN_NAME = "hive"; private static HiveTestDataGenerator instance; private final String dbDir; private final String whDir; private final Map<String, String> config; public static synchronized HiveTestDataGenerator getInstance() throws Exception { if (instance == null) { final String dbDir = getTempDir("metastore_db"); final String whDir = getTempDir("warehouse"); instance = new HiveTestDataGenerator(dbDir, whDir); instance.generateTestData(); } return instance; } private HiveTestDataGenerator(final String dbDir, final String whDir) { this.dbDir = dbDir; this.whDir = whDir; config = Maps.newHashMap(); config.put("hive.metastore.uris", ""); config.put("javax.jdo.option.ConnectionURL", String.format("jdbc:derby:;databaseName=%s;create=true", dbDir)); config.put("hive.metastore.warehouse.dir", whDir); config.put(FileSystem.FS_DEFAULT_NAME_KEY, "file:///"); } /** * Add Hive test storage plugin to the given plugin registry. * @throws Exception */ public void addHiveTestPlugin(final StoragePluginRegistry pluginRegistry) throws Exception { HiveStoragePluginConfig pluginConfig = new HiveStoragePluginConfig(config); pluginConfig.setEnabled(true); pluginRegistry.createOrUpdate(HIVE_TEST_PLUGIN_NAME, pluginConfig, true); } /** * Update the current HiveStoragePlugin in given plugin registry with given <i>configOverride</i>. * * @param configOverride * @throws DrillException if fails to update or no Hive plugin currently exists in given plugin registry. */ public void updatePluginConfig(final StoragePluginRegistry pluginRegistry, Map<String, String> configOverride) throws DrillException { HiveStoragePlugin storagePlugin = (HiveStoragePlugin) pluginRegistry.getPlugin(HIVE_TEST_PLUGIN_NAME); if (storagePlugin == null) { throw new DrillException( "Hive test storage plugin doesn't exist. Add a plugin using addHiveTestPlugin()"); } HiveStoragePluginConfig newPluginConfig = storagePlugin.getConfig(); newPluginConfig.getHiveConfigOverride().putAll(configOverride); pluginRegistry.createOrUpdate(HIVE_TEST_PLUGIN_NAME, newPluginConfig, true); } /** * Delete the Hive test plugin from registry. */ public void deleteHiveTestPlugin(final StoragePluginRegistry pluginRegistry) { pluginRegistry.deletePlugin(HIVE_TEST_PLUGIN_NAME); } private void generateTestData() throws Exception { HiveConf conf = new HiveConf(SessionState.class); conf.set("javax.jdo.option.ConnectionURL", String.format("jdbc:derby:;databaseName=%s;create=true", dbDir)); conf.set(FileSystem.FS_DEFAULT_NAME_KEY, "file:///"); conf.set("hive.metastore.warehouse.dir", whDir); conf.set("mapred.job.tracker", "local"); conf.set(ConfVars.SCRATCHDIR.varname, getTempDir("scratch_dir")); conf.set(ConfVars.LOCALSCRATCHDIR.varname, getTempDir("local_scratch_dir")); conf.set(ConfVars.DYNAMICPARTITIONINGMODE.varname, "nonstrict"); SessionState ss = new SessionState(conf); SessionState.start(ss); Driver hiveDriver = new Driver(conf); // generate (key, value) test data String testDataFile = generateTestDataFile(); // Create a (key, value) schema table with Text SerDe which is available in hive-serdes.jar executeQuery(hiveDriver, "CREATE TABLE IF NOT EXISTS default.kv(key INT, value STRING) " + "ROW FORMAT DELIMITED FIELDS TERMINATED BY ',' STORED AS TEXTFILE"); executeQuery(hiveDriver, "LOAD DATA LOCAL INPATH '" + testDataFile + "' OVERWRITE INTO TABLE default.kv"); // Create a (key, value) schema table in non-default database with RegexSerDe which is available in hive-contrib.jar // Table with RegExSerde is expected to have columns of STRING type only. executeQuery(hiveDriver, "CREATE DATABASE IF NOT EXISTS db1"); executeQuery(hiveDriver, "CREATE TABLE db1.kv_db1(key STRING, value STRING) " + "ROW FORMAT SERDE 'org.apache.hadoop.hive.contrib.serde2.RegexSerDe' " + "WITH SERDEPROPERTIES (" + " \"input.regex\" = \"([0-9]*), (.*_[0-9]*)\", " + " \"output.format.string\" = \"%1$s, %2$s\"" + ") "); executeQuery(hiveDriver, "INSERT INTO TABLE db1.kv_db1 SELECT * FROM default.kv"); // Create an Avro format based table backed by schema in a separate file final String avroCreateQuery = String.format("CREATE TABLE db1.avro " + "ROW FORMAT SERDE 'org.apache.hadoop.hive.serde2.avro.AvroSerDe' " + "STORED AS INPUTFORMAT 'org.apache.hadoop.hive.ql.io.avro.AvroContainerInputFormat' " + "OUTPUTFORMAT 'org.apache.hadoop.hive.ql.io.avro.AvroContainerOutputFormat' " + "TBLPROPERTIES ('avro.schema.url'='file:///%s')", BaseTestQuery.getPhysicalFileFromResource("avro_test_schema.json").replace('\\', '/')); executeQuery(hiveDriver, avroCreateQuery); executeQuery(hiveDriver, "INSERT INTO TABLE db1.avro SELECT * FROM default.kv"); executeQuery(hiveDriver, "USE default"); // create a table with no data executeQuery(hiveDriver, "CREATE TABLE IF NOT EXISTS empty_table(a INT, b STRING)"); // delete the table location of empty table File emptyTableLocation = new File(whDir, "empty_table"); if (emptyTableLocation.exists()) { FileUtils.forceDelete(emptyTableLocation); } // create a Hive table that has columns with data types which are supported for reading in Drill. testDataFile = generateAllTypesDataFile(); executeQuery(hiveDriver, "CREATE TABLE IF NOT EXISTS readtest (" + " binary_field BINARY," + " boolean_field BOOLEAN," + " tinyint_field TINYINT," + " decimal0_field DECIMAL," + " decimal9_field DECIMAL(6, 2)," + " decimal18_field DECIMAL(15, 5)," + " decimal28_field DECIMAL(23, 1)," + " decimal38_field DECIMAL(30, 3)," + " double_field DOUBLE," + " float_field FLOAT," + " int_field INT," + " bigint_field BIGINT," + " smallint_field SMALLINT," + " string_field STRING," + " varchar_field VARCHAR(50)," + " timestamp_field TIMESTAMP," + " date_field DATE" + ") PARTITIONED BY (" + " binary_part BINARY," + " boolean_part BOOLEAN," + " tinyint_part TINYINT," + " decimal0_part DECIMAL," + " decimal9_part DECIMAL(6, 2)," + " decimal18_part DECIMAL(15, 5)," + " decimal28_part DECIMAL(23, 1)," + " decimal38_part DECIMAL(30, 3)," + " double_part DOUBLE," + " float_part FLOAT," + " int_part INT," + " bigint_part BIGINT," + " smallint_part SMALLINT," + " string_part STRING," + " varchar_part VARCHAR(50)," + " timestamp_part TIMESTAMP," + " date_part DATE" + ") ROW FORMAT DELIMITED FIELDS TERMINATED BY ',' " + "TBLPROPERTIES ('serialization.null.format'='') " ); // Add a partition to table 'readtest' executeQuery(hiveDriver, "ALTER TABLE readtest ADD IF NOT EXISTS PARTITION ( " + " binary_part='binary', " + " boolean_part='true', " + " tinyint_part='64', " + " decimal0_part='36.9', " + " decimal9_part='36.9', " + " decimal18_part='3289379872.945645', " + " decimal28_part='39579334534534.35345', " + " decimal38_part='363945093845093890.9', " + " double_part='8.345', " + " float_part='4.67', " + " int_part='123456', " + " bigint_part='234235', " + " smallint_part='3455', " + " string_part='string', " + " varchar_part='varchar', " + " timestamp_part='2013-07-05 17:01:00', " + " date_part='2013-07-05')" ); // Add a second partition to table 'readtest' which contains the same values as the first partition except // for boolean_part partition column executeQuery(hiveDriver, "ALTER TABLE readtest ADD IF NOT EXISTS PARTITION ( " + " binary_part='binary', " + " boolean_part='false', " + " tinyint_part='64', " + " decimal0_part='36.9', " + " decimal9_part='36.9', " + " decimal18_part='3289379872.945645', " + " decimal28_part='39579334534534.35345', " + " decimal38_part='363945093845093890.9', " + " double_part='8.345', " + " float_part='4.67', " + " int_part='123456', " + " bigint_part='234235', " + " smallint_part='3455', " + " string_part='string', " + " varchar_part='varchar', " + " timestamp_part='2013-07-05 17:01:00', " + " date_part='2013-07-05')" ); // Load data into table 'readtest' executeQuery(hiveDriver, String.format("LOAD DATA LOCAL INPATH '%s' OVERWRITE INTO TABLE default.readtest PARTITION (" + " binary_part='binary', " + " boolean_part='true', " + " tinyint_part='64', " + " decimal0_part='36.9', " + " decimal9_part='36.9', " + " decimal18_part='3289379872.945645', " + " decimal28_part='39579334534534.35345', " + " decimal38_part='363945093845093890.9', " + " double_part='8.345', " + " float_part='4.67', " + " int_part='123456', " + " bigint_part='234235', " + " smallint_part='3455', " + " string_part='string', " + " varchar_part='varchar', " + " timestamp_part='2013-07-05 17:01:00', " + " date_part='2013-07-05')", testDataFile)); // create a table that has all Hive types. This is to test how hive tables metadata is populated in // Drill's INFORMATION_SCHEMA. executeQuery(hiveDriver, "CREATE TABLE IF NOT EXISTS infoschematest(" + "booleanType BOOLEAN, " + "tinyintType TINYINT, " + "smallintType SMALLINT, " + "intType INT, " + "bigintType BIGINT, " + "floatType FLOAT, " + "doubleType DOUBLE, " + "dateType DATE, " + "timestampType TIMESTAMP, " + "binaryType BINARY, " + "decimalType DECIMAL(38, 2), " + "stringType STRING, " + "varCharType VARCHAR(20), " + "listType ARRAY<STRING>, " + "mapType MAP<STRING,INT>, " + "structType STRUCT<sint:INT,sboolean:BOOLEAN,sstring:STRING>, " + "uniontypeType UNIONTYPE<int, double, array<string>>)" ); // create a Hive view to test how its metadata is populated in Drill's INFORMATION_SCHEMA executeQuery(hiveDriver, "CREATE VIEW IF NOT EXISTS hiveview AS SELECT * FROM kv"); executeQuery(hiveDriver, "CREATE TABLE IF NOT EXISTS " + "partition_pruning_test_loadtable(a DATE, b TIMESTAMP, c INT, d INT, e INT) " + "ROW FORMAT DELIMITED FIELDS TERMINATED BY ',' STORED AS TEXTFILE"); executeQuery(hiveDriver, String.format("LOAD DATA LOCAL INPATH '%s' INTO TABLE partition_pruning_test_loadtable", generateTestDataFileForPartitionInput())); // create partitioned hive table to test partition pruning executeQuery(hiveDriver, "CREATE TABLE IF NOT EXISTS partition_pruning_test(a DATE, b TIMESTAMP) "+ "partitioned by (c INT, d INT, e INT) ROW FORMAT DELIMITED FIELDS TERMINATED BY ',' STORED AS TEXTFILE"); executeQuery(hiveDriver, "INSERT OVERWRITE TABLE partition_pruning_test PARTITION(c, d, e) " + "SELECT a, b, c, d, e FROM partition_pruning_test_loadtable"); executeQuery(hiveDriver, "DROP TABLE partition_pruning_test_loadtable"); ss.close(); } private File getTempFile() throws Exception { return java.nio.file.Files.createTempFile("drill-hive-test", ".txt").toFile(); } private String generateTestDataFile() throws Exception { final File file = getTempFile(); PrintWriter printWriter = new PrintWriter(file); for (int i=1; i<=5; i++) { printWriter.println (String.format("%d, key_%d", i, i)); } printWriter.close(); return file.getPath(); } private String generateTestDataFileForPartitionInput() throws Exception { final File file = getTempFile(); PrintWriter printWriter = new PrintWriter(file); String partValues[] = {"1", "2", "null"}; for(int c = 0; c < partValues.length; c++) { for(int d = 0; d < partValues.length; d++) { for(int e = 0; e < partValues.length; e++) { for (int i = 1; i <= 5; i++) { Date date = new Date(System.currentTimeMillis()); Timestamp ts = new Timestamp(System.currentTimeMillis()); printWriter.printf("%s,%s,%s,%s,%s", date.toString(), ts.toString(), partValues[c], partValues[d], partValues[e]); printWriter.println(); } } } } printWriter.close(); return file.getPath(); } private String generateAllTypesDataFile() throws Exception { File file = getTempFile(); PrintWriter printWriter = new PrintWriter(file); printWriter.println("YmluYXJ5ZmllbGQ=,false,34,65.99,2347.923,2758725827.9999,29375892739852.7689," + "89853749534593985.7834783,8.345,4.67,123456,234235,3455,stringfield,varcharfield," + "2013-07-05 17:01:00,2013-07-05"); printWriter.println(",,,,,,,,,,,,,,,,"); printWriter.close(); return file.getPath(); } }
apache-2.0
nmcl/scratch
graalvm/transactions/fork/narayana/ArjunaJTA/jta/classes/com/arjuna/ats/internal/jta/tools/osb/mbean/jta/CommitMarkableResourceRecordBean.java
4700
/* * Copyright 2013, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. * See the copyright.txt in the distribution for a * full listing of individual contributors. * This copyrighted material is made available to anyone wishing to use, * modify, copy, or redistribute it subject to the terms and conditions * of the GNU Lesser General Public License, v. 2.1. * This program is distributed in the hope that it will be useful, but WITHOUT A * 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, * v.2.1 along with this distribution; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. * * (C) 2013 * @author JBoss Inc. */ package com.arjuna.ats.internal.jta.tools.osb.mbean.jta; import javax.management.MBeanException; import javax.transaction.xa.XAResource; import com.arjuna.ats.arjuna.coordinator.AbstractRecord; import com.arjuna.ats.arjuna.tools.osb.mbean.*; import com.arjuna.ats.internal.jta.resources.arjunacore.CommitMarkableResourceRecord; import com.arjuna.ats.internal.jta.xa.XID; import com.arjuna.ats.jta.xa.XATxConverter; import com.arjuna.ats.jta.xa.XidImple; /** * MBean implementation of a transaction participant corresponding to a JTA * XAResource */ /** * @deprecated as of 5.0.5.Final In a subsequent release we will change packages names in order to * provide a better separation between public and internal classes. */ @Deprecated // in order to provide a better separation between public and internal classes. public class CommitMarkableResourceRecordBean extends LogRecordWrapper implements CommitMarkableResourceRecordBeanMBean { String className; String eisProductName; String eisProductVersion; String jndiName; int timeout; XidImple xidImple; int heuristic; public CommitMarkableResourceRecordBean(UidWrapper w) { super(w.getUid()); init(); } public CommitMarkableResourceRecordBean(ActionBean parent, AbstractRecord rec, ParticipantStatus listType) { super(parent, rec, listType); init(); // xares = new JTAXAResourceRecordWrapper(rec.order()); } private void init() { jndiName = getUid().stringForm(); className = "unavailable"; eisProductName = "unavailable"; eisProductVersion = "unavailable"; timeout = 0; heuristic = -1; xidImple = new XidImple(new XID()); } public boolean activate() { boolean ok = super.activate(); XAResource xares = (XAResource) rec.value(); className = rec.getClass().getName(); if (rec instanceof CommitMarkableResourceRecord) { CommitMarkableResourceRecord xarec = (CommitMarkableResourceRecord) rec; eisProductName = xarec.getProductName(); eisProductVersion = xarec.getProductVersion(); jndiName = xarec.getJndiName(); heuristic = xarec.getHeuristic(); } if (xares != null) { className = xares.getClass().getName(); try { timeout = xares.getTransactionTimeout(); } catch (Exception e) { } } return ok; } public String getClassName() { return className; } public String getEisProductName() { return eisProductName; } public String getEisProductVersion() { return eisProductVersion; } @Override public int getTimeout() { return timeout; } @Override public String getJndiName() { return jndiName; } @Override public String getHeuristicStatus() { String hs = super.getHeuristicStatus(); if (heuristic != -1 && HeuristicStatus.UNKNOWN.name().equals(hs)) { hs = HeuristicStatus.intToStatus(heuristic).name(); } return hs; } @Override public byte[] getGlobalTransactionId() { return xidImple.getGlobalTransactionId(); } @Override public byte[] getBranchQualifier() { return xidImple.getBranchQualifier(); } @Override public int getFormatId() { return xidImple.getFormatId(); } @Override public String getNodeName() { return XATxConverter.getNodeName(xidImple.getXID()); } @Override public int getHeuristicValue() { return heuristic; } @Override public boolean forget() { if (rec instanceof CommitMarkableResourceRecord) { CommitMarkableResourceRecord xarec = (CommitMarkableResourceRecord) rec; return xarec.forgetHeuristic(); } return false; } @Override public String remove() throws MBeanException { if (forget()) return super.remove(); return "Operation in progress"; } }
apache-2.0
wesm/arrow
java/memory/memory-core/src/main/java/org/apache/arrow/memory/OwnershipTransferResult.java
1045
/* * 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.arrow.memory; /** * The result of transferring an {@link ArrowBuf} between {@linkplain BufferAllocator}s. */ public interface OwnershipTransferResult { boolean getAllocationFit(); ArrowBuf getTransferredBuffer(); }
apache-2.0
a-zuckut/gateway
server/src/main/java/org/kaazing/gateway/server/ConfigurationExtensionApi.java
1142
/** * Copyright 2007-2016, Kaazing Corporation. 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.kaazing.gateway.server; import java.util.Map; import org.kaazing.gateway.server.config.june2016.LoginModuleOptionsType; public interface ConfigurationExtensionApi { /** * Notification that the gateway is configured additional parsing of the file can be done and * various custom properties can be set-up * @param options * @param rawOptions - the actual XML */ default void parseCustomOptions(Map<String, Object> options, LoginModuleOptionsType rawOptions) { } }
apache-2.0
chengjunjian/killbill
payment/src/main/java/org/killbill/billing/payment/core/PaymentProcessor.java
36267
/* * Copyright 2010-2013 Ning, Inc. * Copyright 2014-2015 Groupon, Inc * Copyright 2014-2015 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.billing.payment.core; import java.math.BigDecimal; import java.util.Collection; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.UUID; import javax.annotation.Nullable; import javax.inject.Inject; import org.killbill.automaton.OperationResult; import org.killbill.billing.ErrorCode; import org.killbill.billing.account.api.Account; import org.killbill.billing.account.api.AccountInternalApi; import org.killbill.billing.callcontext.InternalCallContext; import org.killbill.billing.callcontext.InternalTenantContext; import org.killbill.billing.catalog.api.Currency; import org.killbill.billing.invoice.api.InvoiceInternalApi; import org.killbill.billing.osgi.api.OSGIServiceRegistration; import org.killbill.billing.payment.api.DefaultPayment; import org.killbill.billing.payment.api.DefaultPaymentTransaction; import org.killbill.billing.payment.api.Payment; import org.killbill.billing.payment.api.PaymentApiException; import org.killbill.billing.payment.api.PaymentTransaction; import org.killbill.billing.payment.api.PluginProperty; import org.killbill.billing.payment.api.TransactionStatus; import org.killbill.billing.payment.api.TransactionType; import org.killbill.billing.payment.core.janitor.IncompletePaymentTransactionTask; import org.killbill.billing.payment.core.sm.PaymentAutomatonRunner; import org.killbill.billing.payment.dao.PaymentDao; import org.killbill.billing.payment.dao.PaymentModelDao; import org.killbill.billing.payment.dao.PaymentTransactionModelDao; import org.killbill.billing.payment.plugin.api.PaymentPluginApi; import org.killbill.billing.payment.plugin.api.PaymentPluginApiException; import org.killbill.billing.payment.plugin.api.PaymentTransactionInfoPlugin; import org.killbill.billing.tag.TagInternalApi; import org.killbill.billing.util.callcontext.CallContext; import org.killbill.billing.util.callcontext.InternalCallContextFactory; import org.killbill.billing.util.callcontext.TenantContext; import org.killbill.billing.util.entity.Pagination; import org.killbill.billing.util.entity.dao.DefaultPaginationHelper.EntityPaginationBuilder; import org.killbill.billing.util.entity.dao.DefaultPaginationHelper.SourcePaginationBuilder; import org.killbill.clock.Clock; import org.killbill.commons.locker.GlobalLocker; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Function; import com.google.common.base.Predicate; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.collect.Ordering; import static org.killbill.billing.util.entity.dao.DefaultPaginationHelper.getEntityPagination; import static org.killbill.billing.util.entity.dao.DefaultPaginationHelper.getEntityPaginationFromPlugins; public class PaymentProcessor extends ProcessorBase { private static final ImmutableList<PluginProperty> PLUGIN_PROPERTIES = ImmutableList.<PluginProperty>of(); private final PaymentAutomatonRunner paymentAutomatonRunner; private final IncompletePaymentTransactionTask incompletePaymentTransactionTask; private static final Logger log = LoggerFactory.getLogger(PaymentProcessor.class); @Inject public PaymentProcessor(final OSGIServiceRegistration<PaymentPluginApi> pluginRegistry, final AccountInternalApi accountUserApi, final InvoiceInternalApi invoiceApi, final TagInternalApi tagUserApi, final PaymentDao paymentDao, final InternalCallContextFactory internalCallContextFactory, final GlobalLocker locker, final PaymentAutomatonRunner paymentAutomatonRunner, final IncompletePaymentTransactionTask incompletePaymentTransactionTask, final Clock clock) { super(pluginRegistry, accountUserApi, paymentDao, tagUserApi, locker, internalCallContextFactory, invoiceApi, clock); this.paymentAutomatonRunner = paymentAutomatonRunner; this.incompletePaymentTransactionTask = incompletePaymentTransactionTask; } public Payment createAuthorization(final boolean isApiPayment, @Nullable final UUID attemptId, final Account account, @Nullable final UUID paymentMethodId, @Nullable final UUID paymentId, final BigDecimal amount, final Currency currency, @Nullable final String paymentExternalKey, @Nullable final String paymentTransactionExternalKey, final boolean shouldLockAccountAndDispatch, final Iterable<PluginProperty> properties, final CallContext callContext, final InternalCallContext internalCallContext) throws PaymentApiException { return performOperation(isApiPayment, attemptId, TransactionType.AUTHORIZE, account, paymentMethodId, paymentId, null, amount, currency, paymentExternalKey, paymentTransactionExternalKey, shouldLockAccountAndDispatch, null, properties, callContext, internalCallContext); } public Payment createCapture(final boolean isApiPayment, @Nullable final UUID attemptId, final Account account, final UUID paymentId, final BigDecimal amount, final Currency currency, @Nullable final String paymentTransactionExternalKey, final boolean shouldLockAccountAndDispatch, final Iterable<PluginProperty> properties, final CallContext callContext, final InternalCallContext internalCallContext) throws PaymentApiException { return performOperation(isApiPayment, attemptId, TransactionType.CAPTURE, account, null, paymentId, null, amount, currency, null, paymentTransactionExternalKey, shouldLockAccountAndDispatch, null, properties, callContext, internalCallContext); } public Payment createPurchase(final boolean isApiPayment, @Nullable final UUID attemptId, final Account account, @Nullable final UUID paymentMethodId, @Nullable final UUID paymentId, final BigDecimal amount, final Currency currency, @Nullable final String paymentExternalKey, @Nullable final String paymentTransactionExternalKey, final boolean shouldLockAccountAndDispatch, final Iterable<PluginProperty> properties, final CallContext callContext, final InternalCallContext internalCallContext) throws PaymentApiException { return performOperation(isApiPayment, attemptId, TransactionType.PURCHASE, account, paymentMethodId, paymentId, null, amount, currency, paymentExternalKey, paymentTransactionExternalKey, shouldLockAccountAndDispatch, null, properties, callContext, internalCallContext); } public Payment createVoid(final boolean isApiPayment, @Nullable final UUID attemptId, final Account account, final UUID paymentId, @Nullable final String paymentTransactionExternalKey, final boolean shouldLockAccountAndDispatch, final Iterable<PluginProperty> properties, final CallContext callContext, final InternalCallContext internalCallContext) throws PaymentApiException { return performOperation(isApiPayment, attemptId, TransactionType.VOID, account, null, paymentId, null, null, null, null, paymentTransactionExternalKey, shouldLockAccountAndDispatch, null, properties, callContext, internalCallContext); } public Payment createRefund(final boolean isApiPayment, @Nullable final UUID attemptId, final Account account, final UUID paymentId, final BigDecimal amount, final Currency currency, final String paymentTransactionExternalKey, final boolean shouldLockAccountAndDispatch, final Iterable<PluginProperty> properties, final CallContext callContext, final InternalCallContext internalCallContext) throws PaymentApiException { return performOperation(isApiPayment, attemptId, TransactionType.REFUND, account, null, paymentId, null, amount, currency, null, paymentTransactionExternalKey, shouldLockAccountAndDispatch, null, properties, callContext, internalCallContext); } public Payment createCredit(final boolean isApiPayment, @Nullable final UUID attemptId, final Account account, @Nullable final UUID paymentMethodId, @Nullable final UUID paymentId, final BigDecimal amount, final Currency currency, @Nullable final String paymentExternalKey, @Nullable final String paymentTransactionExternalKey, final boolean shouldLockAccountAndDispatch, final Iterable<PluginProperty> properties, final CallContext callContext, final InternalCallContext internalCallContext) throws PaymentApiException { return performOperation(isApiPayment, attemptId, TransactionType.CREDIT, account, paymentMethodId, paymentId, null, amount, currency, paymentExternalKey, paymentTransactionExternalKey, shouldLockAccountAndDispatch, null, properties, callContext, internalCallContext); } public Payment createChargeback(final boolean isApiPayment, @Nullable final UUID attemptId, final Account account, final UUID paymentId, @Nullable final String paymentTransactionExternalKey, final BigDecimal amount, final Currency currency, final boolean shouldLockAccountAndDispatch, final CallContext callContext, final InternalCallContext internalCallContext) throws PaymentApiException { return performOperation(isApiPayment, attemptId, TransactionType.CHARGEBACK, account, null, paymentId, null, amount, currency, null, paymentTransactionExternalKey, shouldLockAccountAndDispatch, null, PLUGIN_PROPERTIES, callContext, internalCallContext); } public Payment notifyPendingPaymentOfStateChanged(final Account account, final UUID transactionId, final boolean isSuccess, final CallContext callContext, final InternalCallContext internalCallContext) throws PaymentApiException { final PaymentTransactionModelDao transactionModelDao = paymentDao.getPaymentTransaction(transactionId, internalCallContext); if (transactionModelDao.getTransactionStatus() != TransactionStatus.PENDING) { throw new PaymentApiException(ErrorCode.PAYMENT_NO_SUCH_SUCCESS_PAYMENT, transactionModelDao.getPaymentId()); } final OperationResult overridePluginResult = isSuccess ? OperationResult.SUCCESS : OperationResult.FAILURE; return performOperation(true, null, transactionModelDao.getTransactionType(), account, null, transactionModelDao.getPaymentId(), transactionModelDao.getId(), transactionModelDao.getAmount(), transactionModelDao.getCurrency(), null, transactionModelDao.getTransactionExternalKey(), true, overridePluginResult, PLUGIN_PROPERTIES, callContext, internalCallContext); } public List<Payment> getAccountPayments(final UUID accountId, final boolean withPluginInfo, final TenantContext context, final InternalTenantContext tenantContext) throws PaymentApiException { final List<PaymentModelDao> paymentsModelDao = paymentDao.getPaymentsForAccount(accountId, tenantContext); final List<PaymentTransactionModelDao> transactionsModelDao = paymentDao.getTransactionsForAccount(accountId, tenantContext); final Map<UUID, PaymentPluginApi> paymentPluginByPaymentMethodId = new HashMap<UUID, PaymentPluginApi>(); final Collection<UUID> absentPlugins = new HashSet<UUID>(); return Lists.<PaymentModelDao, Payment>transform(paymentsModelDao, new Function<PaymentModelDao, Payment>() { @Override public Payment apply(final PaymentModelDao paymentModelDao) { List<PaymentTransactionInfoPlugin> pluginInfo = null; if (withPluginInfo) { PaymentPluginApi pluginApi = paymentPluginByPaymentMethodId.get(paymentModelDao.getPaymentMethodId()); if (pluginApi == null && !absentPlugins.contains(paymentModelDao.getPaymentMethodId())) { try { pluginApi = getPaymentProviderPlugin(paymentModelDao.getPaymentMethodId(), tenantContext); paymentPluginByPaymentMethodId.put(paymentModelDao.getPaymentMethodId(), pluginApi); } catch (final PaymentApiException e) { log.warn("Unable to retrieve pluginApi for payment method " + paymentModelDao.getPaymentMethodId()); absentPlugins.add(paymentModelDao.getPaymentMethodId()); } } pluginInfo = getPaymentTransactionInfoPluginsIfNeeded(pluginApi, paymentModelDao, context); } return toPayment(paymentModelDao, transactionsModelDao, pluginInfo, tenantContext); } }); } public Payment getPayment(final UUID paymentId, final boolean withPluginInfo, final Iterable<PluginProperty> properties, final TenantContext tenantContext, final InternalTenantContext internalTenantContext) throws PaymentApiException { final PaymentModelDao paymentModelDao = paymentDao.getPayment(paymentId, internalTenantContext); if (paymentModelDao == null) { return null; } return toPayment(paymentModelDao, withPluginInfo, properties, tenantContext, internalTenantContext); } public Payment getPaymentByExternalKey(final String paymentExternalKey, final boolean withPluginInfo, final Iterable<PluginProperty> properties, final TenantContext tenantContext, final InternalTenantContext internalTenantContext) throws PaymentApiException { final PaymentModelDao paymentModelDao = paymentDao.getPaymentByExternalKey(paymentExternalKey, internalTenantContext); if (paymentModelDao == null) { return null; } return toPayment(paymentModelDao, withPluginInfo, properties, tenantContext, internalTenantContext); } public Pagination<Payment> getPayments(final Long offset, final Long limit, final boolean withPluginInfo, final Iterable<PluginProperty> properties, final TenantContext tenantContext, final InternalTenantContext internalTenantContext) { return getEntityPaginationFromPlugins(getAvailablePlugins(), offset, limit, new EntityPaginationBuilder<Payment, PaymentApiException>() { @Override public Pagination<Payment> build(final Long offset, final Long limit, final String pluginName) throws PaymentApiException { return getPayments(offset, limit, pluginName, withPluginInfo, properties, tenantContext, internalTenantContext); } } ); } public Pagination<Payment> getPayments(final Long offset, final Long limit, final String pluginName, final boolean withPluginInfo, final Iterable<PluginProperty> properties, final TenantContext tenantContext, final InternalTenantContext internalTenantContext) throws PaymentApiException { final PaymentPluginApi pluginApi = withPluginInfo ? getPaymentPluginApi(pluginName) : null; return getEntityPagination(limit, new SourcePaginationBuilder<PaymentModelDao, PaymentApiException>() { @Override public Pagination<PaymentModelDao> build() { // Find all payments for all accounts return paymentDao.getPayments(pluginName, offset, limit, internalTenantContext); } }, new Function<PaymentModelDao, Payment>() { @Override public Payment apply(final PaymentModelDao paymentModelDao) { final List<PaymentTransactionInfoPlugin> pluginInfo = getPaymentTransactionInfoPluginsIfNeeded(pluginApi, paymentModelDao, tenantContext); return toPayment(paymentModelDao.getId(), pluginInfo, internalTenantContext); } } ); } public Pagination<Payment> searchPayments(final String searchKey, final Long offset, final Long limit, final boolean withPluginInfo, final Iterable<PluginProperty> properties, final TenantContext tenantContext, final InternalTenantContext internalTenantContext) { return getEntityPaginationFromPlugins(getAvailablePlugins(), offset, limit, new EntityPaginationBuilder<Payment, PaymentApiException>() { @Override public Pagination<Payment> build(final Long offset, final Long limit, final String pluginName) throws PaymentApiException { return searchPayments(searchKey, offset, limit, pluginName, withPluginInfo, properties, tenantContext, internalTenantContext); } } ); } public Pagination<Payment> searchPayments(final String searchKey, final Long offset, final Long limit, final String pluginName, final boolean withPluginInfo, final Iterable<PluginProperty> properties, final TenantContext tenantContext, final InternalTenantContext internalTenantContext) throws PaymentApiException { if (withPluginInfo) { final PaymentPluginApi pluginApi = getPaymentPluginApi(pluginName); return getEntityPagination(limit, new SourcePaginationBuilder<PaymentTransactionInfoPlugin, PaymentApiException>() { @Override public Pagination<PaymentTransactionInfoPlugin> build() throws PaymentApiException { try { return pluginApi.searchPayments(searchKey, offset, limit, properties, tenantContext); } catch (final PaymentPluginApiException e) { throw new PaymentApiException(e, ErrorCode.PAYMENT_PLUGIN_SEARCH_PAYMENTS, pluginName, searchKey); } } }, new Function<PaymentTransactionInfoPlugin, Payment>() { final List<PaymentTransactionInfoPlugin> cachedPaymentTransactions = new LinkedList<PaymentTransactionInfoPlugin>(); @Override public Payment apply(final PaymentTransactionInfoPlugin pluginTransaction) { if (pluginTransaction.getKbPaymentId() == null) { // Garbage from the plugin? log.debug("Plugin {} returned a payment without a kbPaymentId for searchKey {}", pluginName, searchKey); return null; } if (cachedPaymentTransactions.isEmpty() || (cachedPaymentTransactions.get(0).getKbPaymentId().equals(pluginTransaction.getKbPaymentId()))) { cachedPaymentTransactions.add(pluginTransaction); return null; } else { final Payment result = toPayment(pluginTransaction.getKbPaymentId(), ImmutableList.<PaymentTransactionInfoPlugin>copyOf(cachedPaymentTransactions), internalTenantContext); cachedPaymentTransactions.clear(); cachedPaymentTransactions.add(pluginTransaction); return result; } } } ); } else { return getEntityPagination(limit, new SourcePaginationBuilder<PaymentModelDao, PaymentApiException>() { @Override public Pagination<PaymentModelDao> build() { return paymentDao.searchPayments(searchKey, offset, limit, internalTenantContext); } }, new Function<PaymentModelDao, Payment>() { @Override public Payment apply(final PaymentModelDao paymentModelDao) { return toPayment(paymentModelDao.getId(), null, internalTenantContext); } } ); } } private Payment performOperation(final boolean isApiPayment, @Nullable final UUID attemptId, final TransactionType transactionType, final Account account, @Nullable final UUID paymentMethodId, @Nullable final UUID paymentId, @Nullable final UUID transactionId, @Nullable final BigDecimal amount, @Nullable final Currency currency, @Nullable final String paymentExternalKey, @Nullable final String paymentTransactionExternalKey, final boolean shouldLockAccountAndDispatch, @Nullable final OperationResult overridePluginOperationResult, final Iterable<PluginProperty> properties, final CallContext callContext, final InternalCallContext internalCallContext) throws PaymentApiException { final UUID nonNullPaymentId = paymentAutomatonRunner.run(isApiPayment, transactionType, account, attemptId, paymentMethodId, paymentId, transactionId, paymentExternalKey, paymentTransactionExternalKey, amount, currency, shouldLockAccountAndDispatch, overridePluginOperationResult, properties, callContext, internalCallContext); return getPayment(nonNullPaymentId, true, properties, callContext, internalCallContext); } // Used in bulk get API (getAccountPayments / getPayments) private List<PaymentTransactionInfoPlugin> getPaymentTransactionInfoPluginsIfNeeded(@Nullable final PaymentPluginApi pluginApi, final PaymentModelDao paymentModelDao, final TenantContext context) { if (pluginApi == null) { return null; } try { return getPaymentTransactionInfoPlugins(pluginApi, paymentModelDao, PLUGIN_PROPERTIES, context); } catch (final PaymentApiException e) { log.warn("Unable to retrieve plugin info for payment " + paymentModelDao.getId()); return null; } } private List<PaymentTransactionInfoPlugin> getPaymentTransactionInfoPlugins(final PaymentPluginApi plugin, final PaymentModelDao paymentModelDao, final Iterable<PluginProperty> properties, final TenantContext context) throws PaymentApiException { try { return plugin.getPaymentInfo(paymentModelDao.getAccountId(), paymentModelDao.getId(), properties, context); } catch (final PaymentPluginApiException e) { throw new PaymentApiException(ErrorCode.PAYMENT_PLUGIN_GET_PAYMENT_INFO, paymentModelDao.getId(), e.toString()); } } // Used in bulk get APIs (getPayments / searchPayments) private Payment toPayment(final UUID paymentId, @Nullable final Iterable<PaymentTransactionInfoPlugin> pluginTransactions, final InternalTenantContext tenantContext) { final PaymentModelDao paymentModelDao = paymentDao.getPayment(paymentId, tenantContext); if (paymentModelDao == null) { log.warn("Unable to find payment id " + paymentId); return null; } return toPayment(paymentModelDao, pluginTransactions, tenantContext); } // Used in single get APIs (getPayment / getPaymentByExternalKey) private Payment toPayment(final PaymentModelDao paymentModelDao, final boolean withPluginInfo, final Iterable<PluginProperty> properties, final TenantContext context, final InternalTenantContext tenantContext) throws PaymentApiException { final PaymentPluginApi plugin = getPaymentProviderPlugin(paymentModelDao.getPaymentMethodId(), tenantContext); final List<PaymentTransactionInfoPlugin> pluginTransactions = withPluginInfo ? getPaymentTransactionInfoPlugins(plugin, paymentModelDao, properties, context) : null; return toPayment(paymentModelDao, pluginTransactions, tenantContext); } private Payment toPayment(final PaymentModelDao paymentModelDao, @Nullable final Iterable<PaymentTransactionInfoPlugin> pluginTransactions, final InternalTenantContext tenantContext) { final InternalTenantContext tenantContextWithAccountRecordId = getInternalTenantContextWithAccountRecordId(paymentModelDao.getAccountId(), tenantContext); final List<PaymentTransactionModelDao> transactionsForPayment = paymentDao.getTransactionsForPayment(paymentModelDao.getId(), tenantContextWithAccountRecordId); return toPayment(paymentModelDao, transactionsForPayment, pluginTransactions, tenantContextWithAccountRecordId); } // Used in bulk get API (getAccountPayments) private Payment toPayment(final PaymentModelDao curPaymentModelDao, final Iterable<PaymentTransactionModelDao> curTransactionsModelDao, @Nullable final Iterable<PaymentTransactionInfoPlugin> pluginTransactions, final InternalTenantContext internalTenantContext) { final Ordering<PaymentTransaction> perPaymentTransactionOrdering = Ordering.<PaymentTransaction>from(new Comparator<PaymentTransaction>() { @Override public int compare(final PaymentTransaction o1, final PaymentTransaction o2) { return o1.getEffectiveDate().compareTo(o2.getEffectiveDate()); } }); // Need to filter for optimized codepaths looking up by account_record_id final Iterable<PaymentTransactionModelDao> filteredTransactions = Iterables.filter(curTransactionsModelDao, new Predicate<PaymentTransactionModelDao>() { @Override public boolean apply(final PaymentTransactionModelDao curPaymentTransactionModelDao) { return curPaymentTransactionModelDao.getPaymentId().equals(curPaymentModelDao.getId()); } }); PaymentModelDao newPaymentModelDao = curPaymentModelDao; final Collection<PaymentTransaction> transactions = new LinkedList<PaymentTransaction>(); for (final PaymentTransactionModelDao curPaymentTransactionModelDao : filteredTransactions) { PaymentTransactionModelDao newPaymentTransactionModelDao = curPaymentTransactionModelDao; final PaymentTransactionInfoPlugin paymentTransactionInfoPlugin = findPaymentTransactionInfoPlugin(newPaymentTransactionModelDao, pluginTransactions); if (paymentTransactionInfoPlugin != null) { // Make sure to invoke the Janitor task in case the plugin fixes its state on the fly // See https://github.com/killbill/killbill/issues/341 final boolean hasChanged = incompletePaymentTransactionTask.updatePaymentAndTransactionIfNeededWithAccountLock(newPaymentModelDao, newPaymentTransactionModelDao, paymentTransactionInfoPlugin, internalTenantContext); if (hasChanged) { newPaymentModelDao = paymentDao.getPayment(newPaymentModelDao.getId(), internalTenantContext); newPaymentTransactionModelDao = paymentDao.getPaymentTransaction(newPaymentTransactionModelDao.getId(), internalTenantContext); } } final PaymentTransaction transaction = new DefaultPaymentTransaction(newPaymentTransactionModelDao.getId(), newPaymentTransactionModelDao.getAttemptId(), newPaymentTransactionModelDao.getTransactionExternalKey(), newPaymentTransactionModelDao.getCreatedDate(), newPaymentTransactionModelDao.getUpdatedDate(), newPaymentTransactionModelDao.getPaymentId(), newPaymentTransactionModelDao.getTransactionType(), newPaymentTransactionModelDao.getEffectiveDate(), newPaymentTransactionModelDao.getTransactionStatus(), newPaymentTransactionModelDao.getAmount(), newPaymentTransactionModelDao.getCurrency(), newPaymentTransactionModelDao.getProcessedAmount(), newPaymentTransactionModelDao.getProcessedCurrency(), newPaymentTransactionModelDao.getGatewayErrorCode(), newPaymentTransactionModelDao.getGatewayErrorMsg(), paymentTransactionInfoPlugin); transactions.add(transaction); } final List<PaymentTransaction> sortedTransactions = perPaymentTransactionOrdering.immutableSortedCopy(transactions); return new DefaultPayment(curPaymentModelDao.getId(), curPaymentModelDao.getCreatedDate(), curPaymentModelDao.getUpdatedDate(), curPaymentModelDao.getAccountId(), curPaymentModelDao.getPaymentMethodId(), curPaymentModelDao.getPaymentNumber(), curPaymentModelDao.getExternalKey(), sortedTransactions); } private PaymentTransactionInfoPlugin findPaymentTransactionInfoPlugin(final PaymentTransactionModelDao paymentTransactionModelDao, @Nullable final Iterable<PaymentTransactionInfoPlugin> pluginTransactions) { if (pluginTransactions == null) { return null; } return Iterables.tryFind(pluginTransactions, new Predicate<PaymentTransactionInfoPlugin>() { @Override public boolean apply(final PaymentTransactionInfoPlugin paymentTransactionInfoPlugin) { return paymentTransactionModelDao.getId().equals(paymentTransactionInfoPlugin.getKbTransactionPaymentId()); } }).orNull(); } private InternalTenantContext getInternalTenantContextWithAccountRecordId(final UUID accountId, final InternalTenantContext tenantContext) { final InternalTenantContext tenantContextWithAccountRecordId; if (tenantContext.getAccountRecordId() == null) { tenantContextWithAccountRecordId = internalCallContextFactory.createInternalTenantContext(accountId, tenantContext); } else { tenantContextWithAccountRecordId = tenantContext; } return tenantContextWithAccountRecordId; } }
apache-2.0
LegNeato/buck
test/com/facebook/buck/util/string/AsciiBoxStringBuilderTest.java
3042
/* * Copyright 2017-present Facebook, 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.facebook.buck.util; import static org.junit.Assert.assertEquals; import com.facebook.buck.util.string.AsciiBoxStringBuilder; import com.google.common.base.Joiner; import org.junit.Test; public class AsciiBoxStringBuilderTest { private static final int MAX_LENGTH = 20; private AsciiBoxStringBuilder builder = new AsciiBoxStringBuilder(MAX_LENGTH); @Test public void testPutsBoxAroundLine() { assertEquals( Joiner.on('\n') .join( "+----------------------+", "| |", "| Hello |", "| |", "+----------------------+", ""), builder.writeLine("Hello").toString()); } @Test public void testWrapsTooLongLines() { assertEquals( Joiner.on('\n') .join( "+----------------------+", "| |", "| Hello world, how |", "| are you doing? |", "| |", "+----------------------+", ""), builder.writeLine("Hello world, how are you doing?").toString()); } @Test public void testWrapsJustBarelyTooLongLines() { assertEquals( Joiner.on('\n') .join( "+----------------------+", "| |", "| Hello world, how |", "| you? |", "| |", "+----------------------+", ""), builder.writeLine("Hello world, how you?").toString()); } @Test public void testHandlesZeroLength() { builder = new AsciiBoxStringBuilder(0); assertEquals( Joiner.on('\n') .join( "+---+", "| |", "| H |", "| e |", "| l |", "| l |", "| o |", "| |", "+---+", ""), builder.writeLine("Hello").toString()); } @Test public void testSplitsWordsThatAreTooLong() { builder = new AsciiBoxStringBuilder(1); assertEquals( Joiner.on('\n') .join( "+---+", "| |", "| H |", "| e |", "| l |", "| l |", "| o |", "| |", "| w |", "| o |", "| r |", "| l |", "| d |", "| |", "+---+", ""), builder.writeLine("Hello world").toString()); } }
apache-2.0
katre/bazel
src/main/java/com/google/devtools/build/lib/starlarkbuildapi/go/GoConfigurationApi.java
1062
// Copyright 2019 The Bazel Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.devtools.build.lib.starlarkbuildapi.go; import com.google.devtools.build.docgen.annot.DocCategory; import net.starlark.java.annot.StarlarkBuiltin; import net.starlark.java.eval.StarlarkValue; /** A configuration fragment for Go. */ @StarlarkBuiltin( name = "go", doc = "A configuration fragment for Go.", category = DocCategory.CONFIGURATION_FRAGMENT) public interface GoConfigurationApi extends StarlarkValue {}
apache-2.0
xm-king/netty-research
codec-http/src/main/java/io/netty/handler/codec/spdy/DefaultSpdyWindowUpdateFrame.java
2508
/* * Copyright 2013 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: * * 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.netty.handler.codec.spdy; import io.netty.util.internal.StringUtil; /** * The default {@link SpdyWindowUpdateFrame} implementation. */ public class DefaultSpdyWindowUpdateFrame implements SpdyWindowUpdateFrame { private int streamId; private int deltaWindowSize; /** * Creates a new instance. * * @param streamId the Stream-ID of this frame * @param deltaWindowSize the Delta-Window-Size of this frame */ public DefaultSpdyWindowUpdateFrame(int streamId, int deltaWindowSize) { setStreamId(streamId); setDeltaWindowSize(deltaWindowSize); } @Override public int getStreamId() { return streamId; } @Override public SpdyWindowUpdateFrame setStreamId(int streamId) { if (streamId < 0) { throw new IllegalArgumentException( "Stream-ID cannot be negative: " + streamId); } this.streamId = streamId; return this; } @Override public int getDeltaWindowSize() { return deltaWindowSize; } @Override public SpdyWindowUpdateFrame setDeltaWindowSize(int deltaWindowSize) { if (deltaWindowSize <= 0) { throw new IllegalArgumentException( "Delta-Window-Size must be positive: " + deltaWindowSize); } this.deltaWindowSize = deltaWindowSize; return this; } @Override public String toString() { StringBuilder buf = new StringBuilder(); buf.append(StringUtil.simpleClassName(this)); buf.append(StringUtil.NEWLINE); buf.append("--> Stream-ID = "); buf.append(getStreamId()); buf.append(StringUtil.NEWLINE); buf.append("--> Delta-Window-Size = "); buf.append(getDeltaWindowSize()); return buf.toString(); } }
apache-2.0
mdecourci/assertj-core
src/test/java/org/assertj/core/internal/doublearrays/DoubleArrays_assertHasSameSizeAs_with_Iterable_Test.java
2184
/** * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * * Copyright 2012-2015 the original author or authors. */ package org.assertj.core.internal.doublearrays; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.error.ShouldHaveSameSizeAs.shouldHaveSameSizeAs; import static org.assertj.core.test.TestData.someInfo; import static org.assertj.core.test.TestFailures.failBecauseExpectedAssertionErrorWasNotThrown; import static org.assertj.core.util.FailureMessages.actualIsNull; import static org.assertj.core.util.Lists.newArrayList; import java.util.List; import org.assertj.core.api.AssertionInfo; import org.assertj.core.internal.DoubleArraysBaseTest; import org.junit.Test; public class DoubleArrays_assertHasSameSizeAs_with_Iterable_Test extends DoubleArraysBaseTest { private final List<String> other = newArrayList("Solo", "Leia", "Luke"); @Test public void should_fail_if_actual_is_null() { thrown.expectAssertionError(actualIsNull()); arrays.assertHasSameSizeAs(someInfo(), null, other); } @Test public void should_fail_if_size_of_actual_is_not_equal_to_expected_size() { AssertionInfo info = someInfo(); List<String> other = newArrayList("Solo", "Leia"); try { arrays.assertHasSameSizeAs(info, actual, other); } catch (AssertionError e) { assertThat(e).hasMessage(shouldHaveSameSizeAs(actual, actual.length, other.size()).create(null, info.representation())); return; } failBecauseExpectedAssertionErrorWasNotThrown(); } @Test public void should_pass_if_size_of_actual_is_equal_to_expected_size() { arrays.assertHasSameSizeAs(someInfo(), actual, other); } }
apache-2.0
jakubschwan/jbpm
jbpm-flow-builder/src/test/java/org/jbpm/integrationtests/marshalling/ProcessInstanceResolverStrategyTest.java
7602
/* * 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.jbpm.integrationtests.marshalling; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.HashMap; import org.drools.core.common.InternalKnowledgeRuntime; import org.drools.core.common.InternalWorkingMemory; import org.drools.core.impl.EnvironmentFactory; import org.drools.core.impl.InternalKnowledgeBase; import org.drools.core.impl.KnowledgeBaseImpl; import org.drools.core.impl.StatefulKnowledgeSessionImpl; import org.drools.core.io.impl.ClassPathResource; import org.drools.core.marshalling.impl.MarshallerReaderContext; import org.drools.core.marshalling.impl.MarshallerWriteContext; import org.drools.core.marshalling.impl.MarshallingConfigurationImpl; import org.drools.core.marshalling.impl.ProtobufMarshaller; import org.drools.core.marshalling.impl.RuleBaseNodes; import org.jbpm.marshalling.impl.ProcessInstanceResolverStrategy; import org.jbpm.process.instance.ProcessInstanceManager; import org.jbpm.ruleflow.instance.RuleFlowProcessInstance; import org.jbpm.test.util.AbstractBaseTest; import org.jbpm.workflow.core.impl.WorkflowProcessImpl; import org.junit.Test; import org.kie.api.io.ResourceType; import org.kie.api.marshalling.ObjectMarshallingStrategy; import org.kie.api.runtime.process.ProcessInstance; import org.kie.internal.KnowledgeBase; import org.kie.internal.KnowledgeBaseFactory; import org.kie.internal.builder.KnowledgeBuilder; import org.kie.internal.builder.KnowledgeBuilderFactory; import org.kie.internal.marshalling.MarshallerFactory; import org.kie.internal.runtime.StatefulKnowledgeSession; public class ProcessInstanceResolverStrategyTest extends AbstractBaseTest { private final static String PROCESS_NAME = "simpleProcess.xml"; @Test public void testAccept() { KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(); StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession(); WorkflowProcessImpl process = new WorkflowProcessImpl(); RuleFlowProcessInstance processInstance = new RuleFlowProcessInstance(); processInstance.setState(ProcessInstance.STATE_ACTIVE); processInstance.setProcess(process); processInstance.setKnowledgeRuntime((InternalKnowledgeRuntime) ksession); ProcessInstanceResolverStrategy strategy = new ProcessInstanceResolverStrategy(); assertTrue( strategy.accept(processInstance) ); Object object = new Object(); assertTrue( ! strategy.accept(object) ); } @Test public void testProcessInstanceResolverStrategy() throws Exception { // Setup KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); kbuilder.add(new ClassPathResource(PROCESS_NAME, this.getClass()), ResourceType.DRF); KnowledgeBase kbase = kbuilder.newKnowledgeBase(); StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession(); ProcessInstance processInstance = ksession.createProcessInstance("process name", new HashMap<String, Object>()); ksession.insert(processInstance); // strategy setup ProcessInstanceResolverStrategy strategy = new ProcessInstanceResolverStrategy(); ObjectMarshallingStrategy[] strategies = { strategy, MarshallerFactory.newSerializeMarshallingStrategy() }; // Test strategy.write org.kie.api.marshalling.MarshallingConfiguration marshallingConfig = new MarshallingConfigurationImpl(strategies, true, true); ByteArrayOutputStream baos = new ByteArrayOutputStream(); MarshallerWriteContext writerContext = new MarshallerWriteContext(baos, ((InternalKnowledgeBase) kbase), (InternalWorkingMemory) ((StatefulKnowledgeSessionImpl) ksession), RuleBaseNodes.getNodeMap(((InternalKnowledgeBase) kbase)), marshallingConfig.getObjectMarshallingStrategyStore(), marshallingConfig.isMarshallProcessInstances(), marshallingConfig.isMarshallWorkItems(), ksession.getEnvironment()); strategy.write(writerContext, processInstance); baos.close(); writerContext.close(); byte[] bytes = baos.toByteArray(); int numCorrectBytes = calculateNumBytesForLong(processInstance.getId()); assertTrue("Expected " + numCorrectBytes + " bytes, not " + bytes.length, bytes.length == numCorrectBytes); ByteArrayInputStream bais = new ByteArrayInputStream(bytes); ObjectInputStream ois = new ObjectInputStream(bais); long serializedProcessInstanceId = ois.readLong(); assertTrue("Expected " + processInstance.getId() + ", not " + serializedProcessInstanceId, processInstance.getId() == serializedProcessInstanceId); // Test other strategy stuff ProcessInstanceManager pim = ProcessInstanceResolverStrategy.retrieveProcessInstanceManager(writerContext); assertNotNull(pim); assertNotNull(ProcessInstanceResolverStrategy.retrieveKnowledgeRuntime(writerContext)); assertTrue(processInstance == pim.getProcessInstance(serializedProcessInstanceId)); // Test strategy.read bais = new ByteArrayInputStream(bytes); MarshallerReaderContext readerContext = new MarshallerReaderContext(bais, ((KnowledgeBaseImpl) kbase), RuleBaseNodes.getNodeMap( ((KnowledgeBaseImpl) kbase)), marshallingConfig.getObjectMarshallingStrategyStore(), ProtobufMarshaller.TIMER_READERS, marshallingConfig.isMarshallProcessInstances(), marshallingConfig.isMarshallWorkItems() , EnvironmentFactory.newEnvironment()); readerContext.wm = ((StatefulKnowledgeSessionImpl) ksession).getInternalWorkingMemory(); Object procInstObject = strategy.read(readerContext); assertTrue(procInstObject != null && procInstObject instanceof ProcessInstance ); assertTrue(processInstance == procInstObject); } private int calculateNumBytesForLong(Long longVal) throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeLong(longVal); baos.close(); oos.close(); return baos.toByteArray().length; } }
apache-2.0
smilzo-mobimesh/smarthome
bundles/io/org.eclipse.smarthome.io.rest.sitemap/src/main/java/org/eclipse/smarthome/io/rest/sitemap/internal/SitemapResource.java
22122
/** * Copyright (c) 2014-2015 openHAB UG (haftungsbeschraenkt) and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.eclipse.smarthome.io.rest.sitemap.internal; import java.net.URI; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.HashSet; import java.util.LinkedList; import java.util.Set; import javax.ws.rs.DefaultValue; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Context; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriBuilder; import javax.ws.rs.core.UriInfo; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EObject; import org.eclipse.smarthome.core.items.GenericItem; import org.eclipse.smarthome.core.items.Item; import org.eclipse.smarthome.core.items.ItemNotFoundException; import org.eclipse.smarthome.core.items.StateChangeListener; import org.eclipse.smarthome.core.types.State; import org.eclipse.smarthome.io.rest.RESTResource; import org.eclipse.smarthome.io.rest.core.item.EnrichedItemDTOMapper; import org.eclipse.smarthome.model.dto.MappingDTO; import org.eclipse.smarthome.model.dto.PageDTO; import org.eclipse.smarthome.model.dto.SitemapDTO; import org.eclipse.smarthome.model.dto.WidgetDTO; import org.eclipse.smarthome.model.sitemap.Chart; import org.eclipse.smarthome.model.sitemap.Frame; import org.eclipse.smarthome.model.sitemap.Image; import org.eclipse.smarthome.model.sitemap.LinkableWidget; import org.eclipse.smarthome.model.sitemap.List; import org.eclipse.smarthome.model.sitemap.Mapping; import org.eclipse.smarthome.model.sitemap.Mapview; import org.eclipse.smarthome.model.sitemap.Selection; import org.eclipse.smarthome.model.sitemap.Setpoint; import org.eclipse.smarthome.model.sitemap.Sitemap; import org.eclipse.smarthome.model.sitemap.SitemapProvider; import org.eclipse.smarthome.model.sitemap.Slider; import org.eclipse.smarthome.model.sitemap.Switch; import org.eclipse.smarthome.model.sitemap.Video; import org.eclipse.smarthome.model.sitemap.Webview; import org.eclipse.smarthome.model.sitemap.Widget; import org.eclipse.smarthome.ui.items.ItemUIRegistry; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * <p> * This class acts as a REST resource for sitemaps and provides different methods to interact with them, like retrieving * a list of all available sitemaps or just getting the widgets of a single page. * </p> * * @author Kai Kreuzer - Initial contribution and API * @author Chris Jackson */ @Path(SitemapResource.PATH_SITEMAPS) public class SitemapResource implements RESTResource { private final Logger logger = LoggerFactory.getLogger(SitemapResource.class); public static final String PATH_SITEMAPS = "sitemaps"; private static final long TIMEOUT_IN_MS = 30000; @Context UriInfo uriInfo; private ItemUIRegistry itemUIRegistry; private java.util.List<SitemapProvider> sitemapProviders = new ArrayList<>(); public void setItemUIRegistry(ItemUIRegistry itemUIRegistry) { this.itemUIRegistry = itemUIRegistry; } public void unsetItemUIRegistry(ItemUIRegistry itemUIRegistry) { this.itemUIRegistry = null; } public void addSitemapProvider(SitemapProvider provider) { sitemapProviders.add(provider); } public void removeSitemapProvider(SitemapProvider provider) { sitemapProviders.remove(provider); } @GET @Produces(MediaType.APPLICATION_JSON) public Response getSitemaps() { logger.debug("Received HTTP GET request at '{}'", uriInfo.getPath()); Object responseObject = getSitemapBeans(uriInfo.getAbsolutePathBuilder().build()); return Response.ok(responseObject).build(); } @GET @Path("/{sitemapname: [a-zA-Z_0-9]*}") @Produces(MediaType.APPLICATION_JSON) public Response getSitemapData(@Context HttpHeaders headers, @PathParam("sitemapname") String sitemapname, @QueryParam("type") String type, @QueryParam("jsoncallback") @DefaultValue("callback") String callback) { logger.debug("Received HTTP GET request at '{}' for media type '{}'.", new Object[] { uriInfo.getPath(), type }); Object responseObject = getSitemapBean(sitemapname, uriInfo.getBaseUriBuilder().build()); return Response.ok(responseObject).build(); } @GET @Path("/{sitemapname: [a-zA-Z_0-9]*}/{pageid: [a-zA-Z_0-9]*}") @Produces(MediaType.APPLICATION_JSON) public Response getPageData(@Context HttpHeaders headers, @PathParam("sitemapname") String sitemapname, @PathParam("pageid") String pageId) { logger.debug("Received HTTP GET request at '{}'", uriInfo.getPath()); if (headers.getRequestHeader("X-Atmosphere-Transport") != null) { // Make the REST-API pseudo-compatible with openHAB 1.x // The client asks Atmosphere for server push functionality, // so we do a simply listening for changes on the appropriate items blockUnlessChangeOccurs(sitemapname, pageId); } Object responseObject = getPageBean(sitemapname, pageId, uriInfo.getBaseUriBuilder().build()); return Response.ok(responseObject).build(); } private PageDTO getPageBean(String sitemapName, String pageId, URI uri) { Sitemap sitemap = getSitemap(sitemapName); if (sitemap != null) { if (pageId.equals(sitemap.getName())) { return createPageBean(sitemapName, sitemap.getLabel(), sitemap.getIcon(), sitemap.getName(), sitemap.getChildren(), false, isLeaf(sitemap.getChildren()), uri); } else { Widget pageWidget = itemUIRegistry.getWidget(sitemap, pageId); if (pageWidget instanceof LinkableWidget) { EList<Widget> children = itemUIRegistry.getChildren((LinkableWidget) pageWidget); PageDTO pageBean = createPageBean(sitemapName, itemUIRegistry.getLabel(pageWidget), itemUIRegistry.getIcon(pageWidget), pageId, children, false, isLeaf(children), uri); EObject parentPage = pageWidget.eContainer(); while (parentPage instanceof Frame) { parentPage = parentPage.eContainer(); } if (parentPage instanceof Widget) { String parentId = itemUIRegistry.getWidgetId((Widget) parentPage); pageBean.parent = getPageBean(sitemapName, parentId, uri); pageBean.parent.widgets = null; pageBean.parent.parent = null; } else if (parentPage instanceof Sitemap) { pageBean.parent = getPageBean(sitemapName, sitemap.getName(), uri); pageBean.parent.widgets = null; } return pageBean; } else { if (logger.isDebugEnabled()) { if (pageWidget == null) { logger.debug("Received HTTP GET request at '{}' for the unknown page id '{}'.", uri, pageId); } else { logger.debug("Received HTTP GET request at '{}' for the page id '{}'. " + "This id refers to a non-linkable widget and is therefore no valid page id.", uri, pageId); } } throw new WebApplicationException(404); } } } else { logger.info("Received HTTP GET request at '{}' for the unknown sitemap '{}'.", uri, sitemapName); throw new WebApplicationException(404); } } public Collection<SitemapDTO> getSitemapBeans(URI uri) { Collection<SitemapDTO> beans = new LinkedList<SitemapDTO>(); logger.debug("Received HTTP GET request at '{}'.", UriBuilder.fromUri(uri).build().toASCIIString()); for(SitemapProvider provider : sitemapProviders) { for (String modelName : provider.getSitemapNames()) { Sitemap sitemap = provider.getSitemap(modelName); if (sitemap != null) { SitemapDTO bean = new SitemapDTO(); bean.name = modelName; bean.icon = sitemap.getIcon(); bean.label = sitemap.getLabel(); bean.link = UriBuilder.fromUri(uri).path(bean.name).build().toASCIIString(); bean.homepage = new PageDTO(); bean.homepage.link = bean.link + "/" + sitemap.getName(); beans.add(bean); } } } return beans; } public SitemapDTO getSitemapBean(String sitemapname, URI uri) { Sitemap sitemap = getSitemap(sitemapname); if (sitemap != null) { return createSitemapBean(sitemapname, sitemap, uri); } else { logger.info("Received HTTP GET request at '{}' for the unknown sitemap '{}'.", uriInfo.getPath(), sitemapname); throw new WebApplicationException(404); } } private SitemapDTO createSitemapBean(String sitemapName, Sitemap sitemap, URI uri) { SitemapDTO bean = new SitemapDTO(); bean.name = sitemapName; bean.icon = sitemap.getIcon(); bean.label = sitemap.getLabel(); bean.link = UriBuilder.fromUri(uri).path(SitemapResource.PATH_SITEMAPS).path(bean.name).build().toASCIIString(); bean.homepage = createPageBean(sitemap.getName(), sitemap.getLabel(), sitemap.getIcon(), sitemap.getName(), sitemap.getChildren(), true, false, uri); return bean; } private PageDTO createPageBean(String sitemapName, String title, String icon, String pageId, EList<Widget> children, boolean drillDown, boolean isLeaf, URI uri) { PageDTO bean = new PageDTO(); bean.id = pageId; bean.title = title; bean.icon = icon; bean.leaf = isLeaf; bean.link = UriBuilder.fromUri(uri).path(PATH_SITEMAPS).path(sitemapName).path(pageId).build().toASCIIString(); if (children != null) { int cntWidget = 0; for (Widget widget : children) { String widgetId = pageId + "_" + cntWidget; WidgetDTO subWidget = createWidgetBean(sitemapName, widget, drillDown, uri, widgetId); if (subWidget != null) bean.widgets.add(subWidget); cntWidget++; } } else { bean.widgets = null; } return bean; } private WidgetDTO createWidgetBean(String sitemapName, Widget widget, boolean drillDown, URI uri, String widgetId) { // Test visibility if (itemUIRegistry.getVisiblity(widget) == false) return null; WidgetDTO bean = new WidgetDTO(); if (widget.getItem() != null) { try { Item item = itemUIRegistry.getItem(widget.getItem()); if (item != null) { bean.item = EnrichedItemDTOMapper.map(item, false, UriBuilder.fromUri(uri).build()); } } catch (ItemNotFoundException e) { logger.debug(e.getMessage()); } } bean.widgetId = widgetId; bean.icon = itemUIRegistry.getIcon(widget); bean.labelcolor = itemUIRegistry.getLabelColor(widget); bean.valuecolor = itemUIRegistry.getValueColor(widget); bean.label = itemUIRegistry.getLabel(widget); bean.type = widget.eClass().getName(); if (widget instanceof LinkableWidget) { LinkableWidget linkableWidget = (LinkableWidget) widget; EList<Widget> children = itemUIRegistry.getChildren(linkableWidget); if (widget instanceof Frame) { int cntWidget = 0; for (Widget child : children) { widgetId += "_" + cntWidget; WidgetDTO subWidget = createWidgetBean(sitemapName, child, drillDown, uri, widgetId); if (subWidget != null) { bean.widgets.add(subWidget); cntWidget++; } } } else if (children.size() > 0) { String pageName = itemUIRegistry.getWidgetId(linkableWidget); bean.linkedPage = createPageBean(sitemapName, itemUIRegistry.getLabel(widget), itemUIRegistry.getIcon(widget), pageName, drillDown ? children : null, drillDown, isLeaf(children), uri); } } if (widget instanceof Switch) { Switch switchWidget = (Switch) widget; for (Mapping mapping : switchWidget.getMappings()) { MappingDTO mappingBean = new MappingDTO(); // Remove quotes - if they exist if (mapping.getCmd() != null) { if (mapping.getCmd().startsWith("\"") && mapping.getCmd().endsWith("\"")) { mappingBean.command = mapping.getCmd().substring(1, mapping.getCmd().length() - 1); } else { mappingBean.command = mapping.getCmd(); } } mappingBean.label = mapping.getLabel(); bean.mappings.add(mappingBean); } } if (widget instanceof Selection) { Selection selectionWidget = (Selection) widget; for (Mapping mapping : selectionWidget.getMappings()) { MappingDTO mappingBean = new MappingDTO(); // Remove quotes - if they exist if (mapping.getCmd() != null) { if (mapping.getCmd().startsWith("\"") && mapping.getCmd().endsWith("\"")) { mappingBean.command = mapping.getCmd().substring(1, mapping.getCmd().length() - 1); } else { mappingBean.command = mapping.getCmd(); } } mappingBean.label = mapping.getLabel(); bean.mappings.add(mappingBean); } } if (widget instanceof Slider) { Slider sliderWidget = (Slider) widget; bean.sendFrequency = sliderWidget.getFrequency(); bean.switchSupport = sliderWidget.isSwitchEnabled(); } if (widget instanceof List) { List listWidget = (List) widget; bean.separator = listWidget.getSeparator(); } if (widget instanceof Image) { Image imageWidget = (Image) widget; String wId = itemUIRegistry.getWidgetId(widget); if (uri.getPort() < 0 || uri.getPort() == 80) { bean.url = uri.getScheme() + "://" + uri.getHost() + "/proxy?sitemap=" + sitemapName + ".sitemap&widgetId=" + wId; } else { bean.url = uri.getScheme() + "://" + uri.getHost() + ":" + uri.getPort() + "/proxy?sitemap=" + sitemapName + ".sitemap&widgetId=" + wId; } if (imageWidget.getRefresh() > 0) { bean.refresh = imageWidget.getRefresh(); } } if (widget instanceof Video) { String wId = itemUIRegistry.getWidgetId(widget); if (uri.getPort() < 0 || uri.getPort() == 80) { bean.url = uri.getScheme() + "://" + uri.getHost() + "/proxy?sitemap=" + sitemapName + ".sitemap&widgetId=" + wId; } else { bean.url = uri.getScheme() + "://" + uri.getHost() + ":" + uri.getPort() + "/proxy?sitemap=" + sitemapName + ".sitemap&widgetId=" + wId; } } if (widget instanceof Webview) { Webview webViewWidget = (Webview) widget; bean.url = webViewWidget.getUrl(); bean.height = webViewWidget.getHeight(); } if (widget instanceof Mapview) { Mapview mapViewWidget = (Mapview) widget; bean.height = mapViewWidget.getHeight(); } if (widget instanceof Chart) { Chart chartWidget = (Chart) widget; bean.service = chartWidget.getService(); bean.period = chartWidget.getPeriod(); if (chartWidget.getRefresh() > 0) { bean.refresh = chartWidget.getRefresh(); } } if (widget instanceof Setpoint) { Setpoint setpointWidget = (Setpoint) widget; bean.minValue = setpointWidget.getMinValue(); bean.maxValue = setpointWidget.getMaxValue(); bean.step = setpointWidget.getStep(); } return bean; } private boolean isLeaf(EList<Widget> children) { for (Widget w : children) { if (w instanceof Frame) { if (isLeaf(((Frame) w).getChildren())) { return false; } } else if (w instanceof LinkableWidget) { LinkableWidget linkableWidget = (LinkableWidget) w; if (itemUIRegistry.getChildren(linkableWidget).size() > 0) { return false; } } } return true; } private Sitemap getSitemap(String sitemapname) { for (SitemapProvider provider : sitemapProviders) { Sitemap sitemap = provider.getSitemap(sitemapname); if (sitemap != null) { return sitemap; } } return null; } private void blockUnlessChangeOccurs(String sitemapname, String pageId) { Sitemap sitemap = getSitemap(sitemapname); if (sitemap != null) { if (pageId.equals(sitemap.getName())) { waitForChanges(sitemap.getChildren()); } else { Widget pageWidget = itemUIRegistry.getWidget(sitemap, pageId); if (pageWidget instanceof LinkableWidget) { EList<Widget> children = itemUIRegistry.getChildren((LinkableWidget) pageWidget); waitForChanges(children); } } } } /** * This method only returns when a change has occurred to any item on the page to display * or if the timeout is reached * * @param widgets the widgets of the page to observe */ private boolean waitForChanges(EList<Widget> widgets) { long startTime = (new Date()).getTime(); boolean timeout = false; BlockingStateChangeListener listener = new BlockingStateChangeListener(); // let's get all items for these widgets Set<GenericItem> items = getAllItems(widgets); for (GenericItem item : items) { item.addStateChangeListener(listener); } while (!listener.hasChangeOccurred() && !timeout) { timeout = (new Date()).getTime() - startTime > TIMEOUT_IN_MS; try { Thread.sleep(300); } catch (InterruptedException e) { timeout = true; break; } } for (GenericItem item : items) { item.removeStateChangeListener(listener); } return !timeout; } /** * Collects all items that are represented by a given list of widgets * * @param widgets the widget list to get the items for * @return all items that are represented by the list of widgets */ private Set<GenericItem> getAllItems(EList<Widget> widgets) { Set<GenericItem> items = new HashSet<GenericItem>(); if (itemUIRegistry != null) { for (Widget widget : widgets) { String itemName = widget.getItem(); if (itemName != null) { try { Item item = itemUIRegistry.getItem(itemName); if (item instanceof GenericItem) { final GenericItem gItem = (GenericItem) item; items.add(gItem); } } catch (ItemNotFoundException e) { // ignore } } else { if (widget instanceof Frame) { items.addAll(getAllItems(((Frame) widget).getChildren())); } } } } return items; } /** * This is a state change listener, which is merely used to determine, if a state * change has occurred on one of a list of items. * * @author Kai Kreuzer - Initial contribution and API * */ private static class BlockingStateChangeListener implements StateChangeListener { private boolean changed = false; /** * {@inheritDoc} */ @Override public void stateChanged(Item item, State oldState, State newState) { changed = true; } /** * determines, whether a state change has occurred since its creation * * @return true, if a state has changed */ public boolean hasChangeOccurred() { return changed; } /** * {@inheritDoc} */ @Override public void stateUpdated(Item item, State state) { // ignore if the state did not change } } }
epl-1.0
codenvy/che-core
platform-api/che-core-api-core/src/main/java/org/eclipse/che/api/core/util/DownloadPlugin.java
2119
/******************************************************************************* * Copyright (c) 2012-2016 Codenvy, S.A. * 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: * Codenvy, S.A. - initial API and implementation *******************************************************************************/ package org.eclipse.che.api.core.util; import java.io.IOException; /** * Downloads remote file. * * @author andrew00x */ public interface DownloadPlugin { interface Callback { /** * Notified when file downloaded. * * @param downloaded * downloaded file */ void done(java.io.File downloaded); /** * Notified when error occurs. * * @param e * error */ void error(IOException e); } /** * Download file from specified location to local directory {@code downloadTo}. * * @param downloadUrl * download URL * @param downloadTo * local directory for download * @param callback * notified when download is done or an error occurs */ void download(String downloadUrl, java.io.File downloadTo, Callback callback); /** * Download file from specified location to local directory {@code downloadTo} and save it in file {@code fileName}. * * @param downloadUrl * download URL * @param downloadTo * local directory for download * @param fileName * name of local file to save download result * @param replaceExisting * replace existed file with the same name * @throws IOException if i/o error occurs when try download file or save it on local filesystem */ void download(String downloadUrl, java.io.File downloadTo, String fileName, boolean replaceExisting) throws IOException; }
epl-1.0
google/error-prone-javac
test/jdk/javadoc/doclet/testModules/TestModuleServices.java
13306
/* * Copyright (c) 2017, 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 8178067 * @summary tests the module's services, such as provides and uses * @modules jdk.javadoc/jdk.javadoc.internal.api * jdk.javadoc/jdk.javadoc.internal.tool * jdk.compiler/com.sun.tools.javac.api * jdk.compiler/com.sun.tools.javac.main * @library ../lib /tools/lib * @build toolbox.ToolBox toolbox.ModuleBuilder JavadocTester * @run main TestModuleServices */ import java.nio.file.Path; import java.nio.file.Paths; import toolbox.*; public class TestModuleServices extends JavadocTester { public final ToolBox tb; public static void main(String... args) throws Exception { TestModuleServices tester = new TestModuleServices(); tester.runTests(m -> new Object[] { Paths.get(m.getName()) }); } public TestModuleServices() { tb = new ToolBox(); } @Test public void checkUsesNoApiTagModuleModeDefault(Path base) throws Exception { ModuleBuilder mb = new ModuleBuilder(tb, "m") .comment("module m.\n@provides p1.A abc") // bogus tag .uses("p1.A") .uses("p1.B") .exports("p1") .classes("package p1; public class A {}") .classes("package p1; public class B {}"); mb.write(base); javadoc("-d", base.toString() + "/out", "-quiet", "--module-source-path", base.toString(), "--module", "m"); checkExit(Exit.OK); checkOutput("m-summary.html", false, "<h3>Services</h3>"); } @Test public void checkUsesNoApiTagModuleModeAll(Path base) throws Exception { ModuleBuilder mb = new ModuleBuilder(tb, "m") .uses("p1.A") .uses("p1.B") .exports("p1") .classes("package p1; public class A {}") .classes("package p1; public class B {}"); mb.write(base); javadoc("-d", base.toString() + "/out", "-quiet", "--show-module-contents", "all", "--module-source-path", base.toString(), "--module", "m"); checkExit(Exit.OK); checkOutput("m-summary.html", true, "<h3>Services</h3>"); checkOutput("m-summary.html", true, "<table class=\"usesSummary\" summary=\"Uses table, listing types, and an explanation\">\n" + "<caption><span>Uses</span><span class=\"tabEnd\">&nbsp;</span></caption>\n" + "<tr>\n" + "<th class=\"colFirst\" scope=\"col\">Type</th>\n" + "<th class=\"colLast\" scope=\"col\">Description</th>\n" + "</tr>\n" + "<tbody>\n" + "<tr class=\"altColor\">\n" + "<th class=\"colFirst\" scope=\"row\"><a href=\"p1/A.html\" title=\"class in p1\">A</a></th>\n" + "<td class=\"colLast\">&nbsp;</td>\n" + "</tr>\n" + "<tr class=\"rowColor\">\n" + "<th class=\"colFirst\" scope=\"row\"><a href=\"p1/B.html\" title=\"class in p1\">B</a></th>\n" + "<td class=\"colLast\">&nbsp;</td>\n" + "</tr>\n" + "</tbody>\n" + "</table>\n"); } @Test public void checkUsesWithApiTagModuleModeDefault(Path base) throws Exception { ModuleBuilder mb = new ModuleBuilder(tb, "m") .comment("module m.\n@uses p1.A") .uses("p1.A") .uses("p1.B") .exports("p1") .classes("package p1; public class A {}") .classes("package p1; public class B {}"); mb.write(base); javadoc("-d", base.toString() + "/out", "-quiet", "--module-source-path", base.toString(), "--module", "m"); checkExit(Exit.OK); checkOutput("m-summary.html", true, "<h3>Services</h3>"); checkOutput("m-summary.html", true, "<table class=\"usesSummary\" summary=\"Uses table, listing types, and an explanation\">\n" + "<caption><span>Uses</span><span class=\"tabEnd\">&nbsp;</span></caption>\n" + "<tr>\n" + "<th class=\"colFirst\" scope=\"col\">Type</th>\n" + "<th class=\"colLast\" scope=\"col\">Description</th>\n" + "</tr>\n" + "<tbody>\n" + "<tr class=\"altColor\">\n" + "<th class=\"colFirst\" scope=\"row\"><a href=\"p1/A.html\" title=\"class in p1\">A</a></th>\n" + "<td class=\"colLast\">&nbsp;</td>\n" + "</tr>\n" + "</tbody>\n" + "</table>\n"); } @Test public void checkProvidesNoApiTagModuleModeDefault(Path base) throws Exception { ModuleBuilder mb = new ModuleBuilder(tb, "m") .comment("module m.\n@uses p1.A") .provides("p1.A", "p1.B") .exports("p1") .classes("package p1; public interface A {}") .classes("package p1; public class B implements A {}") .provides("p2.A", "p2.B") .exports("p2") .classes("package p2; public interface A {}") .classes("package p2; public class B implements A {}"); mb.write(base); javadoc("-d", base.toString() + "/out", "-quiet", "--module-source-path", base.toString(), "--module", "m"); checkExit(Exit.OK); checkOutput("m-summary.html", false, "<h3>Services</h3>"); } @Test public void checkProvidesNoApiTagModuleModeAll(Path base) throws Exception { ModuleBuilder mb = new ModuleBuilder(tb, "m") .comment("module m.\n@uses p1.A") // bogus uses tag .provides("p1.A", "p1.B") .exports("p1") .classes("package p1; public interface A {}") .classes("package p1; public class B implements A {}") .provides("p2.A", "p2.B") .exports("p2") .classes("package p2; public interface A {}") .classes("package p2; public class B implements A {}"); mb.write(base); javadoc("-d", base.toString() + "/out", "-quiet", "--show-module-contents", "all", "--module-source-path", base.toString(), "--module", "m"); checkExit(Exit.OK); checkOutput("m-summary.html", true, "<h3>Services</h3>"); checkOutput("m-summary.html", true, "<table class=\"providesSummary\" summary=\"Provides table, listing types, and an explanation\">\n" + "<caption><span>Provides</span><span class=\"tabEnd\">&nbsp;</span></caption>\n" + "<tr>\n" + "<th class=\"colFirst\" scope=\"col\">Type</th>\n" + "<th class=\"colLast\" scope=\"col\">Description</th>\n" + "</tr>\n" + "<tbody>\n" + "<tr class=\"altColor\">\n" + "<th class=\"colFirst\" scope=\"row\"><a href=\"p1/A.html\" title=\"interface in p1\">A</a></th>\n" + "<td class=\"colLast\">&nbsp;<br>(<span class=\"implementationLabel\">Implementation(s):</span>&nbsp;<a href=\"p1/B.html\" title=\"class in p1\">B</a>)</td>\n" + "</tr>\n" + "<tr class=\"rowColor\">\n" + "<th class=\"colFirst\" scope=\"row\"><a href=\"p2/A.html\" title=\"interface in p2\">A</a></th>\n" + "<td class=\"colLast\">&nbsp;<br>(<span class=\"implementationLabel\">Implementation(s):</span>&nbsp;<a href=\"p2/B.html\" title=\"class in p2\">B</a>)</td>\n" + "</tr>\n" + "</tbody>\n"); } @Test public void checkProvidesWithApiTagModuleModeDefault(Path base) throws Exception { ModuleBuilder mb = new ModuleBuilder(tb, "m") .comment("module m.\n@provides p1.A abc") .provides("p1.A", "p1.B") .exports("p1") .classes("package p1; public interface A {}") .classes("package p1; public class B implements A {}") .provides("p2.A", "p2.B") .exports("p2") .classes("package p2; public interface A {}") .classes("package p2; public class B implements A {}"); mb.write(base); javadoc("-d", base.toString() + "/out", "-quiet", "--module-source-path", base.toString(), "--module", "m"); checkExit(Exit.OK); checkOutput("m-summary.html", true, "<h3>Services</h3>"); checkOutput("m-summary.html", true, "<table class=\"providesSummary\" summary=\"Provides table, listing types, and an explanation\">\n" + "<caption><span>Provides</span><span class=\"tabEnd\">&nbsp;</span></caption>\n" + "<tr>\n" + "<th class=\"colFirst\" scope=\"col\">Type</th>\n" + "<th class=\"colLast\" scope=\"col\">Description</th>\n" + "</tr>\n" + "<tbody>\n" + "<tr class=\"altColor\">\n" + "<th class=\"colFirst\" scope=\"row\"><a href=\"p1/A.html\" title=\"interface in p1\">A</a></th>\n" + "<td class=\"colLast\">abc&nbsp;</td>\n" + "</tr>\n" + "</tbody>\n" + "</table>\n"); } @Test public void checkUsesProvidesWithApiTagsModeDefault(Path base) throws Exception { ModuleBuilder mb = new ModuleBuilder(tb, "m") .comment("module m.\n@provides p1.A abc\n@uses p2.B def") .provides("p1.A", "p1.B") .exports("p1") .classes("package p1; public interface A {}") .classes("package p1; public class B implements A {}") .provides("p2.A", "p2.B") .uses("p2.B") .exports("p2") .classes("package p2; public interface A {}") .classes("package p2; public class B implements A {}"); mb.write(base); javadoc("-d", base.toString() + "/out", "-quiet", "--module-source-path", base.toString(), "--module", "m"); checkExit(Exit.OK); checkOutput("m-summary.html", true, "<h3>Services</h3>"); checkOutput("m-summary.html", true, "<table class=\"providesSummary\" summary=\"Provides table, listing types, and an explanation\">\n" + "<caption><span>Provides</span><span class=\"tabEnd\">&nbsp;</span></caption>\n" + "<tr>\n" + "<th class=\"colFirst\" scope=\"col\">Type</th>\n" + "<th class=\"colLast\" scope=\"col\">Description</th>\n" + "</tr>\n" + "<tbody>\n" + "<tr class=\"altColor\">\n" + "<th class=\"colFirst\" scope=\"row\"><a href=\"p1/A.html\" title=\"interface in p1\">A</a></th>\n" + "<td class=\"colLast\">abc&nbsp;</td>\n" + "</tr>\n" + "</tbody>\n" + "</table>", "<table class=\"usesSummary\" summary=\"Uses table, listing types, and an explanation\">\n" + "<caption><span>Uses</span><span class=\"tabEnd\">&nbsp;</span></caption>\n" + "<tr>\n" + "<th class=\"colFirst\" scope=\"col\">Type</th>\n" + "<th class=\"colLast\" scope=\"col\">Description</th>\n" + "</tr>\n" + "<tbody>\n" + "<tr class=\"altColor\">\n" + "<th class=\"colFirst\" scope=\"row\"><a href=\"p2/B.html\" title=\"class in p2\">B</a></th>\n" + "<td class=\"colLast\">def&nbsp;</td>\n" + "</tr>\n" + "</tbody>\n" + "</table>\n"); } }
gpl-2.0
sics-sse/moped
squawk/phoneme/midp/src/ams/ams_api/reference/classes/com/sun/midp/midlet/MIDletEventListener.java
4820
/* * * * Copyright 1990-2007 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER * * This program 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 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 version 2 for more details (a copy is * included at /legal/license.txt). * * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa * Clara, CA 95054 or visit www.sun.com if you need additional * information or have any questions. */ package com.sun.midp.midlet; import com.sun.midp.events.Event; import com.sun.midp.events.EventTypes; import com.sun.midp.events.EventQueue; import com.sun.midp.events.EventListener; import com.sun.midp.events.NativeEvent; import com.sun.midp.security.Permissions; import com.sun.midp.security.SecurityToken; import com.sun.midp.log.Logging; import com.sun.midp.log.LogChannels; /** * Listener for MIDlet related events (state changes, etc). * */ public class MIDletEventListener implements EventListener { /** Cached reference to the MIDP event queue. */ private EventQueue eventQueue; /** The controller of MIDlets. */ private MIDletStateHandler midletStateHandler; /** This class has a different security domain than the application. */ private static SecurityToken classSecurityToken; /** * The constructor for the default event handler for LCDUI. * * @param token security token that has AMS permission to * use restricted MIDlet state handler methods * @param theMIDletStateHandler the midlet state handler * @param theEventQueue the event queue */ public MIDletEventListener( SecurityToken token, MIDletStateHandler theMIDletStateHandler, EventQueue theEventQueue) { token.checkIfPermissionAllowed(Permissions.AMS); classSecurityToken = token; midletStateHandler = theMIDletStateHandler; eventQueue = theEventQueue; /* * All events handled by this object are of NativeEventClass * and are instance specific events assosiated with some display Id. * So this listener is able to find an appropriate DisplayEventConsumer * associated with the displayId field of NativeEvent and * to call methods of found consumer. */ eventQueue.registerEventListener(EventTypes.ACTIVATE_MIDLET_EVENT, this); eventQueue.registerEventListener(EventTypes.PAUSE_MIDLET_EVENT, this); eventQueue.registerEventListener(EventTypes.DESTROY_MIDLET_EVENT, this); } /** * Preprocess an event that is being posted to the event queue. * * @param event event being posted * * @param waitingEvent previous event of this type waiting in the * queue to be processed * * @return true to allow the post to continue, false to not post the * event to the queue */ public boolean preprocess(Event event, Event waitingEvent) { return true; } /** * Process an event. * * @param event event to process */ public void process(Event event) { NativeEvent nativeEvent = (NativeEvent)event; MIDletEventConsumer midletEventConsumer = midletStateHandler.getMIDletEventConsumer(classSecurityToken, nativeEvent.stringParam1); if (midletEventConsumer != null) { switch (event.getType()) { case EventTypes.ACTIVATE_MIDLET_EVENT: midletEventConsumer.handleMIDletActivateEvent(); return; case EventTypes.PAUSE_MIDLET_EVENT: midletEventConsumer.handleMIDletPauseEvent(); return; case EventTypes.DESTROY_MIDLET_EVENT: midletEventConsumer.handleMIDletDestroyEvent(); return; default: if (Logging.REPORT_LEVEL <= Logging.WARNING) { Logging.report(Logging.WARNING, LogChannels.LC_CORE, "unknown system event (" + event.getType() + ")"); } } } } }
gpl-2.0
simplyianm/stanford-corenlp
src/main/java/edu/stanford/nlp/util/Generics.java
4765
package edu.stanford.nlp.util; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.Collection; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.Map; import java.util.SortedSet; import java.util.Stack; import java.util.TreeMap; import java.util.TreeSet; import java.util.WeakHashMap; import java.util.concurrent.ConcurrentHashMap; import edu.stanford.nlp.util.concurrent.SynchronizedInterner; /** * A collection of utilities to make dealing with Java generics less * painful and verbose. For example, rather than declaring * * <pre> * {@code Map<String, List<Pair<IndexedWord, GrammaticalRelation>>> = new HashMap<String, List<Pair<IndexedWord, GrammaticalRelation>>>()} * </pre> * * you just call <code>Generics.newHashMap()</code>: * * <pre> * {@code Map<String, List<Pair<IndexedWord, GrammaticalRelation>>> = Generics.newHashMap()} * </pre> * * Java type-inference will almost always just <em>do the right thing</em> * (every once in a while, the compiler will get confused before you do, * so you might still occasionally have to specify the appropriate types). * * This class is based on the examples in Brian Goetz's article * <a href="http://www.ibm.com/developerworks/library/j-jtp02216.html">Java * theory and practice: The pseudo-typedef antipattern</a>. * * @author Ilya Sherman */ public class Generics { private Generics() {} // static class /* Collections */ public static <E> ArrayList<E> newArrayList() { return new ArrayList<E>(); } public static <E> ArrayList<E> newArrayList(int size) { return new ArrayList<E>(size); } public static <E> ArrayList<E> newArrayList(Collection<? extends E> c) { return new ArrayList<E>(c); } public static <E> LinkedList<E> newLinkedList() { return new LinkedList<E>(); } public static <E> LinkedList<E> newLinkedList(Collection<? extends E> c) { return new LinkedList<E>(c); } public static <E> HashSet<E> newHashSet() { return new HashSet<E>(); } public static <E> HashSet<E> newHashSet(int initialCapacity) { return new HashSet<E>(initialCapacity); } public static <E> HashSet<E> newHashSet(Collection<? extends E> c) { return new HashSet<E>(c); } public static <E> TreeSet<E> newTreeSet() { return new TreeSet<E>(); } public static <E> TreeSet<E> newTreeSet(Comparator<? super E> comparator) { return new TreeSet<E>(comparator); } public static <E> TreeSet<E> newTreeSet(SortedSet<E> s) { return new TreeSet<E>(s); } public static <E> Stack<E> newStack() { return new Stack<E>(); } public static <E> BinaryHeapPriorityQueue<E> newBinaryHeapPriorityQueue() { return new BinaryHeapPriorityQueue<E>(); } /* Maps */ public static <K,V> HashMap<K,V> newHashMap() { return new HashMap<K,V>(); } public static <K,V> HashMap<K,V> newHashMap(int initialCapacity) { return new HashMap<K,V>(initialCapacity); } public static <K,V> HashMap<K,V> newHashMap(Map<? extends K,? extends V> m) { return new HashMap<K,V>(m); } public static <K,V> WeakHashMap<K,V> newWeakHashMap() { return new WeakHashMap<K,V>(); } public static <K,V> ConcurrentHashMap<K,V> newConcurrentHashMap() { return new ConcurrentHashMap<K,V>(); } public static <K,V> ConcurrentHashMap<K,V> newConcurrentHashMap(int initialCapacity) { return new ConcurrentHashMap<K,V>(initialCapacity); } public static <K,V> ConcurrentHashMap<K,V> newConcurrentHashMap(int initialCapacity, float loadFactor, int concurrencyLevel) { return new ConcurrentHashMap<K,V>(initialCapacity, loadFactor, concurrencyLevel); } public static <K,V> TreeMap<K,V> newTreeMap() { return new TreeMap<K,V>(); } public static <E> Index<E> newIndex() { return new HashIndex<E>(); } /* Other */ public static <T1,T2> Pair<T1,T2> newPair(T1 first, T2 second) { return new Pair<T1,T2>(first, second); } public static <T1,T2, T3> Triple<T1,T2, T3> newTriple(T1 first, T2 second, T3 third) { return new Triple<T1,T2, T3>(first, second, third); } public static <T> Interner<T> newInterner() { return new Interner<T>(); } public static <T> SynchronizedInterner<T> newSynchronizedInterner(Interner<T> interner) { return new SynchronizedInterner<T>(interner); } public static <T> SynchronizedInterner<T> newSynchronizedInterner(Interner<T> interner, Object mutex) { return new SynchronizedInterner<T>(interner, mutex); } public static <T> WeakReference<T> newWeakReference(T referent) { return new WeakReference<T>(referent); } }
gpl-2.0
mateor/PDroidHistory
frameworks/base/core/java/android/content/ContentUris.java
2104
/* * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.content; import android.net.Uri; /** * Utility methods useful for working with content {@link android.net.Uri}s, * those with a "content" scheme. */ public class ContentUris { /** * Converts the last path segment to a long. * * <p>This supports a common convention for content URIs where an ID is * stored in the last segment. * * @throws UnsupportedOperationException if this isn't a hierarchical URI * @throws NumberFormatException if the last segment isn't a number * * @return the long conversion of the last segment or -1 if the path is * empty */ public static long parseId(Uri contentUri) { String last = contentUri.getLastPathSegment(); return last == null ? -1 : Long.parseLong(last); } /** * Appends the given ID to the end of the path. * * @param builder to append the ID to * @param id to append * * @return the given builder */ public static Uri.Builder appendId(Uri.Builder builder, long id) { return builder.appendEncodedPath(String.valueOf(id)); } /** * Appends the given ID to the end of the path. * * @param contentUri to start with * @param id to append * * @return a new URI with the given ID appended to the end of the path */ public static Uri withAppendedId(Uri contentUri, long id) { return appendId(contentUri.buildUpon(), id).build(); } }
gpl-3.0
jaechoon2/droidar
droidar/src/gui/simpleUI/modifiers/IntModifier.java
1723
package gui.simpleUI.modifiers; import gui.simpleUI.AbstractModifier; import gui.simpleUI.SimpleUIv1; import util.Log; import android.content.Context; import android.view.Gravity; import android.view.View; import android.view.ViewGroup.LayoutParams; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.TextView; public abstract class IntModifier extends AbstractModifier { private EditText e; public abstract int load(); public abstract String getVarName(); public abstract boolean save(int newValue); @Override public View getView(Context context) { LinearLayout l = new LinearLayout(context); l.setGravity(Gravity.CENTER_VERTICAL); LayoutParams p = new LinearLayout.LayoutParams( LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT, 2); LayoutParams p2 = new LinearLayout.LayoutParams( LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT, 1); TextView t = new TextView(context); t.setLayoutParams(p); t.setText(this.getVarName()); l.addView(t); // TODO replace by better view representative: e = new EditText(context); e.setLayoutParams(p2); e.setText("" + load()); l.addView(e); l.setPadding(SimpleUIv1.DEFAULT_PADDING, SimpleUIv1.DEFAULT_PADDING, SimpleUIv1.DEFAULT_PADDING, SimpleUIv1.DEFAULT_PADDING); if (getTheme() != null) { getTheme().applyOuter1(l); getTheme().applyNormal1(t); getTheme().applyNormal1(e); } return l; } @Override public boolean save() { try { return save(Integer.parseInt(e.getText().toString())); } catch (NumberFormatException e) { // TODO show toast? Log.e("EditScreen", "The entered value for " + getVarName() + " was no number!"); } return false; } }
gpl-3.0
ceabie/jfreechart
source/org/jfree/chart/plot/ContourPlot.java
59758
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2014, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ---------------- * ContourPlot.java * ---------------- * (C) Copyright 2002-2014, by David M. O'Donnell and Contributors. * * Original Author: David M. O'Donnell; * Contributor(s): David Gilbert (for Object Refinery Limited); * Arnaud Lelievre; * Nicolas Brodu; * * Changes * ------- * 26-Nov-2002 : Version 1 contributed by David M. O'Donnell (DG); * 14-Jan-2003 : Added crosshair attributes (DG); * 23-Jan-2003 : Removed two constructors (DG); * 21-Mar-2003 : Bug fix 701744 (DG); * 26-Mar-2003 : Implemented Serializable (DG); * 09-Jul-2003 : Changed ColorBar from extending axis classes to enclosing * them (DG); * 05-Aug-2003 : Applied changes in bug report 780298 (DG); * 08-Sep-2003 : Added internationalization via use of properties * resourceBundle (RFE 690236) (AL); * 11-Sep-2003 : Cloning support (NB); * 16-Sep-2003 : Changed ChartRenderingInfo --> PlotRenderingInfo (DG); * 17-Jan-2004 : Removed references to DefaultContourDataset class, replaced * with ContourDataset interface (with changes to the interface). * See bug 741048 (DG); * 21-Jan-2004 : Update for renamed method in ValueAxis (DG); * 25-Feb-2004 : Replaced CrosshairInfo with CrosshairState (DG); * 06-Oct-2004 : Updated for changes in DatasetUtilities class (DG); * 11-Nov-2004 : Renamed zoom methods to match ValueAxisPlot interface (DG); * 25-Nov-2004 : Small update to clone() implementation (DG); * 11-Jan-2005 : Removed deprecated code in preparation for 1.0.0 release (DG); * 05-May-2005 : Updated draw() method parameters (DG); * 16-Jun-2005 : Added default constructor (DG); * 01-Sep-2005 : Moved dataAreaRatio from Plot to here (DG); * ------------- JFREECHART 1.0.x --------------------------------------------- * 31-Jan-2007 : Deprecated (DG); * 18-Dec-2008 : Use ResourceBundleWrapper - see patch 1607918 by * Jess Thrysoee (DG); * 19-May-2009 : Fixed FindBugs warnings, patch by Michal Wozniak (DG); * 02-Jul-2013 : Fix NB warnings (DG); * */ package org.jfree.chart.plot; import java.awt.AlphaComposite; import java.awt.Composite; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.RenderingHints; import java.awt.Shape; import java.awt.Stroke; import java.awt.geom.Ellipse2D; import java.awt.geom.GeneralPath; import java.awt.geom.Line2D; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.awt.geom.RectangularShape; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.Serializable; import java.util.Iterator; import java.util.List; import java.util.ResourceBundle; import org.jfree.chart.ClipPath; import org.jfree.chart.annotations.XYAnnotation; import org.jfree.chart.axis.AxisSpace; import org.jfree.chart.axis.ColorBar; import org.jfree.chart.axis.NumberAxis; import org.jfree.chart.axis.ValueAxis; import org.jfree.chart.entity.ContourEntity; import org.jfree.chart.entity.EntityCollection; import org.jfree.chart.event.AxisChangeEvent; import org.jfree.chart.event.PlotChangeEvent; import org.jfree.chart.labels.ContourToolTipGenerator; import org.jfree.chart.labels.StandardContourToolTipGenerator; import org.jfree.chart.renderer.xy.XYBlockRenderer; import org.jfree.chart.urls.XYURLGenerator; import org.jfree.chart.util.ResourceBundleWrapper; import org.jfree.data.Range; import org.jfree.data.contour.ContourDataset; import org.jfree.data.general.DatasetChangeEvent; import org.jfree.data.general.DatasetUtilities; import org.jfree.ui.RectangleEdge; import org.jfree.ui.RectangleInsets; import org.jfree.util.ObjectUtilities; /** * A class for creating shaded contours. * * @deprecated This plot is no longer supported, please use {@link XYPlot} with * an {@link XYBlockRenderer}. */ public class ContourPlot extends Plot implements ContourValuePlot, ValueAxisPlot, PropertyChangeListener, Serializable, Cloneable { /** For serialization. */ private static final long serialVersionUID = 7861072556590502247L; /** The default insets. */ protected static final RectangleInsets DEFAULT_INSETS = new RectangleInsets(2.0, 2.0, 100.0, 10.0); /** The domain axis (used for the x-values). */ private ValueAxis domainAxis; /** The range axis (used for the y-values). */ private ValueAxis rangeAxis; /** The dataset. */ private ContourDataset dataset; /** The colorbar axis (used for the z-values). */ private ColorBar colorBar = null; /** The color bar location. */ private RectangleEdge colorBarLocation; /** A flag that controls whether or not a domain crosshair is drawn..*/ private boolean domainCrosshairVisible; /** The domain crosshair value. */ private double domainCrosshairValue; /** The pen/brush used to draw the crosshair (if any). */ private transient Stroke domainCrosshairStroke; /** The color used to draw the crosshair (if any). */ private transient Paint domainCrosshairPaint; /** * A flag that controls whether or not the crosshair locks onto actual data * points. */ private boolean domainCrosshairLockedOnData = true; /** A flag that controls whether or not a range crosshair is drawn..*/ private boolean rangeCrosshairVisible; /** The range crosshair value. */ private double rangeCrosshairValue; /** The pen/brush used to draw the crosshair (if any). */ private transient Stroke rangeCrosshairStroke; /** The color used to draw the crosshair (if any). */ private transient Paint rangeCrosshairPaint; /** * A flag that controls whether or not the crosshair locks onto actual data * points. */ private boolean rangeCrosshairLockedOnData = true; /** * Defines dataArea rectangle as the ratio formed from dividing height by * width (of the dataArea). Modifies plot area calculations. * ratio &gt; 0 will attempt to layout the plot so that the * dataArea.height/dataArea.width = ratio. * ratio &lt; 0 will attempt to layout the plot so that the * dataArea.height/dataArea.width in plot units (not java2D units as when * ratio &gt; 0) = -1.*ratio. */ //dmo private double dataAreaRatio = 0.0; //zero when the parameter is not set /** A list of markers (optional) for the domain axis. */ private List domainMarkers; /** A list of markers (optional) for the range axis. */ private List rangeMarkers; /** A list of annotations (optional) for the plot. */ private List annotations; /** The tool tip generator. */ private ContourToolTipGenerator toolTipGenerator; /** The URL text generator. */ private XYURLGenerator urlGenerator; /** * Controls whether data are render as filled rectangles or rendered as * points */ private boolean renderAsPoints = false; /** * Size of points rendered when renderAsPoints = true. Size is relative to * dataArea */ private double ptSizePct = 0.05; /** Contains the a ClipPath to "trim" the contours. */ private transient ClipPath clipPath = null; /** Set to Paint to represent missing values. */ private transient Paint missingPaint = null; /** The resourceBundle for the localization. */ protected static ResourceBundle localizationResources = ResourceBundleWrapper.getBundle( "org.jfree.chart.plot.LocalizationBundle"); /** * Creates a new plot with no dataset or axes. */ public ContourPlot() { this(null, null, null, null); } /** * Constructs a contour plot with the specified axes (other attributes take * default values). * * @param dataset The dataset. * @param domainAxis The domain axis. * @param rangeAxis The range axis. * @param colorBar The z-axis axis. */ public ContourPlot(ContourDataset dataset, ValueAxis domainAxis, ValueAxis rangeAxis, ColorBar colorBar) { super(); this.dataset = dataset; if (dataset != null) { dataset.addChangeListener(this); } this.domainAxis = domainAxis; if (domainAxis != null) { domainAxis.setPlot(this); domainAxis.addChangeListener(this); } this.rangeAxis = rangeAxis; if (rangeAxis != null) { rangeAxis.setPlot(this); rangeAxis.addChangeListener(this); } this.colorBar = colorBar; if (colorBar != null) { colorBar.getAxis().setPlot(this); colorBar.getAxis().addChangeListener(this); colorBar.configure(this); } this.colorBarLocation = RectangleEdge.LEFT; this.toolTipGenerator = new StandardContourToolTipGenerator(); } /** * Returns the color bar location. * * @return The color bar location. */ public RectangleEdge getColorBarLocation() { return this.colorBarLocation; } /** * Sets the color bar location and sends a {@link PlotChangeEvent} to all * registered listeners. * * @param edge the location. */ public void setColorBarLocation(RectangleEdge edge) { this.colorBarLocation = edge; fireChangeEvent(); } /** * Returns the primary dataset for the plot. * * @return The primary dataset (possibly <code>null</code>). */ public ContourDataset getDataset() { return this.dataset; } /** * Sets the dataset for the plot, replacing the existing dataset if there * is one. * * @param dataset the dataset (<code>null</code> permitted). */ public void setDataset(ContourDataset dataset) { // if there is an existing dataset, remove the plot from the list of // change listeners... ContourDataset existing = this.dataset; if (existing != null) { existing.removeChangeListener(this); } // set the new dataset, and register the chart as a change listener... this.dataset = dataset; if (dataset != null) { setDatasetGroup(dataset.getGroup()); dataset.addChangeListener(this); } // send a dataset change event to self... DatasetChangeEvent event = new DatasetChangeEvent(this, dataset); datasetChanged(event); } /** * Returns the domain axis for the plot. * * @return The domain axis. */ public ValueAxis getDomainAxis() { ValueAxis result = this.domainAxis; return result; } /** * Sets the domain axis for the plot (this must be compatible with the plot * type or an exception is thrown). * * @param axis The new axis. */ public void setDomainAxis(ValueAxis axis) { if (isCompatibleDomainAxis(axis)) { if (axis != null) { axis.setPlot(this); axis.addChangeListener(this); } // plot is likely registered as a listener with the existing axis... if (this.domainAxis != null) { this.domainAxis.removeChangeListener(this); } this.domainAxis = axis; fireChangeEvent(); } } /** * Returns the range axis for the plot. * * @return The range axis. */ public ValueAxis getRangeAxis() { ValueAxis result = this.rangeAxis; return result; } /** * Sets the range axis for the plot. * <P> * An exception is thrown if the new axis and the plot are not mutually * compatible. * * @param axis The new axis (null permitted). */ public void setRangeAxis(ValueAxis axis) { if (axis != null) { axis.setPlot(this); axis.addChangeListener(this); } // plot is likely registered as a listener with the existing axis... if (this.rangeAxis != null) { this.rangeAxis.removeChangeListener(this); } this.rangeAxis = axis; fireChangeEvent(); } /** * Sets the colorbar for the plot. * * @param axis The new axis (null permitted). */ public void setColorBarAxis(ColorBar axis) { this.colorBar = axis; fireChangeEvent(); } /** * Returns the data area ratio. * * @return The ratio. */ public double getDataAreaRatio() { return this.dataAreaRatio; } /** * Sets the data area ratio. * * @param ratio the ratio. */ public void setDataAreaRatio(double ratio) { this.dataAreaRatio = ratio; } /** * Adds a marker for the domain axis. * <P> * Typically a marker will be drawn by the renderer as a line perpendicular * to the range axis, however this is entirely up to the renderer. * * @param marker the marker. */ public void addDomainMarker(Marker marker) { if (this.domainMarkers == null) { this.domainMarkers = new java.util.ArrayList(); } this.domainMarkers.add(marker); fireChangeEvent(); } /** * Clears all the domain markers. */ public void clearDomainMarkers() { if (this.domainMarkers != null) { this.domainMarkers.clear(); fireChangeEvent(); } } /** * Adds a marker for the range axis. * <P> * Typically a marker will be drawn by the renderer as a line perpendicular * to the range axis, however this is entirely up to the renderer. * * @param marker The marker. */ public void addRangeMarker(Marker marker) { if (this.rangeMarkers == null) { this.rangeMarkers = new java.util.ArrayList(); } this.rangeMarkers.add(marker); fireChangeEvent(); } /** * Clears all the range markers. */ public void clearRangeMarkers() { if (this.rangeMarkers != null) { this.rangeMarkers.clear(); fireChangeEvent(); } } /** * Adds an annotation to the plot. * * @param annotation the annotation. */ public void addAnnotation(XYAnnotation annotation) { if (this.annotations == null) { this.annotations = new java.util.ArrayList(); } this.annotations.add(annotation); fireChangeEvent(); } /** * Clears all the annotations. */ public void clearAnnotations() { if (this.annotations != null) { this.annotations.clear(); fireChangeEvent(); } } /** * Checks the compatibility of a domain axis, returning true if the axis is * compatible with the plot, and false otherwise. * * @param axis The proposed axis. * * @return <code>true</code> if the axis is compatible with the plot. */ public boolean isCompatibleDomainAxis(ValueAxis axis) { return true; } /** * Draws the plot on a Java 2D graphics device (such as the screen or a * printer). * <P> * The optional <code>info</code> argument collects information about the * rendering of the plot (dimensions, tooltip information etc). Just pass * in <code>null</code> if you do not need this information. * * @param g2 the graphics device. * @param area the area within which the plot (including axis labels) * should be drawn. * @param anchor the anchor point (<code>null</code> permitted). * @param parentState the state from the parent plot, if there is one. * @param info collects chart drawing information (<code>null</code> * permitted). */ @Override public void draw(Graphics2D g2, Rectangle2D area, Point2D anchor, PlotState parentState, PlotRenderingInfo info) { // if the plot area is too small, just return... boolean b1 = (area.getWidth() <= MINIMUM_WIDTH_TO_DRAW); boolean b2 = (area.getHeight() <= MINIMUM_HEIGHT_TO_DRAW); if (b1 || b2) { return; } // record the plot area... if (info != null) { info.setPlotArea(area); } // adjust the drawing area for plot insets (if any)... RectangleInsets insets = getInsets(); insets.trim(area); AxisSpace space = new AxisSpace(); space = this.domainAxis.reserveSpace(g2, this, area, RectangleEdge.BOTTOM, space); space = this.rangeAxis.reserveSpace(g2, this, area, RectangleEdge.LEFT, space); Rectangle2D estimatedDataArea = space.shrink(area, null); AxisSpace space2 = new AxisSpace(); space2 = this.colorBar.reserveSpace(g2, this, area, estimatedDataArea, this.colorBarLocation, space2); Rectangle2D adjustedPlotArea = space2.shrink(area, null); Rectangle2D dataArea = space.shrink(adjustedPlotArea, null); Rectangle2D colorBarArea = space2.reserved(area, this.colorBarLocation); // additional dataArea modifications if (getDataAreaRatio() != 0.0) { //check whether modification is double ratio = getDataAreaRatio(); Rectangle2D tmpDataArea = (Rectangle2D) dataArea.clone(); double h = tmpDataArea.getHeight(); double w = tmpDataArea.getWidth(); if (ratio > 0) { // ratio represents pixels if (w * ratio <= h) { h = ratio * w; } else { w = h / ratio; } } else { // ratio represents axis units ratio *= -1.0; double xLength = getDomainAxis().getRange().getLength(); double yLength = getRangeAxis().getRange().getLength(); double unitRatio = yLength / xLength; ratio = unitRatio * ratio; if (w * ratio <= h) { h = ratio * w; } else { w = h / ratio; } } dataArea.setRect(tmpDataArea.getX() + tmpDataArea.getWidth() / 2 - w / 2, tmpDataArea.getY(), w, h); } if (info != null) { info.setDataArea(dataArea); } CrosshairState crosshairState = new CrosshairState(); crosshairState.setCrosshairDistance(Double.POSITIVE_INFINITY); // draw the plot background... drawBackground(g2, dataArea); double cursor = dataArea.getMaxY(); if (this.domainAxis != null) { this.domainAxis.draw(g2, cursor, adjustedPlotArea, dataArea, RectangleEdge.BOTTOM, info); } if (this.rangeAxis != null) { cursor = dataArea.getMinX(); this.rangeAxis.draw(g2, cursor, adjustedPlotArea, dataArea, RectangleEdge.LEFT, info); } if (this.colorBar != null) { cursor = 0.0; this.colorBar.draw(g2, cursor, adjustedPlotArea, dataArea, colorBarArea, this.colorBarLocation); } Shape originalClip = g2.getClip(); Composite originalComposite = g2.getComposite(); g2.clip(dataArea); g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, getForegroundAlpha())); render(g2, dataArea, info, crosshairState); if (this.domainMarkers != null) { Iterator iterator = this.domainMarkers.iterator(); while (iterator.hasNext()) { Marker marker = (Marker) iterator.next(); drawDomainMarker(g2, this, getDomainAxis(), marker, dataArea); } } if (this.rangeMarkers != null) { Iterator iterator = this.rangeMarkers.iterator(); while (iterator.hasNext()) { Marker marker = (Marker) iterator.next(); drawRangeMarker(g2, this, getRangeAxis(), marker, dataArea); } } // TO DO: these annotations only work with XYPlot, see if it is possible to // make ContourPlot a subclass of XYPlot (DG); // // draw the annotations... // if (this.annotations != null) { // Iterator iterator = this.annotations.iterator(); // while (iterator.hasNext()) { // Annotation annotation = (Annotation) iterator.next(); // if (annotation instanceof XYAnnotation) { // XYAnnotation xya = (XYAnnotation) annotation; // // get the annotation to draw itself... // xya.draw(g2, this, dataArea, getDomainAxis(), // getRangeAxis()); // } // } // } g2.setClip(originalClip); g2.setComposite(originalComposite); drawOutline(g2, dataArea); } /** * Draws a representation of the data within the dataArea region, using the * current renderer. * <P> * The <code>info</code> and <code>crosshairState</code> arguments may be * <code>null</code>. * * @param g2 the graphics device. * @param dataArea the region in which the data is to be drawn. * @param info an optional object for collection dimension information. * @param crosshairState an optional object for collecting crosshair info. */ public void render(Graphics2D g2, Rectangle2D dataArea, PlotRenderingInfo info, CrosshairState crosshairState) { // now get the data and plot it (the visual representation will depend // on the renderer that has been set)... ContourDataset data = getDataset(); if (data != null) { ColorBar zAxis = getColorBar(); if (this.clipPath != null) { GeneralPath clipper = getClipPath().draw(g2, dataArea, this.domainAxis, this.rangeAxis); if (this.clipPath.isClip()) { g2.clip(clipper); } } if (this.renderAsPoints) { pointRenderer(g2, dataArea, info, this, this.domainAxis, this.rangeAxis, zAxis, data, crosshairState); } else { contourRenderer(g2, dataArea, info, this, this.domainAxis, this.rangeAxis, zAxis, data, crosshairState); } // draw vertical crosshair if required... setDomainCrosshairValue(crosshairState.getCrosshairX(), false); if (isDomainCrosshairVisible()) { drawVerticalLine(g2, dataArea, getDomainCrosshairValue(), getDomainCrosshairStroke(), getDomainCrosshairPaint()); } // draw horizontal crosshair if required... setRangeCrosshairValue(crosshairState.getCrosshairY(), false); if (isRangeCrosshairVisible()) { drawHorizontalLine(g2, dataArea, getRangeCrosshairValue(), getRangeCrosshairStroke(), getRangeCrosshairPaint()); } } else if (this.clipPath != null) { getClipPath().draw(g2, dataArea, this.domainAxis, this.rangeAxis); } } /** * Fills the plot. * * @param g2 the graphics device. * @param dataArea the area within which the data is being drawn. * @param info collects information about the drawing. * @param plot the plot (can be used to obtain standard color * information etc). * @param horizontalAxis the domain (horizontal) axis. * @param verticalAxis the range (vertical) axis. * @param colorBar the color bar axis. * @param data the dataset. * @param crosshairState information about crosshairs on a plot. */ public void contourRenderer(Graphics2D g2, Rectangle2D dataArea, PlotRenderingInfo info, ContourPlot plot, ValueAxis horizontalAxis, ValueAxis verticalAxis, ColorBar colorBar, ContourDataset data, CrosshairState crosshairState) { // setup for collecting optional entity info... Rectangle2D.Double entityArea; EntityCollection entities = null; if (info != null) { entities = info.getOwner().getEntityCollection(); } Rectangle2D.Double rect; rect = new Rectangle2D.Double(); //turn off anti-aliasing when filling rectangles Object antiAlias = g2.getRenderingHint(RenderingHints.KEY_ANTIALIASING); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); // get the data points Number[] xNumber = data.getXValues(); Number[] yNumber = data.getYValues(); Number[] zNumber = data.getZValues(); double[] x = new double[xNumber.length]; double[] y = new double[yNumber.length]; for (int i = 0; i < x.length; i++) { x[i] = xNumber[i].doubleValue(); y[i] = yNumber[i].doubleValue(); } int[] xIndex = data.indexX(); int[] indexX = data.getXIndices(); boolean vertInverted = ((NumberAxis) verticalAxis).isInverted(); boolean horizInverted = false; if (horizontalAxis instanceof NumberAxis) { horizInverted = ((NumberAxis) horizontalAxis).isInverted(); } double transX = 0.0; double transXm1; double transXp1; double transDXm1; double transDXp1 = 0.0; double transDX = 0.0; double transY; double transYm1; double transYp1; double transDYm1; double transDYp1 = 0.0; double transDY; int iMax = xIndex[xIndex.length - 1]; for (int k = 0; k < x.length; k++) { int i = xIndex[k]; if (indexX[i] == k) { // this is a new column if (i == 0) { transX = horizontalAxis.valueToJava2D(x[k], dataArea, RectangleEdge.BOTTOM); transXm1 = transX; transXp1 = horizontalAxis.valueToJava2D( x[indexX[i + 1]], dataArea, RectangleEdge.BOTTOM); transDXm1 = Math.abs(0.5 * (transX - transXm1)); transDXp1 = Math.abs(0.5 * (transX - transXp1)); } else if (i == iMax) { transX = horizontalAxis.valueToJava2D(x[k], dataArea, RectangleEdge.BOTTOM); transXm1 = horizontalAxis.valueToJava2D(x[indexX[i - 1]], dataArea, RectangleEdge.BOTTOM); transXp1 = transX; transDXm1 = Math.abs(0.5 * (transX - transXm1)); transDXp1 = Math.abs(0.5 * (transX - transXp1)); } else { transX = horizontalAxis.valueToJava2D(x[k], dataArea, RectangleEdge.BOTTOM); transXp1 = horizontalAxis.valueToJava2D(x[indexX[i + 1]], dataArea, RectangleEdge.BOTTOM); transDXm1 = transDXp1; transDXp1 = Math.abs(0.5 * (transX - transXp1)); } if (horizInverted) { transX -= transDXp1; } else { transX -= transDXm1; } transDX = transDXm1 + transDXp1; transY = verticalAxis.valueToJava2D(y[k], dataArea, RectangleEdge.LEFT); transYm1 = transY; if (k + 1 == y.length) { continue; } transYp1 = verticalAxis.valueToJava2D(y[k + 1], dataArea, RectangleEdge.LEFT); transDYm1 = Math.abs(0.5 * (transY - transYm1)); transDYp1 = Math.abs(0.5 * (transY - transYp1)); } else if ((i < indexX.length - 1 && indexX[i + 1] - 1 == k) || k == x.length - 1) { // end of column transY = verticalAxis.valueToJava2D(y[k], dataArea, RectangleEdge.LEFT); transYm1 = verticalAxis.valueToJava2D(y[k - 1], dataArea, RectangleEdge.LEFT); transYp1 = transY; transDYm1 = Math.abs(0.5 * (transY - transYm1)); transDYp1 = Math.abs(0.5 * (transY - transYp1)); } else { transY = verticalAxis.valueToJava2D(y[k], dataArea, RectangleEdge.LEFT); transYp1 = verticalAxis.valueToJava2D(y[k + 1], dataArea, RectangleEdge.LEFT); transDYm1 = transDYp1; transDYp1 = Math.abs(0.5 * (transY - transYp1)); } if (vertInverted) { transY -= transDYm1; } else { transY -= transDYp1; } transDY = transDYm1 + transDYp1; rect.setRect(transX, transY, transDX, transDY); if (zNumber[k] != null) { g2.setPaint(colorBar.getPaint(zNumber[k].doubleValue())); g2.fill(rect); } else if (this.missingPaint != null) { g2.setPaint(this.missingPaint); g2.fill(rect); } entityArea = rect; // add an entity for the item... if (entities != null) { String tip = ""; if (getToolTipGenerator() != null) { tip = this.toolTipGenerator.generateToolTip(data, k); } // Shape s = g2.getClip(); // if (s.contains(rect) || s.intersects(rect)) { String url = null; // if (getURLGenerator() != null) { //dmo: look at this later // url = getURLGenerator().generateURL(data, series, item); // } // Unlike XYItemRenderer, we need to clone entityArea since it // reused. ContourEntity entity = new ContourEntity( (Rectangle2D.Double) entityArea.clone(), tip, url); entity.setIndex(k); entities.add(entity); // } } // do we need to update the crosshair values? if (plot.isDomainCrosshairLockedOnData()) { if (plot.isRangeCrosshairLockedOnData()) { // both axes crosshairState.updateCrosshairPoint(x[k], y[k], transX, transY, PlotOrientation.VERTICAL); } else { // just the horizontal axis... crosshairState.updateCrosshairX(transX); } } else { if (plot.isRangeCrosshairLockedOnData()) { // just the vertical axis... crosshairState.updateCrosshairY(transY); } } } g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, antiAlias); } /** * Draws the visual representation of a single data item. * * @param g2 the graphics device. * @param dataArea the area within which the data is being drawn. * @param info collects information about the drawing. * @param plot the plot (can be used to obtain standard color * information etc). * @param domainAxis the domain (horizontal) axis. * @param rangeAxis the range (vertical) axis. * @param colorBar the color bar axis. * @param data the dataset. * @param crosshairState information about crosshairs on a plot. */ public void pointRenderer(Graphics2D g2, Rectangle2D dataArea, PlotRenderingInfo info, ContourPlot plot, ValueAxis domainAxis, ValueAxis rangeAxis, ColorBar colorBar, ContourDataset data, CrosshairState crosshairState) { // setup for collecting optional entity info... RectangularShape entityArea; EntityCollection entities = null; if (info != null) { entities = info.getOwner().getEntityCollection(); } // Rectangle2D.Double rect = null; // rect = new Rectangle2D.Double(); RectangularShape rect = new Ellipse2D.Double(); //turn off anti-aliasing when filling rectangles Object antiAlias = g2.getRenderingHint(RenderingHints.KEY_ANTIALIASING); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); // if (tooltips!=null) tooltips.clearToolTips(); // reset collection // get the data points Number[] xNumber = data.getXValues(); Number[] yNumber = data.getYValues(); Number[] zNumber = data.getZValues(); double[] x = new double[xNumber.length]; double[] y = new double[yNumber.length]; for (int i = 0; i < x.length; i++) { x[i] = xNumber[i].doubleValue(); y[i] = yNumber[i].doubleValue(); } double transX; double transDX; double transY; double transDY; double size = dataArea.getWidth() * this.ptSizePct; for (int k = 0; k < x.length; k++) { transX = domainAxis.valueToJava2D(x[k], dataArea, RectangleEdge.BOTTOM) - 0.5 * size; transY = rangeAxis.valueToJava2D(y[k], dataArea, RectangleEdge.LEFT) - 0.5 * size; transDX = size; transDY = size; rect.setFrame(transX, transY, transDX, transDY); if (zNumber[k] != null) { g2.setPaint(colorBar.getPaint(zNumber[k].doubleValue())); g2.fill(rect); } else if (this.missingPaint != null) { g2.setPaint(this.missingPaint); g2.fill(rect); } entityArea = rect; // add an entity for the item... if (entities != null) { String tip = null; if (getToolTipGenerator() != null) { tip = this.toolTipGenerator.generateToolTip(data, k); } String url = null; // if (getURLGenerator() != null) { //dmo: look at this later // url = getURLGenerator().generateURL(data, series, item); // } // Unlike XYItemRenderer, we need to clone entityArea since it // reused. ContourEntity entity = new ContourEntity( (RectangularShape) entityArea.clone(), tip, url); entity.setIndex(k); entities.add(entity); } // do we need to update the crosshair values? if (plot.isDomainCrosshairLockedOnData()) { if (plot.isRangeCrosshairLockedOnData()) { // both axes crosshairState.updateCrosshairPoint(x[k], y[k], transX, transY, PlotOrientation.VERTICAL); } else { // just the horizontal axis... crosshairState.updateCrosshairX(transX); } } else { if (plot.isRangeCrosshairLockedOnData()) { // just the vertical axis... crosshairState.updateCrosshairY(transY); } } } g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, antiAlias); } /** * Utility method for drawing a crosshair on the chart (if required). * * @param g2 The graphics device. * @param dataArea The data area. * @param value The coordinate, where to draw the line. * @param stroke The stroke to use. * @param paint The paint to use. */ protected void drawVerticalLine(Graphics2D g2, Rectangle2D dataArea, double value, Stroke stroke, Paint paint) { double xx = getDomainAxis().valueToJava2D(value, dataArea, RectangleEdge.BOTTOM); Line2D line = new Line2D.Double(xx, dataArea.getMinY(), xx, dataArea.getMaxY()); g2.setStroke(stroke); g2.setPaint(paint); g2.draw(line); } /** * Utility method for drawing a crosshair on the chart (if required). * * @param g2 The graphics device. * @param dataArea The data area. * @param value The coordinate, where to draw the line. * @param stroke The stroke to use. * @param paint The paint to use. */ protected void drawHorizontalLine(Graphics2D g2, Rectangle2D dataArea, double value, Stroke stroke, Paint paint) { double yy = getRangeAxis().valueToJava2D(value, dataArea, RectangleEdge.LEFT); Line2D line = new Line2D.Double(dataArea.getMinX(), yy, dataArea.getMaxX(), yy); g2.setStroke(stroke); g2.setPaint(paint); g2.draw(line); } /** * Handles a 'click' on the plot by updating the anchor values... * * @param x x-coordinate, where the click occured. * @param y y-coordinate, where the click occured. * @param info An object for collection dimension information. */ @Override public void handleClick(int x, int y, PlotRenderingInfo info) { /* // set the anchor value for the horizontal axis... ValueAxis hva = getDomainAxis(); if (hva != null) { double hvalue = hva.translateJava2DtoValue( (float) x, info.getDataArea() ); hva.setAnchorValue(hvalue); setDomainCrosshairValue(hvalue); } // set the anchor value for the vertical axis... ValueAxis vva = getRangeAxis(); if (vva != null) { double vvalue = vva.translateJava2DtoValue( (float) y, info.getDataArea() ); vva.setAnchorValue(vvalue); setRangeCrosshairValue(vvalue); } */ } /** * Zooms the axis ranges by the specified percentage about the anchor point. * * @param percent The amount of the zoom. */ @Override public void zoom(double percent) { if (percent > 0) { // double range = this.domainAxis.getRange().getLength(); // double scaledRange = range * percent; // domainAxis.setAnchoredRange(scaledRange); // range = this.rangeAxis.getRange().getLength(); // scaledRange = range * percent; // rangeAxis.setAnchoredRange(scaledRange); } else { getRangeAxis().setAutoRange(true); getDomainAxis().setAutoRange(true); } } /** * Returns the plot type as a string. * * @return A short string describing the type of plot. */ @Override public String getPlotType() { return localizationResources.getString("Contour_Plot"); } /** * Returns the range for an axis. * * @param axis the axis. * * @return The range for an axis. */ @Override public Range getDataRange(ValueAxis axis) { if (this.dataset == null) { return null; } Range result = null; if (axis == getDomainAxis()) { result = DatasetUtilities.findDomainBounds(this.dataset); } else if (axis == getRangeAxis()) { result = DatasetUtilities.findRangeBounds(this.dataset); } return result; } /** * Returns the range for the Contours. * * @return The range for the Contours (z-axis). */ @Override public Range getContourDataRange() { Range result = null; ContourDataset data = getDataset(); if (data != null) { Range h = getDomainAxis().getRange(); Range v = getRangeAxis().getRange(); result = this.visibleRange(data, h, v); } return result; } /** * Notifies all registered listeners of a property change. * <P> * One source of property change events is the plot's renderer. * * @param event Information about the property change. */ @Override public void propertyChange(PropertyChangeEvent event) { fireChangeEvent(); } /** * Receives notification of a change to the plot's dataset. * <P> * The chart reacts by passing on a chart change event to all registered * listeners. * * @param event Information about the event (not used here). */ @Override public void datasetChanged(DatasetChangeEvent event) { if (this.domainAxis != null) { this.domainAxis.configure(); } if (this.rangeAxis != null) { this.rangeAxis.configure(); } if (this.colorBar != null) { this.colorBar.configure(this); } super.datasetChanged(event); } /** * Returns the colorbar. * * @return The colorbar. */ public ColorBar getColorBar() { return this.colorBar; } /** * Returns a flag indicating whether or not the domain crosshair is visible. * * @return The flag. */ public boolean isDomainCrosshairVisible() { return this.domainCrosshairVisible; } /** * Sets the flag indicating whether or not the domain crosshair is visible. * * @param flag the new value of the flag. */ public void setDomainCrosshairVisible(boolean flag) { if (this.domainCrosshairVisible != flag) { this.domainCrosshairVisible = flag; fireChangeEvent(); } } /** * Returns a flag indicating whether or not the crosshair should "lock-on" * to actual data values. * * @return The flag. */ public boolean isDomainCrosshairLockedOnData() { return this.domainCrosshairLockedOnData; } /** * Sets the flag indicating whether or not the domain crosshair should * "lock-on" to actual data values. * * @param flag the flag. */ public void setDomainCrosshairLockedOnData(boolean flag) { if (this.domainCrosshairLockedOnData != flag) { this.domainCrosshairLockedOnData = flag; fireChangeEvent(); } } /** * Returns the domain crosshair value. * * @return The value. */ public double getDomainCrosshairValue() { return this.domainCrosshairValue; } /** * Sets the domain crosshair value. * <P> * Registered listeners are notified that the plot has been modified, but * only if the crosshair is visible. * * @param value the new value. */ public void setDomainCrosshairValue(double value) { setDomainCrosshairValue(value, true); } /** * Sets the domain crosshair value. * <P> * Registered listeners are notified that the axis has been modified, but * only if the crosshair is visible. * * @param value the new value. * @param notify a flag that controls whether or not listeners are * notified. */ public void setDomainCrosshairValue(double value, boolean notify) { this.domainCrosshairValue = value; if (isDomainCrosshairVisible() && notify) { fireChangeEvent(); } } /** * Returns the Stroke used to draw the crosshair (if visible). * * @return The crosshair stroke. */ public Stroke getDomainCrosshairStroke() { return this.domainCrosshairStroke; } /** * Sets the Stroke used to draw the crosshairs (if visible) and notifies * registered listeners that the axis has been modified. * * @param stroke the new crosshair stroke. */ public void setDomainCrosshairStroke(Stroke stroke) { this.domainCrosshairStroke = stroke; fireChangeEvent(); } /** * Returns the domain crosshair color. * * @return The crosshair color. */ public Paint getDomainCrosshairPaint() { return this.domainCrosshairPaint; } /** * Sets the Paint used to color the crosshairs (if visible) and notifies * registered listeners that the axis has been modified. * * @param paint the new crosshair paint. */ public void setDomainCrosshairPaint(Paint paint) { this.domainCrosshairPaint = paint; fireChangeEvent(); } /** * Returns a flag indicating whether or not the range crosshair is visible. * * @return The flag. */ public boolean isRangeCrosshairVisible() { return this.rangeCrosshairVisible; } /** * Sets the flag indicating whether or not the range crosshair is visible. * * @param flag the new value of the flag. */ public void setRangeCrosshairVisible(boolean flag) { if (this.rangeCrosshairVisible != flag) { this.rangeCrosshairVisible = flag; fireChangeEvent(); } } /** * Returns a flag indicating whether or not the crosshair should "lock-on" * to actual data values. * * @return The flag. */ public boolean isRangeCrosshairLockedOnData() { return this.rangeCrosshairLockedOnData; } /** * Sets the flag indicating whether or not the range crosshair should * "lock-on" to actual data values. * * @param flag the flag. */ public void setRangeCrosshairLockedOnData(boolean flag) { if (this.rangeCrosshairLockedOnData != flag) { this.rangeCrosshairLockedOnData = flag; fireChangeEvent(); } } /** * Returns the range crosshair value. * * @return The value. */ public double getRangeCrosshairValue() { return this.rangeCrosshairValue; } /** * Sets the domain crosshair value. * <P> * Registered listeners are notified that the plot has been modified, but * only if the crosshair is visible. * * @param value the new value. */ public void setRangeCrosshairValue(double value) { setRangeCrosshairValue(value, true); } /** * Sets the range crosshair value. * <P> * Registered listeners are notified that the axis has been modified, but * only if the crosshair is visible. * * @param value the new value. * @param notify a flag that controls whether or not listeners are * notified. */ public void setRangeCrosshairValue(double value, boolean notify) { this.rangeCrosshairValue = value; if (isRangeCrosshairVisible() && notify) { fireChangeEvent(); } } /** * Returns the Stroke used to draw the crosshair (if visible). * * @return The crosshair stroke. */ public Stroke getRangeCrosshairStroke() { return this.rangeCrosshairStroke; } /** * Sets the Stroke used to draw the crosshairs (if visible) and notifies * registered listeners that the axis has been modified. * * @param stroke the new crosshair stroke. */ public void setRangeCrosshairStroke(Stroke stroke) { this.rangeCrosshairStroke = stroke; fireChangeEvent(); } /** * Returns the range crosshair color. * * @return The crosshair color. */ public Paint getRangeCrosshairPaint() { return this.rangeCrosshairPaint; } /** * Sets the Paint used to color the crosshairs (if visible) and notifies * registered listeners that the axis has been modified. * * @param paint the new crosshair paint. */ public void setRangeCrosshairPaint(Paint paint) { this.rangeCrosshairPaint = paint; fireChangeEvent(); } /** * Returns the tool tip generator. * * @return The tool tip generator (possibly null). */ public ContourToolTipGenerator getToolTipGenerator() { return this.toolTipGenerator; } /** * Sets the tool tip generator. * * @param generator the tool tip generator (null permitted). */ public void setToolTipGenerator(ContourToolTipGenerator generator) { //Object oldValue = this.toolTipGenerator; this.toolTipGenerator = generator; } /** * Returns the URL generator for HTML image maps. * * @return The URL generator (possibly null). */ public XYURLGenerator getURLGenerator() { return this.urlGenerator; } /** * Sets the URL generator for HTML image maps. * * @param urlGenerator the URL generator (null permitted). */ public void setURLGenerator(XYURLGenerator urlGenerator) { //Object oldValue = this.urlGenerator; this.urlGenerator = urlGenerator; } /** * Draws a vertical line on the chart to represent a 'range marker'. * * @param g2 the graphics device. * @param plot the plot. * @param domainAxis the domain axis. * @param marker the marker line. * @param dataArea the axis data area. */ public void drawDomainMarker(Graphics2D g2, ContourPlot plot, ValueAxis domainAxis, Marker marker, Rectangle2D dataArea) { if (marker instanceof ValueMarker) { ValueMarker vm = (ValueMarker) marker; double value = vm.getValue(); Range range = domainAxis.getRange(); if (!range.contains(value)) { return; } double x = domainAxis.valueToJava2D(value, dataArea, RectangleEdge.BOTTOM); Line2D line = new Line2D.Double(x, dataArea.getMinY(), x, dataArea.getMaxY()); Paint paint = marker.getOutlinePaint(); Stroke stroke = marker.getOutlineStroke(); g2.setPaint(paint != null ? paint : Plot.DEFAULT_OUTLINE_PAINT); g2.setStroke(stroke != null ? stroke : Plot.DEFAULT_OUTLINE_STROKE); g2.draw(line); } } /** * Draws a horizontal line across the chart to represent a 'range marker'. * * @param g2 the graphics device. * @param plot the plot. * @param rangeAxis the range axis. * @param marker the marker line. * @param dataArea the axis data area. */ public void drawRangeMarker(Graphics2D g2, ContourPlot plot, ValueAxis rangeAxis, Marker marker, Rectangle2D dataArea) { if (marker instanceof ValueMarker) { ValueMarker vm = (ValueMarker) marker; double value = vm.getValue(); Range range = rangeAxis.getRange(); if (!range.contains(value)) { return; } double y = rangeAxis.valueToJava2D(value, dataArea, RectangleEdge.LEFT); Line2D line = new Line2D.Double(dataArea.getMinX(), y, dataArea.getMaxX(), y); Paint paint = marker.getOutlinePaint(); Stroke stroke = marker.getOutlineStroke(); g2.setPaint(paint != null ? paint : Plot.DEFAULT_OUTLINE_PAINT); g2.setStroke(stroke != null ? stroke : Plot.DEFAULT_OUTLINE_STROKE); g2.draw(line); } } /** * Returns the clipPath. * @return ClipPath */ public ClipPath getClipPath() { return this.clipPath; } /** * Sets the clipPath. * @param clipPath The clipPath to set */ public void setClipPath(ClipPath clipPath) { this.clipPath = clipPath; } /** * Returns the ptSizePct. * @return double */ public double getPtSizePct() { return this.ptSizePct; } /** * Returns the renderAsPoints. * @return boolean */ public boolean isRenderAsPoints() { return this.renderAsPoints; } /** * Sets the ptSizePct. * @param ptSizePct The ptSizePct to set */ public void setPtSizePct(double ptSizePct) { this.ptSizePct = ptSizePct; } /** * Sets the renderAsPoints. * @param renderAsPoints The renderAsPoints to set */ public void setRenderAsPoints(boolean renderAsPoints) { this.renderAsPoints = renderAsPoints; } /** * Receives notification of a change to one of the plot's axes. * * @param event information about the event. */ @Override public void axisChanged(AxisChangeEvent event) { Object source = event.getSource(); if (source.equals(this.rangeAxis) || source.equals(this.domainAxis)) { ColorBar cba = this.colorBar; if (this.colorBar.getAxis().isAutoRange()) { cba.getAxis().configure(); } } super.axisChanged(event); } /** * Returns the visible z-range. * * @param data the dataset. * @param x the x range. * @param y the y range. * * @return The range. */ public Range visibleRange(ContourDataset data, Range x, Range y) { Range range = data.getZValueRange(x, y); return range; } /** * Returns the missingPaint. * @return Paint */ public Paint getMissingPaint() { return this.missingPaint; } /** * Sets the missingPaint. * * @param paint the missingPaint to set. */ public void setMissingPaint(Paint paint) { this.missingPaint = paint; } /** * Multiplies the range on the domain axis/axes by the specified factor * (to be implemented). * * @param x the x-coordinate (in Java2D space). * @param y the y-coordinate (in Java2D space). * @param factor the zoom factor. */ public void zoomDomainAxes(double x, double y, double factor) { // TODO: to be implemented } /** * Zooms the domain axes (not yet implemented). * * @param x the x-coordinate (in Java2D space). * @param y the y-coordinate (in Java2D space). * @param lowerPercent the new lower bound. * @param upperPercent the new upper bound. */ public void zoomDomainAxes(double x, double y, double lowerPercent, double upperPercent) { // TODO: to be implemented } /** * Multiplies the range on the range axis/axes by the specified factor. * * @param x the x-coordinate (in Java2D space). * @param y the y-coordinate (in Java2D space). * @param factor the zoom factor. */ public void zoomRangeAxes(double x, double y, double factor) { // TODO: to be implemented } /** * Zooms the range axes (not yet implemented). * * @param x the x-coordinate (in Java2D space). * @param y the y-coordinate (in Java2D space). * @param lowerPercent the new lower bound. * @param upperPercent the new upper bound. */ public void zoomRangeAxes(double x, double y, double lowerPercent, double upperPercent) { // TODO: to be implemented } /** * Returns <code>false</code>. * * @return A boolean. */ public boolean isDomainZoomable() { return false; } /** * Returns <code>false</code>. * * @return A boolean. */ public boolean isRangeZoomable() { return false; } /** * Extends plot cloning to this plot type * @see org.jfree.chart.plot.Plot#clone() */ @Override public Object clone() throws CloneNotSupportedException { ContourPlot clone = (ContourPlot) super.clone(); if (this.domainAxis != null) { clone.domainAxis = (ValueAxis) this.domainAxis.clone(); clone.domainAxis.setPlot(clone); clone.domainAxis.addChangeListener(clone); } if (this.rangeAxis != null) { clone.rangeAxis = (ValueAxis) this.rangeAxis.clone(); clone.rangeAxis.setPlot(clone); clone.rangeAxis.addChangeListener(clone); } if (clone.dataset != null) { clone.dataset.addChangeListener(clone); } if (this.colorBar != null) { clone.colorBar = (ColorBar) this.colorBar.clone(); } clone.domainMarkers = (List) ObjectUtilities.deepClone( this.domainMarkers); clone.rangeMarkers = (List) ObjectUtilities.deepClone( this.rangeMarkers); clone.annotations = (List) ObjectUtilities.deepClone(this.annotations); if (this.clipPath != null) { clone.clipPath = (ClipPath) this.clipPath.clone(); } return clone; } }
lgpl-2.1
opax/exist
src/org/exist/xquery/BasicExpressionVisitor.java
7322
/* * eXist Open Source Native XML Database * Copyright (C) 2001-2015 The eXist Project * http://exist-db.org * * 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 * 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 library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package org.exist.xquery; import java.util.ArrayList; import java.util.List; /** * Basic implementation of the {@link ExpressionVisitor} interface. * This implementation will traverse a PathExpr object if it wraps * around a single other expression. All other methods are empty. * * @author wolf * */ public class BasicExpressionVisitor implements ExpressionVisitor { @Override public void visit(Expression expression) { processWrappers(expression); } @Override public void visitCastExpr(CastExpression expression) { //Nothing to do } /** * Default implementation will traverse a PathExpr * if it is just a wrapper around another single * expression object. */ @Override public void visitPathExpr(PathExpr expression) { if (expression.getLength() == 1) { final Expression next = expression.getExpression(0); next.accept(this); } } @Override public void visitFunctionCall(FunctionCall call) { // Nothing to do } @Override public void visitGeneralComparison(GeneralComparison comparison) { //Nothing to do } @Override public void visitUnionExpr(Union union) { //Nothing to do } @Override public void visitIntersectionExpr(Intersect intersect) { //Nothing to do } @Override public void visitAndExpr(OpAnd and) { //Nothing to do } @Override public void visitOrExpr(OpOr or) { //Nothing to do } @Override public void visitLocationStep(LocationStep locationStep) { //Nothing to do } @Override public void visitFilteredExpr(FilteredExpression filtered) { //Nothing to do } @Override public void visitPredicate(Predicate predicate) { //Nothing to do } @Override public void visitVariableReference(VariableReference ref) { //Nothing to do } @Override public void visitVariableDeclaration(VariableDeclaration decl) { // Nothing to do } protected void processWrappers(Expression expr) { if (expr instanceof Atomize || expr instanceof DynamicCardinalityCheck || expr instanceof DynamicNameCheck || expr instanceof DynamicTypeCheck || expr instanceof UntypedValueCheck) { expr.accept(this); } } public static LocationStep findFirstStep(Expression expr) { if (expr instanceof LocationStep) {return (LocationStep) expr;} final FirstStepVisitor visitor = new FirstStepVisitor(); expr.accept(visitor); return visitor.firstStep; } public static List<LocationStep> findLocationSteps(Expression expr) { final List<LocationStep> steps = new ArrayList<LocationStep>(5); if (expr instanceof LocationStep) { steps.add((LocationStep)expr); return steps; } expr.accept( new BasicExpressionVisitor() { @Override public void visitPathExpr(PathExpr expression) { for (int i = 0; i < expression.getLength(); i++) { final Expression next = expression.getExpression(i); next.accept(this); if (steps.size() - 1 != i) { steps.add(null); } } } @Override public void visitLocationStep(LocationStep locationStep) { steps.add(locationStep); } } ); return steps; } public static VariableReference findVariableRef(Expression expr) { final VariableRefVisitor visitor = new VariableRefVisitor(); expr.accept(visitor); return visitor.ref; } @Override public void visitForExpression(ForExpr forExpr) { //Nothing to do } @Override public void visitLetExpression(LetExpr letExpr) { //Nothing to do } @Override public void visitOrderByClause(OrderByClause orderBy) { // Nothing to do } @Override public void visitGroupByClause(GroupByClause groupBy) { // Nothing to do } @Override public void visitWhereClause(WhereClause where) { // Nothing to do } @Override public void visitBuiltinFunction(Function function) { //Nothing to do } @Override public void visitUserFunction(UserDefinedFunction function) { //Nothing to do } @Override public void visitConditional(ConditionalExpression conditional) { //Nothing to do } @Override public void visitTryCatch(TryCatchExpression conditional) { //Nothing to do } @Override public void visitDocumentConstructor(DocumentConstructor constructor) { // Nothing to do } public void visitElementConstructor(ElementConstructor constructor) { //Nothing to do } @Override public void visitTextConstructor(DynamicTextConstructor constructor) { //Nothing to do } @Override public void visitAttribConstructor(AttributeConstructor constructor) { //Nothing to do } @Override public void visitAttribConstructor(DynamicAttributeConstructor constructor) { //Nothing to do } @Override public void visitSimpleMapOperator(OpSimpleMap simpleMap) { // Nothing to do } public static class FirstStepVisitor extends BasicExpressionVisitor { private LocationStep firstStep = null; public LocationStep getFirstStep() { return firstStep; } @Override public void visitLocationStep(LocationStep locationStep) { firstStep = locationStep; } } public static class VariableRefVisitor extends BasicExpressionVisitor { private VariableReference ref = null; @Override public void visitVariableReference(VariableReference ref) { this.ref = ref; } @Override public void visitPathExpr(PathExpr expression) { for (int i = 0; i < expression.getLength(); i++) { final Expression next = expression.getExpression(i); next.accept(this); } } } }
lgpl-2.1
syntelos/cddb
src/org/jaudiotagger/tag/images/StandardImageHandler.java
4653
package org.jaudiotagger.tag.images; import org.jaudiotagger.tag.id3.valuepair.ImageFormats; import javax.imageio.ImageIO; import javax.imageio.ImageWriter; import javax.imageio.stream.ImageInputStream; import java.awt.*; import java.awt.geom.AffineTransform; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.Iterator; /** Image Handling used when running on standard JVM */ public class StandardImageHandler implements ImageHandler { private static StandardImageHandler instance; public static StandardImageHandler getInstanceOf() { if(instance==null) { instance = new StandardImageHandler(); } return instance; } private StandardImageHandler() { } /** * Resize the image until the total size require to store the image is less than maxsize * @param artwork * @param maxSize * @throws IOException */ public void reduceQuality(Artwork artwork, int maxSize) throws IOException { while(artwork.getBinaryData().length > maxSize) { Image srcImage = (Image)artwork.getImage(); int w = srcImage.getWidth(null); int newSize = w /2; makeSmaller(artwork,newSize); } } /** * Resize image using Java 2D * @param artwork * @param size * @throws java.io.IOException */ public void makeSmaller(Artwork artwork,int size) throws IOException { Image srcImage = (Image)artwork.getImage(); int w = srcImage.getWidth(null); int h = srcImage.getHeight(null); // Determine the scaling required to get desired result. float scaleW = (float) size / (float) w; float scaleH = (float) size / (float) h; //Create an image buffer in which to paint on, create as an opaque Rgb type image, it doesnt matter what type //the original image is we want to convert to the best type for displaying on screen regardless BufferedImage bi = new BufferedImage(size, size, BufferedImage.TYPE_INT_RGB); // Set the scale. AffineTransform tx = new AffineTransform(); tx.scale(scaleW, scaleH); // Paint image. Graphics2D g2d = bi.createGraphics(); g2d.drawImage(srcImage, tx, null); g2d.dispose(); if(artwork.getMimeType()!=null && isMimeTypeWritable(artwork.getMimeType())) { artwork.setBinaryData(writeImage(bi,artwork.getMimeType())); } else { artwork.setBinaryData(writeImageAsPng(bi)); } } public boolean isMimeTypeWritable(String mimeType) { Iterator<ImageWriter> writers = ImageIO.getImageWritersByMIMEType(mimeType); return writers.hasNext(); } /** * Write buffered image as required format * * @param bi * @param mimeType * @return * @throws IOException */ public byte[] writeImage(BufferedImage bi,String mimeType) throws IOException { Iterator<ImageWriter> writers = ImageIO.getImageWritersByMIMEType(mimeType); if(writers.hasNext()) { ImageWriter writer = writers.next(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); writer.setOutput(ImageIO.createImageOutputStream(baos)); writer.write(bi); return baos.toByteArray(); } throw new IOException("Cannot write to this mimetype"); } /** * * @param bi * @return * @throws IOException */ public byte[] writeImageAsPng(BufferedImage bi) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(bi, ImageFormats.MIME_TYPE_PNG,baos); return baos.toByteArray(); } /** * Show read formats * * On Windows supports png/jpeg/bmp/gif */ public void showReadFormats() { String[] formats = ImageIO.getReaderMIMETypes(); for(String f:formats) { System.out.println("r"+f); } } /** * Show write formats * * On Windows supports png/jpeg/bmp */ public void showWriteFormats() { String[] formats = ImageIO.getWriterMIMETypes(); for(String f:formats) { System.out.println(f); } } }
lgpl-3.0
shyamalschandra/flex-sdk
modules/thirdparty/batik/sources/org/apache/flex/forks/batik/dom/AbstractComment.java
1748
/* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.apache.flex.forks.batik.dom; import org.w3c.dom.Comment; /** * This class implements the {@link org.w3c.dom.Comment} interface. * * @author <a href="mailto:stephane@hillion.org">Stephane Hillion</a> * @version $Id: AbstractComment.java 475685 2006-11-16 11:16:05Z cam $ */ public abstract class AbstractComment extends AbstractCharacterData implements Comment { /** * <b>DOM</b>: Implements {@link org.w3c.dom.Node#getNodeName()}. * @return "#comment". */ public String getNodeName() { return "#comment"; } /** * <b>DOM</b>: Implements {@link org.w3c.dom.Node#getNodeType()}. * @return {@link org.w3c.dom.Node#COMMENT_NODE} */ public short getNodeType() { return COMMENT_NODE; } /** * <b>DOM</b>: Implements {@link org.w3c.dom.Node#getTextContent()}. */ public String getTextContent() { return getNodeValue(); } }
apache-2.0
goodwinnk/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/typeEnhancers/FromStringHintProcessor.java
3478
/* * Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. */ package org.jetbrains.plugins.groovy.lang.psi.typeEnhancers; import com.intellij.psi.*; import com.intellij.psi.impl.light.LightElement; import com.intellij.psi.scope.ElementClassHint; import com.intellij.psi.scope.PsiScopeProcessor; import com.intellij.util.IncorrectOperationException; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.plugins.groovy.GroovyLanguage; import org.jetbrains.plugins.groovy.lang.psi.GroovyFile; import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory; import org.jetbrains.plugins.groovy.lang.resolve.ResolveUtil; import java.util.List; public class FromStringHintProcessor extends SignatureHintProcessor { @Override public String getHintName() { return "groovy.transform.stc.FromString"; } @NotNull @Override public List<PsiType[]> inferExpectedSignatures(@NotNull final PsiMethod method, @NotNull final PsiSubstitutor substitutor, @NotNull String[] options) { PsiElement context = createContext(method); PsiElementFactory factory = JavaPsiFacade.getElementFactory(method.getProject()); return ContainerUtil.map(options, value -> { try { PsiType original = factory.createTypeFromText("SomeUnexpectedDummyClass<" + value + ">", context); if (original instanceof PsiClassType) { PsiType[] parameters = ((PsiClassType)original).getParameters(); return ContainerUtil.map(parameters, substitutor::substitute).toArray(new PsiType[parameters.length]) ; } } catch (IncorrectOperationException e) { //do nothing. Just don't throw an exception } return new PsiType[]{PsiType.NULL}; }); } @NotNull public static PsiElement createContext(@NotNull PsiMethod method) { return new FromStringLightElement(method); } } class FromStringLightElement extends LightElement { private final PsiMethod myMethod; private final GroovyFile myFile; FromStringLightElement(@NotNull PsiMethod method) { super(method.getManager(), GroovyLanguage.INSTANCE); myMethod = method; myFile = GroovyPsiElementFactory.getInstance(getProject()).createGroovyFile("", false, null); } @Override public boolean processDeclarations(@NotNull PsiScopeProcessor processor, @NotNull ResolveState state, PsiElement lastParent, @NotNull PsiElement place) { if (!ResolveUtil.shouldProcessClasses(processor.getHint(ElementClassHint.KEY))) return true; for (PsiTypeParameter parameter : myMethod.getTypeParameters()) { if (!ResolveUtil.processElement(processor, parameter, state)) return false; } PsiClass containingClass = myMethod.getContainingClass(); if (containingClass != null) { PsiTypeParameter[] parameters = containingClass.getTypeParameters(); for (PsiTypeParameter parameter : parameters) { if (!ResolveUtil.processElement(processor, parameter, state)) return false; } } return myFile.processDeclarations(processor, state, lastParent, place); } @Override public String toString() { return "fromStringLightElement"; } }
apache-2.0
thomasdarimont/spring-security
samples/javaconfig/aspectj/src/test/java/sample/aspectj/AspectJInterceptorTests.java
3577
/* * Copyright 2002-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 sample.aspectj; import org.junit.After; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.lang.reflect.Proxy; import static org.assertj.core.api.Assertions.assertThat; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = AspectjSecurityConfig.class) public class AspectJInterceptorTests { private Authentication admin = new UsernamePasswordAuthenticationToken("test", "xxx", AuthorityUtils.createAuthorityList("ROLE_ADMIN")); private Authentication user = new UsernamePasswordAuthenticationToken("test", "xxx", AuthorityUtils.createAuthorityList("ROLE_USER")); @Autowired private Service service; @Autowired private SecuredService securedService; @Test public void publicMethod() throws Exception { service.publicMethod(); } @Test(expected = AuthenticationCredentialsNotFoundException.class) public void securedMethodNotAuthenticated() throws Exception { service.secureMethod(); } @Test(expected = AccessDeniedException.class) public void securedMethodWrongRole() throws Exception { SecurityContextHolder.getContext().setAuthentication(admin); service.secureMethod(); } @Test public void securedMethodEverythingOk() throws Exception { SecurityContextHolder.getContext().setAuthentication(user); service.secureMethod(); } @Test(expected = AuthenticationCredentialsNotFoundException.class) public void securedClassNotAuthenticated() throws Exception { securedService.secureMethod(); } @Test(expected = AccessDeniedException.class) public void securedClassWrongRole() throws Exception { SecurityContextHolder.getContext().setAuthentication(admin); securedService.secureMethod(); } @Test(expected = AccessDeniedException.class) public void securedClassWrongRoleOnNewedInstance() throws Exception { SecurityContextHolder.getContext().setAuthentication(admin); new SecuredService().secureMethod(); } @Test public void securedClassEverythingOk() throws Exception { SecurityContextHolder.getContext().setAuthentication(user); securedService.secureMethod(); new SecuredService().secureMethod(); } // SEC-2595 @Test public void notProxy() { assertThat(Proxy.isProxyClass(securedService.getClass())).isFalse(); } @After public void tearDown() { SecurityContextHolder.clearContext(); } }
apache-2.0
ricepanda/rice-git3
rice-middleware/impl/src/main/java/org/kuali/rice/kew/doctype/DocumentTypeSecurity.java
15608
/** * Copyright 2005-2014 The Kuali Foundation * * Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php * * 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.kuali.rice.kew.doctype; import org.apache.commons.lang.StringUtils; import org.kuali.rice.core.api.impex.xml.XmlConstants; import org.kuali.rice.core.api.util.ConcreteKeyValue; import org.kuali.rice.core.api.util.KeyValue; import org.kuali.rice.kew.api.WorkflowRuntimeException; import org.kuali.rice.kew.api.exception.WorkflowException; import org.kuali.rice.kew.rule.xmlrouting.XPathHelper; import org.kuali.rice.kew.util.Utilities; import org.kuali.rice.kim.api.group.Group; import org.kuali.rice.kim.api.services.KimApiServiceLocator; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import java.io.BufferedReader; import java.io.IOException; import java.io.Serializable; import java.io.StringReader; import java.util.ArrayList; import java.util.List; public class DocumentTypeSecurity implements Serializable { private static final long serialVersionUID = -1886779857180381404L; private static final org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(DocumentTypeSecurity.class); private Boolean active; private Boolean initiatorOk; private Boolean routeLogAuthenticatedOk; private List<KeyValue> searchableAttributes = new ArrayList<KeyValue>(); private List<Group> workgroups = new ArrayList<Group>(); private List<SecurityPermissionInfo> permissions = new ArrayList<SecurityPermissionInfo>(); private List<String> allowedRoles = new ArrayList<String>(); private List<String> disallowedRoles = new ArrayList<String>(); private List<String> securityAttributeExtensionNames = new ArrayList<String>(); private List<String> securityAttributeClassNames = new ArrayList<String>(); private static XPath xpath = XPathHelper.newXPath(); public DocumentTypeSecurity() {} /** parse <security> XML to populate security object * @throws ParserConfigurationException * @throws IOException * @throws SAXException */ public DocumentTypeSecurity(String standardApplicationId, String documentTypeSecurityXml) { try { if (org.apache.commons.lang.StringUtils.isEmpty(documentTypeSecurityXml)) { return; } InputSource inputSource = new InputSource(new BufferedReader(new StringReader(documentTypeSecurityXml))); Element securityElement = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(inputSource).getDocumentElement(); String active = (String) xpath.evaluate("./@active", securityElement, XPathConstants.STRING); if (org.apache.commons.lang.StringUtils.isEmpty(active) || "true".equals(active.toLowerCase())) { // true is the default this.setActive(Boolean.valueOf(true)); } else { this.setActive(Boolean.valueOf(false)); } // there should only be one <initiator> tag NodeList initiatorNodes = (NodeList) xpath.evaluate("./initiator", securityElement, XPathConstants.NODESET); if (initiatorNodes != null && initiatorNodes.getLength()>0) { Node initiatorNode = initiatorNodes.item(0); String value = initiatorNode.getTextContent(); if (org.apache.commons.lang.StringUtils.isEmpty(value) || value.toLowerCase().equals("true")) { this.setInitiatorOk(Boolean.valueOf(true)); } else { this.initiatorOk = Boolean.valueOf(false); } } // there should only be one <routeLogAuthenticated> tag NodeList routeLogAuthNodes = (NodeList) xpath.evaluate("./routeLogAuthenticated", securityElement, XPathConstants.NODESET); if (routeLogAuthNodes != null && routeLogAuthNodes.getLength()>0) { Node routeLogAuthNode = routeLogAuthNodes.item(0); String value = routeLogAuthNode.getTextContent(); if (org.apache.commons.lang.StringUtils.isEmpty(value) || value.toLowerCase().equals("true")) { this.routeLogAuthenticatedOk = Boolean.valueOf(true); } else { this.routeLogAuthenticatedOk = Boolean.valueOf(false); } } NodeList searchableAttributeNodes = (NodeList) xpath.evaluate("./searchableAttribute", securityElement, XPathConstants.NODESET); if (searchableAttributeNodes != null && searchableAttributeNodes.getLength()>0) { for (int i = 0; i < searchableAttributeNodes.getLength(); i++) { Node searchableAttributeNode = searchableAttributeNodes.item(i); String name = (String) xpath.evaluate("./@name", searchableAttributeNode, XPathConstants.STRING); String idType = (String) xpath.evaluate("./@idType", searchableAttributeNode, XPathConstants.STRING); if (!org.apache.commons.lang.StringUtils.isEmpty(name) && !org.apache.commons.lang.StringUtils.isEmpty(idType)) { KeyValue searchableAttribute = new ConcreteKeyValue(name, idType); searchableAttributes.add(searchableAttribute); } } } NodeList workgroupNodes = (NodeList) xpath.evaluate("./workgroup", securityElement, XPathConstants.NODESET); if (workgroupNodes != null && workgroupNodes.getLength()>0) { LOG.warn("Document Type Security XML is using deprecated element 'workgroup', please use 'groupName' instead."); for (int i = 0; i < workgroupNodes.getLength(); i++) { Node workgroupNode = workgroupNodes.item(i); String value = workgroupNode.getTextContent().trim(); if (!org.apache.commons.lang.StringUtils.isEmpty(value)) { value = Utilities.substituteConfigParameters(value); String namespaceCode = Utilities.parseGroupNamespaceCode(value); String groupName = Utilities.parseGroupName(value); Group groupObject = KimApiServiceLocator.getGroupService().getGroupByNamespaceCodeAndName(namespaceCode, groupName); if (groupObject == null) { throw new WorkflowException("Could not find group: " + value); } workgroups.add(groupObject); } } } NodeList groupNodes = (NodeList) xpath.evaluate("./groupName", securityElement, XPathConstants.NODESET); if (groupNodes != null && groupNodes.getLength()>0) { for (int i = 0; i < groupNodes.getLength(); i++) { Node groupNode = groupNodes.item(i); if (groupNode.getNodeType() == Node.ELEMENT_NODE) { String groupName = groupNode.getTextContent().trim(); if (!org.apache.commons.lang.StringUtils.isEmpty(groupName)) { groupName = Utilities.substituteConfigParameters(groupName).trim(); String namespaceCode = Utilities.substituteConfigParameters(((Element) groupNode).getAttribute(XmlConstants.NAMESPACE)).trim(); Group groupObject = KimApiServiceLocator.getGroupService().getGroupByNamespaceCodeAndName(namespaceCode, groupName); if (groupObject != null) { workgroups.add(groupObject); } else { LOG.warn("Could not find group with name '" + groupName + "' and namespace '" + namespaceCode + "' which was defined on Document Type security"); } // if (groupObject == null) { // throw new WorkflowException("Could not find group with name '" + groupName + "' and namespace '" + namespaceCode + "'"); // } } } } } NodeList permissionNodes = (NodeList) xpath.evaluate("./permission", securityElement, XPathConstants.NODESET); if (permissionNodes != null && permissionNodes.getLength()>0) { for (int i = 0; i < permissionNodes.getLength(); i++) { Node permissionNode = permissionNodes.item(i); if (permissionNode.getNodeType() == Node.ELEMENT_NODE) { SecurityPermissionInfo securityPermission = new SecurityPermissionInfo(); securityPermission.setPermissionName(Utilities.substituteConfigParameters(((Element) permissionNode).getAttribute(XmlConstants.NAME)).trim()); securityPermission.setPermissionNamespaceCode(Utilities.substituteConfigParameters(((Element) permissionNode).getAttribute(XmlConstants.NAMESPACE)).trim()); if (!StringUtils.isEmpty(securityPermission.getPermissionName()) && !StringUtils.isEmpty(securityPermission.getPermissionNamespaceCode())) { //get details and qualifications if (permissionNode.hasChildNodes()) { NodeList permissionChildNodes = permissionNode.getChildNodes(); for (int j = 0; j <permissionChildNodes.getLength(); j++) { Node permissionChildNode = permissionChildNodes.item(j); if (permissionChildNode.getNodeType() == Node.ELEMENT_NODE) { String childAttributeName = Utilities.substituteConfigParameters(((Element) permissionChildNode).getAttribute(XmlConstants.NAME)).trim(); String childAttributeValue = permissionChildNode.getTextContent().trim(); if (!StringUtils.isEmpty(childAttributeValue)) { childAttributeValue = Utilities.substituteConfigParameters(childAttributeValue).trim(); } if (!StringUtils.isEmpty(childAttributeValue)) { childAttributeValue = Utilities.substituteConfigParameters(childAttributeValue).trim(); } if (permissionChildNode.getNodeName().trim().equals("permissionDetail")) { securityPermission.getPermissionDetails().put(childAttributeName, childAttributeValue); } if (permissionChildNode.getNodeName().trim().equals("qualification")) { securityPermission.getQualifications().put(childAttributeName, childAttributeValue); } } } } //if ( KimApiServiceLocator.getPermissionService().isPermissionDefined(securityPermission.getPermissionNamespaceCode(), securityPermission.getPermissionName(), securityPermission.getPermissionDetails())) { permissions.add(securityPermission); //} else { // LOG.warn("Could not find permission with name '" + securityPermission.getPermissionName() + "' and namespace '" + securityPermission.getPermissionNamespaceCode() + "' which was defined on Document Type security"); //} } } } } NodeList roleNodes = (NodeList) xpath.evaluate("./role", securityElement, XPathConstants.NODESET); if (roleNodes != null && roleNodes.getLength()>0) { for (int i = 0; i < roleNodes.getLength(); i++) { Element roleElement = (Element)roleNodes.item(i); String value = roleElement.getTextContent().trim(); String allowedValue = roleElement.getAttribute("allowed"); if (StringUtils.isBlank(allowedValue)) { allowedValue = "true"; } if (!org.apache.commons.lang.StringUtils.isEmpty(value)) { if (Boolean.parseBoolean(allowedValue)) { allowedRoles.add(value); } else { disallowedRoles.add(value); } } } } NodeList attributeNodes = (NodeList) xpath.evaluate("./securityAttribute", securityElement, XPathConstants.NODESET); if (attributeNodes != null && attributeNodes.getLength()>0) { for (int i = 0; i < attributeNodes.getLength(); i++) { Element attributeElement = (Element)attributeNodes.item(i); NamedNodeMap elemAttributes = attributeElement.getAttributes(); // can be an attribute name or an actual classname String attributeOrClassName = null; String applicationId = standardApplicationId; if (elemAttributes.getNamedItem("name") != null) { // found a name attribute so find the class name String extensionName = elemAttributes.getNamedItem("name").getNodeValue().trim(); this.securityAttributeExtensionNames.add(extensionName); } else if (elemAttributes.getNamedItem("class") != null) { // class name defined String className = elemAttributes.getNamedItem("class").getNodeValue().trim(); this.securityAttributeClassNames.add(className); } else { throw new WorkflowException("Cannot find attribute 'name' or attribute 'class' for securityAttribute Node"); } } } } catch (Exception err) { throw new WorkflowRuntimeException(err); } } public List<String> getSecurityAttributeExtensionNames() { return this.securityAttributeExtensionNames; } public void setSecurityAttributeExtensionNames(List<String> securityAttributeExtensionNames) { this.securityAttributeExtensionNames = securityAttributeExtensionNames; } public List<String> getSecurityAttributeClassNames() { return securityAttributeClassNames; } public void setSecurityAttributeClassNames(List<String> securityAttributeClassNames) { this.securityAttributeClassNames = securityAttributeClassNames; } public Boolean getInitiatorOk() { return initiatorOk; } public void setInitiatorOk(Boolean initiatorOk) { this.initiatorOk = initiatorOk; } public Boolean getRouteLogAuthenticatedOk() { return routeLogAuthenticatedOk; } public void setRouteLogAuthenticatedOk(Boolean routeLogAuthenticatedOk) { this.routeLogAuthenticatedOk = routeLogAuthenticatedOk; } public List<String> getAllowedRoles() { return allowedRoles; } public void setAllowedRoles(List<String> allowedRoles) { this.allowedRoles = allowedRoles; } public List<String> getDisallowedRoles() { return disallowedRoles; } public void setDisallowedRoles(List<String> disallowedRoles) { this.disallowedRoles = disallowedRoles; } public List<KeyValue> getSearchableAttributes() { return searchableAttributes; } public void setSearchableAttributes(List<KeyValue> searchableAttributes) { this.searchableAttributes = searchableAttributes; } public List<Group> getWorkgroups() { return workgroups; } public void setWorkgroups(List<Group> workgroups) { this.workgroups = workgroups; } public List<SecurityPermissionInfo> getPermissions() { return this.permissions; } public void setPermissions(List<SecurityPermissionInfo> permissions) { this.permissions = permissions; } public Boolean getActive() { return active; } public void setActive(Boolean active) { this.active = active; } public boolean isActive() { if (active != null) { return active.booleanValue(); } else { return false; } } }
apache-2.0
goodwinnk/intellij-community
platform/platform-impl/src/com/intellij/openapi/editor/impl/view/ApproximationFragment.java
2054
// Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.editor.impl.view; import org.jetbrains.annotations.NotNull; import java.awt.*; /** * Used for quick estimation of editor's viewable area size (without full text layout) */ class ApproximationFragment implements LineFragment { private final int myLength; private final int myColumnCount; private final float myWidth; ApproximationFragment(int length, int columnCount, float charWidth) { myLength = length; myColumnCount = columnCount; myWidth = charWidth * columnCount; } @Override public int getLength() { return myLength; } @Override public int getLogicalColumnCount(int startColumn) { return myColumnCount; } @Override public int getVisualColumnCount(float startX) { return myColumnCount; } @Override public int logicalToVisualColumn(float startX, int startColumn, int column) { return column; } @Override public int visualToLogicalColumn(float startX, int startColumn, int column) { return column; } @Override public int visualColumnToOffset(float startX, int column) { return column; } @Override public float visualColumnToX(float startX, int column) { return column < myColumnCount ? 0 : myWidth; } @Override public int[] xToVisualColumn(float startX, float x) { float relX = x - startX; int column = relX < myWidth / 2 ? 0 : myColumnCount; return new int[] {column, relX <= visualColumnToX(startX, column) ? 0 : 1}; } @Override public float offsetToX(float startX, int startOffset, int offset) { return startX + (offset < myLength ? 0 : myWidth); } @Override public void draw(Graphics2D g, float x, float y, int startColumn, int endColumn) { throw new UnsupportedOperationException(); } @NotNull @Override public LineFragment subFragment(int startOffset, int endOffset) { throw new UnsupportedOperationException(); } }
apache-2.0
robin13/elasticsearch
x-pack/plugin/security/src/internalClusterTest/java/org/elasticsearch/xpack/security/user/AnonymousUserIntegTests.java
2865
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ package org.elasticsearch.xpack.security.user; import org.apache.http.util.EntityUtils; import org.elasticsearch.client.Request; import org.elasticsearch.client.Response; import org.elasticsearch.client.ResponseException; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.test.SecurityIntegTestCase; import org.elasticsearch.xpack.core.security.user.AnonymousUser; import org.elasticsearch.xpack.security.authz.AuthorizationService; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.nullValue; public class AnonymousUserIntegTests extends SecurityIntegTestCase { private boolean authorizationExceptionsEnabled = randomBoolean(); @Override protected boolean addMockHttpTransport() { return false; // enable http } @Override public Settings nodeSettings(int nodeOrdinal, Settings otherSettings) { return Settings.builder() .put(super.nodeSettings(nodeOrdinal, otherSettings)) .put(AnonymousUser.ROLES_SETTING.getKey(), "anonymous") .put(AuthorizationService.ANONYMOUS_AUTHORIZATION_EXCEPTION_SETTING.getKey(), authorizationExceptionsEnabled) .build(); } @Override public String configRoles() { return super.configRoles() + "\n" + "anonymous:\n" + " indices:\n" + " - names: '*'\n" + " privileges: [ READ ]\n"; } public void testAnonymousViaHttp() throws Exception { try { getRestClient().performRequest(new Request("GET", "/_nodes")); fail("request should have failed"); } catch(ResponseException e) { int statusCode = e.getResponse().getStatusLine().getStatusCode(); Response response = e.getResponse(); if (authorizationExceptionsEnabled) { assertThat(statusCode, is(403)); assertThat(response.getHeader("WWW-Authenticate"), nullValue()); assertThat(EntityUtils.toString(response.getEntity()), containsString("security_exception")); } else { assertThat(statusCode, is(401)); assertThat(response.getHeader("WWW-Authenticate"), notNullValue()); assertThat(response.getHeader("WWW-Authenticate"), containsString("Basic")); assertThat(EntityUtils.toString(response.getEntity()), containsString("security_exception")); } } } }
apache-2.0
lsinfo3/onos
core/api/src/main/java/org/onosproject/net/group/GroupProviderService.java
1548
/* * Copyright 2015-present Open Networking Laboratory * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onosproject.net.group; import java.util.Collection; import org.onosproject.net.DeviceId; import org.onosproject.net.provider.ProviderService; /** * Service through which Group providers can inject information into * the core. */ public interface GroupProviderService extends ProviderService<GroupProvider> { /** * Notifies core if any failure from data plane during group operations. * * @param deviceId the device ID * @param operation offended group operation */ void groupOperationFailed(DeviceId deviceId, GroupOperation operation); /** * Pushes the collection of group detected in the data plane along * with statistics. * * @param deviceId device identifier * @param groupEntries collection of group entries as seen in data plane */ void pushGroupMetrics(DeviceId deviceId, Collection<Group> groupEntries); }
apache-2.0
vineetgarg02/hive
ql/src/java/org/apache/hadoop/hive/ql/exec/persistence/MapJoinKeyObject.java
5411
/* * 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.hive.ql.exec.persistence; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Arrays; import java.util.List; import org.apache.hadoop.hive.ql.exec.ExprNodeEvaluator; import org.apache.hadoop.hive.ql.exec.vector.expressions.VectorExpression; import org.apache.hadoop.hive.ql.exec.vector.expressions.VectorExpressionWriter; import org.apache.hadoop.hive.ql.exec.vector.wrapper.VectorHashKeyWrapperBase; import org.apache.hadoop.hive.ql.exec.vector.wrapper.VectorHashKeyWrapperBatch; import org.apache.hadoop.hive.ql.metadata.HiveException; import org.apache.hadoop.hive.serde2.AbstractSerDe; import org.apache.hadoop.hive.serde2.SerDeException; import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorUtils; import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorUtils.ObjectInspectorCopyOption; import org.apache.hadoop.io.Writable; @SuppressWarnings("deprecation") public class MapJoinKeyObject extends MapJoinKey { private static final Object[] EMPTY_OBJECT_ARRAY = new Object[0]; private Object[] key; public MapJoinKeyObject(Object[] key) { this.key = key; } public MapJoinKeyObject() { this(EMPTY_OBJECT_ARRAY); } public Object[] getKeyObjects() { return key; } public void setKeyObjects(Object[] key) { this.key = key; } public int getKeyLength() { return key.length; } @Override public boolean hasAnyNulls(int fieldCount, boolean[] nullsafes) { assert fieldCount == key.length; if (key != null && key.length > 0) { for (int i = 0; i < key.length; i++) { if (key[i] == null && (nullsafes == null || !nullsafes[i])) { return true; } } } return false; } @Override public int hashCode() { return ObjectInspectorUtils.writableArrayHashCode(key); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; MapJoinKeyObject other = (MapJoinKeyObject) obj; if (!Arrays.equals(key, other.key)) return false; return true; } public void read(MapJoinObjectSerDeContext context, ObjectInputStream in, Writable container) throws IOException, SerDeException { container.readFields(in); read(context, container); } public void read(MapJoinObjectSerDeContext context, Writable container) throws SerDeException { read(context.getSerDe().getObjectInspector(), context.getSerDe().deserialize(container)); } protected void read(ObjectInspector oi, Object obj) throws SerDeException { @SuppressWarnings("unchecked") List<Object> value = (List<Object>)ObjectInspectorUtils.copyToStandardObject( obj, oi, ObjectInspectorCopyOption.WRITABLE); if (value == null) { key = EMPTY_OBJECT_ARRAY; } else { key = value.toArray(); } } @Override public void write(MapJoinObjectSerDeContext context, ObjectOutputStream out) throws IOException, SerDeException { AbstractSerDe serde = context.getSerDe(); ObjectInspector objectInspector = context.getStandardOI(); Writable container = serde.serialize(key, objectInspector); container.write(out); } public void readFromRow(Object[] fieldObjs, List<ObjectInspector> keyFieldsOI) throws HiveException { if (key == null || key.length != fieldObjs.length) { key = new Object[fieldObjs.length]; } for (int keyIndex = 0; keyIndex < fieldObjs.length; ++keyIndex) { key[keyIndex] = (ObjectInspectorUtils.copyToStandardObject(fieldObjs[keyIndex], keyFieldsOI.get(keyIndex), ObjectInspectorCopyOption.WRITABLE)); } } protected boolean[] getNulls() { boolean[] nulls = null; for (int i = 0; i < key.length; ++i) { if (key[i] == null) { if (nulls == null) { nulls = new boolean[key.length]; } nulls[i] = true; } } return nulls; } public void readFromVector(VectorHashKeyWrapperBase kw, VectorExpressionWriter[] keyOutputWriters, VectorHashKeyWrapperBatch keyWrapperBatch) throws HiveException { if (key == null || key.length != keyOutputWriters.length) { key = new Object[keyOutputWriters.length]; } for (int keyIndex = 0; keyIndex < keyOutputWriters.length; ++keyIndex) { key[keyIndex] = keyWrapperBatch.getWritableKeyValue( kw, keyIndex, keyOutputWriters[keyIndex]); } } }
apache-2.0
codeaudit/mapdb
src/test/java/org/mapdb/Issue198Test.java
460
package org.mapdb; import org.junit.Test; public class Issue198Test { @Test public void main() { DB db = DBMaker.fileDB(TT.tempDbFile()) .closeOnJvmShutdown() //.randomAccessFileEnable() .make(); BTreeMap<Integer, Integer> map = db.treeMapCreate("testmap").makeOrGet(); for(int i = 1; i <= 3000; ++i) map.put(i, i); db.commit(); db.close(); } }
apache-2.0
mztaylor/rice-git
rice-middleware/impl/src/main/java/org/kuali/rice/kew/impl/Responsibility/ResponsibilityChangeQueueImpl.java
1419
/** * Copyright 2005-2014 The Kuali Foundation * * Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php * * 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.kuali.rice.kew.impl.Responsibility; import org.apache.commons.collections.CollectionUtils; import org.kuali.rice.kew.api.responsibility.ResponsibilityChangeQueue; import org.kuali.rice.kew.service.KEWServiceLocator; import java.util.Set; /** * Reference implementation of the {@code ResponsibilityChangeQueue}. * * @author Kuali Rice Team (rice.collab@kuali.org) */ public class ResponsibilityChangeQueueImpl implements ResponsibilityChangeQueue { @Override public void responsibilitiesChanged(Set<String> responsibilityIds) { if (CollectionUtils.isNotEmpty(responsibilityIds)) { KEWServiceLocator.getActionRequestService().updateActionRequestsForResponsibilityChange(responsibilityIds); } } }
apache-2.0
gouessej/nifty-gui
nifty-core/src/main/java/de/lessvoid/nifty/Clipboard.java
435
package de.lessvoid.nifty; import javax.annotation.Nullable; /** * Clipboard interface. * @author void */ public interface Clipboard { /** * Put data into clipboard. * @param data the data for the clipboard or {@link null} to clear the clipboard */ void put(@Nullable String data); /** * Get data back from clipboard. * @return data from clipboard */ @Nullable String get(); }
bsd-2-clause
wangscript/libjingle-1
trunk/talk/examples/android/src/org/appspot/apprtc/GAEChannelClient.java
5796
/* * libjingle * Copyright 2013, Google Inc. * * 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. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 org.appspot.apprtc; import android.annotation.SuppressLint; import android.app.Activity; import android.util.Log; import android.webkit.ConsoleMessage; import android.webkit.JavascriptInterface; import android.webkit.WebChromeClient; import android.webkit.WebView; import android.webkit.WebViewClient; /** * Java-land version of Google AppEngine's JavaScript Channel API: * https://developers.google.com/appengine/docs/python/channel/javascript * * Requires a hosted HTML page that opens the desired channel and dispatches JS * on{Open,Message,Close,Error}() events to a global object named * "androidMessageHandler". */ public class GAEChannelClient { private static final String TAG = "GAEChannelClient"; private WebView webView; private final ProxyingMessageHandler proxyingMessageHandler; /** * Callback interface for messages delivered on the Google AppEngine channel. * * Methods are guaranteed to be invoked on the UI thread of |activity| passed * to GAEChannelClient's constructor. */ public interface MessageHandler { public void onOpen(); public void onMessage(String data); public void onClose(); public void onError(int code, String description); } /** Asynchronously open an AppEngine channel. */ @SuppressLint("SetJavaScriptEnabled") public GAEChannelClient( Activity activity, String token, MessageHandler handler) { webView = new WebView(activity); webView.getSettings().setJavaScriptEnabled(true); webView.setWebChromeClient(new WebChromeClient() { // Purely for debugging. public boolean onConsoleMessage (ConsoleMessage msg) { Log.d(TAG, "console: " + msg.message() + " at " + msg.sourceId() + ":" + msg.lineNumber()); return false; } }); webView.setWebViewClient(new WebViewClient() { // Purely for debugging. public void onReceivedError( WebView view, int errorCode, String description, String failingUrl) { Log.e(TAG, "JS error: " + errorCode + " in " + failingUrl + ", desc: " + description); } }); proxyingMessageHandler = new ProxyingMessageHandler(activity, handler); webView.addJavascriptInterface( proxyingMessageHandler, "androidMessageHandler"); webView.loadUrl("file:///android_asset/channel.html?token=" + token); } /** Close the connection to the AppEngine channel. */ public void close() { if (webView == null) { return; } proxyingMessageHandler.disconnect(); webView.removeJavascriptInterface("androidMessageHandler"); webView.loadUrl("about:blank"); webView = null; } // Helper class for proxying callbacks from the Java<->JS interaction // (private, background) thread to the Activity's UI thread. private static class ProxyingMessageHandler { private final Activity activity; private final MessageHandler handler; private final boolean[] disconnected = { false }; public ProxyingMessageHandler(Activity activity, MessageHandler handler) { this.activity = activity; this.handler = handler; } public void disconnect() { disconnected[0] = true; } private boolean disconnected() { return disconnected[0]; } @JavascriptInterface public void onOpen() { activity.runOnUiThread(new Runnable() { public void run() { if (!disconnected()) { handler.onOpen(); } } }); } @JavascriptInterface public void onMessage(final String data) { activity.runOnUiThread(new Runnable() { public void run() { if (!disconnected()) { handler.onMessage(data); } } }); } @JavascriptInterface public void onClose() { activity.runOnUiThread(new Runnable() { public void run() { if (!disconnected()) { handler.onClose(); } } }); } @JavascriptInterface public void onError( final int code, final String description) { activity.runOnUiThread(new Runnable() { public void run() { if (!disconnected()) { handler.onError(code, description); } } }); } } }
bsd-3-clause
rnathanday/dryad-repo
dspace-api/src/main/java/org/dspace/authority/indexer/AuthorityConsumer.java
2863
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.authority.indexer; import org.apache.log4j.Logger; import org.dspace.content.DSpaceObject; import org.dspace.content.Item; import org.dspace.core.Context; import org.dspace.event.Consumer; import org.dspace.event.Event; import java.util.HashSet; import java.util.Set; /** * Consumer that takes care of the indexing of authority controlled metadata fields for installed/updated items * * @author Antoine Snyers (antoine at atmire.com) * @author Kevin Van de Velde (kevin at atmire dot com) * @author Ben Bosman (ben at atmire dot com) * @author Mark Diggory (markd at atmire dot com) */ public class AuthorityConsumer implements Consumer { private static final Logger log = Logger.getLogger(AuthorityConsumer.class); /** A set of all item IDs installed which need their authority updated **/ private Set<Integer> itemsToUpdateAuthority = null; /** A set of item IDs who's metadata needs to be reindexed **/ private Set<Integer> itemsToReindex = null; public void initialize() throws Exception { } public void consume(Context ctx, Event event) throws Exception { if(itemsToUpdateAuthority == null){ itemsToUpdateAuthority = new HashSet<Integer>(); itemsToReindex = new HashSet<Integer>(); } DSpaceObject dso = event.getSubject(ctx); if(dso instanceof Item){ Item item = (Item) dso; if(item.isArchived()){ if(!itemsToReindex.contains(item.getID())) itemsToReindex.add(item.getID()); } if(("ARCHIVED: " + true).equals(event.getDetail())){ itemsToUpdateAuthority.add(item.getID()); } } } public void end(Context ctx) throws Exception { if(itemsToUpdateAuthority == null) return; try{ ctx.turnOffAuthorisationSystem(); for (Integer id : itemsToUpdateAuthority) { Item item = Item.find(ctx, id); AuthorityIndexClient.indexItem(ctx, item); } //Loop over our items which need to be re indexed for (Integer id : itemsToReindex) { Item item = Item.find(ctx, id); AuthorityIndexClient.indexItem(ctx, item); } } catch (Exception e){ log.error("Error while consuming the authority consumer", e); } finally { itemsToUpdateAuthority = null; itemsToReindex = null; ctx.restoreAuthSystemState(); } } public void finish(Context ctx) throws Exception { } }
bsd-3-clause
arturog8m/ocs
bundle/edu.gemini.wdba.xmlrpc.api/src/main/java/edu/gemini/wdba/xmlrpc/IExecXmlRpc.java
603
// // $Id: IExecXmlRpc.java 756 2007-01-08 18:01:24Z gillies $ // package edu.gemini.wdba.xmlrpc; /** * The SeqExec can fetch the sequence file for an observation form the ODB. * The format of the response is an Sequence XML file specified KGillies and DTerret. */ public interface IExecXmlRpc { String NAME = "WDBA_Exec"; /** * Returns the sequence data for a specific observation. * * @param observationId is the observation to use * @return the XML result for the observation sequence. */ public String getSequence(String observationId) throws ServiceException; }
bsd-3-clause
arturog8m/ocs
bundle/jsky.app.ot/src/main/java/jsky/science/Wavelength1DFormula.java
9770
//=== File Prolog=========================================================== // This code was developed by NASA, Goddard Space Flight Center, Code 588 // for the Scientist's Expert Assistant (SEA) project for Next Generation // Space Telescope (NGST). // //--- Notes----------------------------------------------------------------- // //--- Development History--------------------------------------------------- // Date Author Reference // 06/30/2000 S.Grosvenor // Initial packaging of class // //--- DISCLAIMER--------------------------------------------------------------- // // This software is provided "as is" without any warranty of any kind, either // express, implied, or statutory, including, but not limited to, any // warranty that the software will conform to specification, any implied // warranties of merchantability, fitness for a particular purpose, and // freedom from infringement, and any warranty that the documentation will // conform to the program, or any warranty that the software will be error // free. // // In no event shall NASA be liable for any damages, including, but not // limited to direct, indirect, special or consequential damages, arising out // of, resulting from, or in any way connected with this software, whether or // not based upon warranty, contract, tort or otherwise, whether or not // injury was sustained by persons or property or otherwise, and whether or // not loss was sustained from or arose out of the results of, or use of, // their software or services provided hereunder. //=== End File Prolog======================================================= package jsky.science; import jsky.science.Wavelength; import jsky.science.Quantity; import java.beans.PropertyChangeEvent; import java.beans.PropertyVetoException; import java.util.Vector; import java.io.Reader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.StreamTokenizer; import java.io.IOException; import nom.tam.fits.*; /** * Implements a Wavelength1Dmodel as a formula value=f(wavelength) * with a minimum and maximum wavelength, and a number of expected points. * * <P>This code was developed by NASA, Goddard Space Flight Center, Code 588 * for the Scientist's Expert Assistant (SEA) project for Next Generation * Space Telescope (NGST). * * @version 06.30.00 * @author Sandy Grosvenor * **/ public abstract class Wavelength1DFormula extends AbstractWavelength1D { protected Wavelength fMinWavelength; protected Wavelength fMaxWavelength; protected int fNumPoints; /** * The Stream Unique Identifier for this class. **/ private static final long serialVersionUID = 1L; /** * Creates a new Wavelength1DFormula, with * default number of points (100 points), and * default wavelength range (100 to 1100 nanometers). **/ public Wavelength1DFormula() { this(null, new Wavelength(100, Wavelength.NANOMETER), new Wavelength(1100, Wavelength.NANOMETER), 100); } /** * Creates a new Wavelength1DFormula of specified number of points, * no name, and default wavelength * range **/ public Wavelength1DFormula(int inPoints) { this(null, new Wavelength(100, Wavelength.NANOMETER), new Wavelength(1100, Wavelength.NANOMETER), inPoints); } /** * Creates a new Wavelength1DFormula with specified name and default * number of points and range. **/ public Wavelength1DFormula(String inName) { this(inName, new Wavelength(100, Wavelength.NANOMETER), new Wavelength(1100, Wavelength.NANOMETER), 100); } /** * Creates a new Wavelength1DFormula of with no name and specified * number of points and wavelength range. * * @param inMin Minimum Wavelength for the dataset * @param inMax Maximum Wavelength for the dataset * @param inPts number of points in the dataset **/ public Wavelength1DFormula(Wavelength inMin, Wavelength inMax, int inPts) { this(null, inMin, inMax, inPts); } /** * Creates a new Wavelength1DFormula of with specified name, * number of points and wavelength range. * * @param inProp Name of the dataset * @param inMin Minimum Wavelength for the dataset * @param inMax Maximum Wavelength for the dataset * @param inPts number of points in the dataset **/ public Wavelength1DFormula(String inProp, Wavelength inMin, Wavelength inMax, int inPts) { super(inProp); fMinWavelength = inMin; fMaxWavelength = inMax; fNumPoints = inPts; } public Object clone() { Wavelength1DFormula newDS = (Wavelength1DFormula) super.clone(); newDS.setMinWavelength((Wavelength) this.getMinWavelength().clone()); newDS.setMaxWavelength((Wavelength) this.getMaxWavelength().clone()); return newDS; } /** * After check with superclass, returns true if objects are same Class and * have same min/max and number * of points. **/ public boolean equals(Object obj) { if (obj == this) return true; if (!super.equals(obj)) return false; try { Wavelength1DFormula that = (Wavelength1DFormula) obj; if (!this.getClass().equals(that.getClass())) return false; if (fNumPoints != that.fNumPoints) return false; if ((fMinWavelength == null) ? (that.fMinWavelength != null) : !(fMinWavelength.equals(that.fMinWavelength))) return false; if ((fMaxWavelength == null) ? (that.fMaxWavelength != null) : !(fMaxWavelength.equals(that.fMaxWavelength))) return false; return true; } catch (Exception e) { return false; } } public Wavelength getMinWavelength() { return fMinWavelength; } public Wavelength getMaxWavelength() { return fMaxWavelength; } public void setMinWavelength(Wavelength newWL) { if (fMinWavelength != null) fMinWavelength.removePropertyChangeListener(this); Wavelength oldWL = fMinWavelength; fMinWavelength = newWL; if (fMinWavelength != null) fMinWavelength.addPropertyChangeListener(this); firePropertyChange(MINWAVELENGTH_PROPERTY, oldWL, newWL); } public void setMaxWavelength(Wavelength newWL) { if (fMaxWavelength != null) fMaxWavelength.removePropertyChangeListener(this); Wavelength oldWL = fMaxWavelength; fMaxWavelength = newWL; if (fMaxWavelength != null) fMaxWavelength.addPropertyChangeListener(this); firePropertyChange(MAXWAVELENGTH_PROPERTY, oldWL, newWL); } /** * overriding to public access */ public void setPending(boolean b) { super.setPending(b); } /** * Returns an array of doubles containing containing the formula's value * for each wavelength returned by toArrayWavelengths(). */ public double[] toArrayData() { double[] array = new double[fNumPoints]; double wl = fMinWavelength.getValue(); double inc = (fMaxWavelength.getValue() - wl) / fNumPoints; for (int i = 0; i < fNumPoints; i++) { array[i] = getValue(new Wavelength(wl)); wl += inc; } return array; } /** * Creates an array of doubles containing wavelength values at even intervals * across the min/max wavelength of the object and of size * getNumPoints() */ public double[] toArrayWavelengths() { double[] array = new double[fNumPoints]; double wl = fMinWavelength.getValue(); double inc = (fMaxWavelength.getValue() - wl) / fNumPoints; for (int i = 0; i < fNumPoints; i++) { array[i] = wl; wl += inc; } return array; } /** * Returns the wavelength data value for specified index as a Wavelength **/ public Wavelength getWavelengthAtIndex(int index) { return new Wavelength(getWavelengthAtIndexAsDouble(index)); } /** * Returns the wavelength data value for specified index * as a double value in the current default wavelength units **/ public double getWavelengthAtIndexAsDouble(int index) { double inc = (fMaxWavelength.getValue() - fMinWavelength.getValue()) / fNumPoints; return fMinWavelength.getValue() + index * inc; } /** * This is a trivial implementation that returns the formula value for a * specified index. Most subclasses of Wavelength1DFormula will * define getValue( Wavelength) and rarely if ever reference this method. * <P> * However, if * you have an array of wavelength values that you are "sharing" across * several different Wavelength1DFormula, then overriding this method to * define the formula's functionality, and then writing getValue to reference * this method may be computationally much faster. * * See SEA's ExpCalcSpectroscopy for an example. */ public double getValueAtIndex(int i) { return getValue(getWavelengthAtIndex(i)); } /** * Changes the length of the array that would be returned by toArrayWavelengths() * and toArrayData(). **/ public void setNumPoints(int newP) { int oldP = fNumPoints; fNumPoints = newP; firePropertyChange(NUMPOINTS_PROPERTY, new Integer(oldP), new Integer(newP)); } /** * returns the length of the array that would be returned by toArrayWavelengths() * and toArrayData(). **/ public int getNumPoints() { return fNumPoints; } }
bsd-3-clause
bocap/pgjdbc
org/postgresql/ssl/WrappedFactory.java
1738
/*------------------------------------------------------------------------- * * Copyright (c) 2004-2014, PostgreSQL Global Development Group * * *------------------------------------------------------------------------- */ package org.postgresql.ssl; import java.io.IOException; import java.net.Socket; import java.net.InetAddress; import javax.net.ssl.SSLSocketFactory; /** * Provide a wrapper to a real SSLSocketFactory delegating all calls * to the contained instance. A subclass needs only provide a * constructor for the wrapped SSLSocketFactory. */ public abstract class WrappedFactory extends SSLSocketFactory { protected SSLSocketFactory _factory; public Socket createSocket(InetAddress host, int port) throws IOException { return _factory.createSocket(host, port); } public Socket createSocket(String host, int port) throws IOException { return _factory.createSocket(host, port); } public Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException { return _factory.createSocket(host, port, localHost, localPort); } public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException { return _factory.createSocket(address, port, localAddress, localPort); } public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException { return _factory.createSocket(socket, host, port, autoClose); } public String[] getDefaultCipherSuites() { return _factory.getDefaultCipherSuites(); } public String[] getSupportedCipherSuites() { return _factory.getSupportedCipherSuites(); } }
bsd-3-clause
kashike/SpongeAPI
src/main/java/org/spongepowered/api/entity/ai/task/package-info.java
1353
/* * This file is part of SpongeAPI, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ @org.spongepowered.api.util.annotation.NonnullByDefault package org.spongepowered.api.entity.ai.task;
mit
YouDiSN/OpenJDK-Research
jdk9/hotspot/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.jtt/src/org/graalvm/compiler/jtt/optimize/ArrayCopy04.java
3589
/* * Copyright (c) 2011, 2012, 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. */ package org.graalvm.compiler.jtt.optimize; import org.junit.Before; import org.junit.Test; import org.graalvm.compiler.jtt.JTTTest; /* * Tests calls to the array copy method. */ public class ArrayCopy04 extends JTTTest { public static byte[] array = new byte[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; public static byte[] array0 = new byte[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; static { // Ensure System is resolved System.arraycopy(array, 0, array, 0, array.length); } @Before public void setUp() { System.currentTimeMillis(); for (int i = 0; i < array.length; i++) { array[i] = array0[i]; } } public static byte[] test(int srcPos, int destPos, int length) { System.arraycopy(array, srcPos, array, destPos, length); return array; } @Test public void run0() throws Throwable { runTest("test", 0, 0, 0); } @Test public void run1() throws Throwable { runTest("test", 0, 0, -1); } @Test public void run2() throws Throwable { runTest("test", -1, 0, 0); } @Test public void run3() throws Throwable { runTest("test", 0, -1, 0); } @Test public void run4() throws Throwable { runTest("test", 0, 0, 2); } @Test public void run5() throws Throwable { runTest("test", 0, 1, 11); } @Test public void run6() throws Throwable { runTest("test", 1, 0, 11); } @Test public void run7() throws Throwable { runTest("test", 1, 1, -1); } @Test public void run8() throws Throwable { runTest("test", 0, 1, 2); } @Test public void run9() throws Throwable { runTest("test", 1, 0, 2); } @Test public void run10() throws Throwable { runTest("test", 1, 1, 2); } @Test public void run11() throws Throwable { runTest("test", 0, 0, 6); } @Test public void run12() throws Throwable { runTest("test", 0, 1, 5); } @Test public void run13() throws Throwable { runTest("test", 1, 0, 5); } @Test public void run14() throws Throwable { runTest("test", 1, 1, 5); } @Test public void run15() throws Throwable { runTest("test", 0, 0, 11); } @Test public void run16() throws Throwable { runTest("test", 0, 1, 10); } @Test public void run17() throws Throwable { runTest("test", 1, 0, 10); } }
gpl-2.0
nonconforme/Android-IMSI-Catcher-Detector
app/src/main/java/com/SecUpwN/AIMSICD/adapters/BtsMeasureItemData.java
8460
package com.SecUpwN.AIMSICD.adapters; /** * Description: Contains the data and definitions of all the items of the XML layout * * Dependencies: * DbViewerFragment.java: BuildTable() * BtsMeasureCardInflater.java * bts_measure_data.xml * * TODO: * [ ] Order all the items according to appearance found in the DB table below * * NOTE: * * CREATE TABLE "DBi_measure" ( * "_id" INTEGER PRIMARY KEY AUTOINCREMENT, * "bts_id" INTEGER NOT NULL, -- DBi_bts:_id * "nc_list" TEXT, -- Neighboring Cells List (TODO: specify content) * "time" INTEGER NOT NULL, -- [s] * "gpsd_lat" REAL, -- Device GPS (allow NULL) * "gpsd_lon" REAL, -- Device GPS (allow NULL) * "gpsd_accu" INTEGER, -- Device GPS position accuracy [m] * "gpse_lat" REAL, -- Exact GPS (from where? DBi_import?) * "gpse_lon" REAL, -- Exact GPS (from where? DBi_import?) * "bb_power" TEXT, -- [mW] or [mA] (from BP power rail usage) * "bb_rf_temp" TEXT, -- [C] (from BP internal thermistor) * "tx_power" TEXT, -- [dBm] (from BP ) * "rx_signal" TEXT, -- [dBm] or ASU (from AP/BP) * "rx_stype" TEXT, -- Reveived Signal power Type [RSSI, ...] etc. * "RAT" TEXT NOT NULL, -- Radio Access Technology * "BCCH" TEXT, -- Broadcast Channel -- consider INTEGER * "TMSI" TEXT, -- Temporary IMSI (hex) * "TA" INTEGER DEFAULT 0, -- Timing Advance (GSM, LTE) -- allow NULL * "PD" INTEGER DEFAULT 0, -- Propagation Delay (LTE) -- allow NULL * "BER" INTEGER DEFAULT 0, -- Bit Error Rate -- allow NULL * "AvgEcNo" TEXT, -- Average Ec/No -- consider REAL * "isSubmitted" INTEGER DEFAULT 0, -- * Has been submitted to OCID/MLS etc? * "isNeighbour" INTEGER DEFAULT 0, -- * Is a neighboring BTS? [Is this what we want?] * FOREIGN KEY("bts_id") -- * REFERENCES "DBi_bts"("_id") -- * ); * * * ChangeLog: * 2015-07-08 Marvin Arnold Initial commit * 2015-07-27 E:V:A Added placeholders for missing items * */ public class BtsMeasureItemData { public String getBts_id() { return bts_id; } public void setBts_id(String bts_id) { this.bts_id = bts_id; } public String getNc_list() { return nc_list; } public void setNc_list(String nc_list) { this.nc_list = nc_list; } public String getTime() { return time; } public void setTime(String time) { this.time = time; } public String getGpsd_lat() { return gpsd_lat; } public void setGpsd_lat(String gpsd_lat) { this.gpsd_lat = gpsd_lat; } public String getGpsd_lon() { return gpsd_lon; } public void setGpsd_lon(String gpsd_lon) { this.gpsd_lon = gpsd_lon; } public String getGpsd_accu() { return gpsd_accu; } public void setGpsd_accu(String gpsd_accu) { this.gpsd_accu = gpsd_accu; } public String getGpse_lat() { return gpse_lat; } public void setGpse_lat(String gpse_lat) { this.gpse_lat = gpse_lat; } public String getGpse_lon() { return gpse_lon; } public void setGpse_lon(String gpse_lon) { this.gpse_lon = gpse_lon; } public String getBb_power() { return bb_power; } public void setBb_power(String bb_power) { this.bb_power = bb_power; } public String getBb_rf_temp() { return bb_rf_temp; } public void setBb_rf_temp(String bb_rf_temp) { this.bb_rf_temp = bb_rf_temp; } public String getTx_power() { return tx_power; } public void setTx_power(String tx_power) { this.tx_power = tx_power; } public String getRx_signal() { return rx_signal; } public void setRx_signal(String rx_signal) { this.rx_signal = rx_signal; } public String getRx_stype() { return rx_stype; } public void setRx_stype(String rx_stype) { this.rx_stype = rx_stype; } public String getRat() { return rat; } public void setRat(String rat) { this.rat = rat; } public String getBCCH() { return BCCH; } public void setBCCH(String BCCH) { this.BCCH = BCCH; } public String getTMSI() { return TMSI; } public void setTMSI(String TMSI) { this.TMSI = TMSI; } public String getTA() { return TA; } public void setTA(String TA) { this.TA = TA; } public String getPD() { return PD; } public void setPD(String PD) { this.PD = PD; } public String getBER() { return BER; } public void setBER(String BER) { this.BER = BER; } public String getAvgEcNo() { return AvgEcNo; } public void setAvgEcNo(String avgEcNo) { AvgEcNo = avgEcNo; } public String getIsSubmitted() { return isSubmitted; } public void setIsSubmitted(String isSubmitted) { this.isSubmitted = isSubmitted; } public String getIsNeighbour() { return isNeighbour; } public void setIsNeighbour(String isNeighbour) { this.isNeighbour = isNeighbour; } public String getRecordId() { return mRecordId; } private String bts_id; private String nc_list; private String time; private String gpsd_lat; private String gpsd_lon; private String gpsd_accu; private String gpse_lat; private String gpse_lon; private String bb_power; private String bb_rf_temp; private String tx_power; private String rx_signal; private String rx_stype; private String rat; private String BCCH; private String TMSI; private String TA; private String PD; private String BER; private String AvgEcNo; private String isSubmitted; private String isNeighbour; private String mRecordId; public BtsMeasureItemData( String _bts_id, String _nc_list, String _time, String _gpsd_lat, String _gpsd_lon, String _gpsd_accu, // String _gpse_lat, // String _gpse_lon, // String _bb_power, // String _bb_rf_temp, // String _tx_power, String _rx_signal, // String _rx_stype, String _rat, // String _BCCH, // String _TMSI, // String _TA, // String _PD, // String _BER, // String _AvgEcNo, String _isSubmitted, String _isNeighbour, String _mRecordId) { this.bts_id = _bts_id; this.nc_list = _nc_list; this.time = _time; this.gpsd_lat = _gpsd_lat; this.gpsd_lon = _gpsd_lon; this.gpsd_accu = _gpsd_accu; // this.gpse_lat = _gpse_lat; // this.gpse_lon = _gpse_lon; // this.bb_power = _bb_power; // this.bb_rf_temp = _bb_rf_temp; // this.tx_power = _tx_power; this.rx_signal = _rx_signal; // this.rx_stype = _rx_stype; this.rat = _rat; // this.BCCH = _BCCH; // this.TMSI = _TMSI; // this.TA = _TA; // this.PD = _PD; // this.BER = _BER; // this.AvgEcNo = _AvgEcNo; this.isSubmitted = _isSubmitted; this.isNeighbour = _isNeighbour; this.mRecordId = _mRecordId; } public BtsMeasureItemData(String... args) { this( args[0], // bts_id args[1], // nc_list args[2], // time args[3], // gpsd_lat args[4], // gpsd_lon args[5], // gpsd_accu args[6], // rx_signal args[7], // rat args[8], // isSubmitted args[9], // isNeighbour args[10] // mRecordId // EVA //, ); } }
gpl-3.0
antidata/htm.java
src/main/java/org/numenta/nupic/encoders/RandomDistributedScalarEncoder.java
21928
/* --------------------------------------------------------------------- * Numenta Platform for Intelligent Computing (NuPIC) * Copyright (C) 2014, Numenta, Inc. Unless you have an agreement * with Numenta, Inc., for a separate license for this software code, the * following terms and conditions apply: * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero Public License version 3 as * published by the Free Software Foundation. * * 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 Public License for more details. * * You should have received a copy of the GNU Affero Public License * along with this program. If not, see http://www.gnu.org/licenses. * * http://numenta.org/licenses/ * --------------------------------------------------------------------- */ package org.numenta.nupic.encoders; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import org.numenta.nupic.FieldMetaType; import org.numenta.nupic.util.MersenneTwister; import org.numenta.nupic.util.Tuple; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * <p> * A scalar encoder encodes a numeric (floating point) value into an array of * bits. * * This class maps a scalar value into a random distributed representation that * is suitable as scalar input into the spatial pooler. The encoding scheme is * designed to replace a simple ScalarEncoder. It preserves the important * properties around overlapping representations. Unlike ScalarEncoder the min * and max range can be dynamically increased without any negative effects. The * only required parameter is resolution, which determines the resolution of * input values. * * Scalar values are mapped to a bucket. The class maintains a random * distributed encoding for each bucket. The following properties are maintained * by RandomDistributedEncoder: * </p> * <ol> * <li>Similar scalars should have high overlap. Overlap should decrease * smoothly as scalars become less similar. Specifically, neighboring bucket * indices must overlap by a linearly decreasing number of bits. * * <li>Dissimilar scalars should have very low overlap so that the SP does not * confuse representations. Specifically, buckets that are more than w indices * apart should have at most maxOverlap bits of overlap. We arbitrarily (and * safely) define "very low" to be 2 bits of overlap or lower. * * Properties 1 and 2 lead to the following overlap rules for buckets i and j:<br> * * <pre> * {@code * If abs(i-j) < w then: * overlap(i,j) = w - abs(i-j); * else: * overlap(i,j) <= maxOverlap; * } * </pre> * * <li>The representation for a scalar must not change during the lifetime of * the object. Specifically, as new buckets are created and the min/max range is * extended, the representation for previously in-range scalars and previously * created buckets must not change. * </ol> * * * @author Numenta * @author Anubhav Chaturvedi */ public class RandomDistributedScalarEncoder extends Encoder<Double> { private static final Logger LOG = LoggerFactory.getLogger(RandomDistributedScalarEncoder.class); public static final long DEFAULT_SEED = 42; // Mersenne Twister RNG, same as used with numpy.random MersenneTwister rng; int maxOverlap; int maxBuckets; Double offset; long seed; int minIndex; int maxIndex; int numRetry; ConcurrentHashMap<Integer, List<Integer>> bucketMap; RandomDistributedScalarEncoder() { } public static Encoder.Builder<RandomDistributedScalarEncoder.Builder, RandomDistributedScalarEncoder> builder() { return new RandomDistributedScalarEncoder.Builder(); } /** * Perform validation on state parameters and proceed with initialization of * the encoder. * * @throws IllegalStateException * Throws {@code IllegalStateException} containing appropriate * message if some validation fails. */ public void init() throws IllegalStateException { if (getW() <= 0 || getW() % 2 == 0) throw new IllegalStateException( "W must be an odd positive integer (to eliminate centering difficulty)"); setHalfWidth((getW() - 1) / 2); if (getResolution() <= 0) throw new IllegalStateException( "Resolution must be a positive number"); if (n <= 6 * getW()) throw new IllegalStateException( "n must be strictly greater than 6*w. For good results we " + "recommend n be strictly greater than 11*w."); initEncoder(getResolution(), getW(), getN(), getOffset(), getSeed()); } /** * Perform the initialization of the encoder. * * @param resolution * @param w * @param n * @param offset * @param seed */ // TODO why are none of these parameters used..? public void initEncoder(double resolution, int w, int n, Double offset, long seed) { rng = (seed == -1) ? new MersenneTwister() : new MersenneTwister(seed); initializeBucketMap(getMaxBuckets(), getOffset()); if (getName() == null || getName().isEmpty()) { setName("[" + getResolution() + "]"); } // TODO reduce logging level? LOG.debug(this.toString()); } /** * Initialize the bucket map assuming the given number of maxBuckets. * * @param maxBuckets * @param offset */ public void initializeBucketMap(int maxBuckets, Double offset) { /* * The first bucket index will be _maxBuckets / 2 and bucket indices * will be allowed to grow lower or higher as long as they don't become * negative. _maxBuckets is required because the current CLA Classifier * assumes bucket indices must be non-negative. This normally does not * need to be changed but if altered, should be set to an even number. */ setMaxBuckets(maxBuckets); setMinIndex(maxBuckets / 2); setMaxIndex(maxBuckets / 2); /* * The scalar offset used to map scalar values to bucket indices. The * middle bucket will correspond to numbers in the range * [offset-resolution/2, offset+resolution/2). The bucket index for a * number x will be: maxBuckets/2 + int( round( (x-offset)/resolution ) * ) */ setOffset(offset); /* * This HashMap maps a bucket index into its bit representation We * initialize the HashMap with a single bucket with index 0 */ bucketMap = new ConcurrentHashMap<Integer, List<Integer>>(); // generate the random permutation ArrayList<Integer> temp = new ArrayList<Integer>(getN()); for (int i = 0; i < getN(); i++) temp.add(i, i); java.util.Collections.shuffle(temp, rng); bucketMap.put(getMinIndex(), temp.subList(0, getW())); // How often we need to retry when generating valid encodings setNumRetry(0); } /** * Create the given bucket index. Recursively create as many in-between * bucket indices as necessary. * * @param index the index at which bucket needs to be created * @throws IllegalStateException */ public void createBucket(int index) throws IllegalStateException { if (index < getMinIndex()) { if (index == getMinIndex() - 1) { /* * Create a new representation that has exactly w-1 overlapping * bits as the min representation */ bucketMap.put(index, newRepresentation(getMinIndex(), index)); setMinIndex(index); } else { // Recursively create all the indices above and then this index createBucket(index + 1); createBucket(index); } } else { if (index == getMaxIndex() + 1) { /* * Create a new representation that has exactly w-1 overlapping * bits as the max representation */ bucketMap.put(index, newRepresentation(getMaxIndex(), index)); setMaxIndex(index); } else { // Recursively create all the indices below and then this index createBucket(index - 1); createBucket(index); } } } /** * Get a new representation for newIndex that overlaps with the * representation at index by exactly w-1 bits * * @param index * @param newIndex * @throws IllegalStateException */ public List<Integer> newRepresentation(int index, int newIndex) throws IllegalStateException { List<Integer> newRepresentation = new ArrayList<Integer>( bucketMap.get(index)); /* * Choose the bit we will replace in this representation. We need to * shift this bit deterministically. If this is always chosen randomly * then there is a 1 in w chance of the same bit being replaced in * neighboring representations, which is fairly high */ int ri = newIndex % getW(); // Now we choose a bit such that the overlap rules are satisfied. int newBit = rng.nextInt(getN()); newRepresentation.set(ri, newBit); while (bucketMap.get(index).contains(newBit) || !newRepresentationOK(newRepresentation, newIndex)) { setNumRetry(getNumRetry() + 1); newBit = rng.nextInt(getN()); newRepresentation.set(ri, newBit); } return newRepresentation; } /** * Check if this new candidate representation satisfies all our * overlap rules. Since we know that neighboring representations differ by * at most one bit, we compute running overlaps. * * @param newRep Encoded SDR to be considered * @param newIndex The index being considered * @return {@code true} if newRep satisfies all our overlap rules * @throws IllegalStateException */ public boolean newRepresentationOK(List<Integer> newRep, int newIndex) { if (newRep.size() != getW()) return false; if (newIndex < getMinIndex() - 1 || newIndex > getMaxIndex() + 1) { throw new IllegalStateException( "newIndex must be within one of existing indices"); } // A binary representation of newRep. We will use this to test // containment boolean[] newRepBinary = new boolean[getN()]; Arrays.fill(newRepBinary, false); for (int index : newRep) newRepBinary[index] = true; // Midpoint int midIdx = getMaxBuckets() / 2; // Start by checking the overlap at minIndex int runningOverlap = countOverlap(bucketMap.get(getMinIndex()), newRep); if (!overlapOK(getMinIndex(), newIndex, runningOverlap)) return false; // Compute running overlaps all the way to the midpoint for (int i = getMinIndex() + 1; i < midIdx + 1; i++) { // This is the bit that is going to change int newBit = (i - 1) % getW(); // Update our running overlap if (newRepBinary[bucketMap.get(i - 1).get(newBit)]) runningOverlap--; if (newRepBinary[bucketMap.get(i).get(newBit)]) runningOverlap++; // Verify our rules if (!overlapOK(i, newIndex, runningOverlap)) return false; } // At this point, runningOverlap contains the overlap for midIdx // Compute running overlaps all the way to maxIndex for (int i = midIdx + 1; i <= getMaxIndex(); i++) { int newBit = i % getW(); // Update our running overlap if (newRepBinary[bucketMap.get(i - 1).get(newBit)]) runningOverlap--; if (newRepBinary[bucketMap.get(i).get(newBit)]) runningOverlap++; // Verify our rules if (!overlapOK(i, newIndex, runningOverlap)) return false; } return true; } /** * Get the overlap between two representations. rep1 and rep2 are * {@link List} of non-zero indices. * * @param rep1 The first representation for overlap calculation * @param rep2 The second representation for overlap calculation * @return The number of 'on' bits that overlap */ public int countOverlap(List<Integer> rep1, List<Integer> rep2) { int overlap = 0; for (int index : rep1) { for (int index2 : rep2) if (index == index2) overlap++; } return overlap; } /** * Get the overlap between two representations. rep1 and rep2 are arrays * of non-zero indices. * * @param rep1 The first representation for overlap calculation * @param rep2 The second representation for overlap calculation * @return The number of 'on' bits that overlap */ public int countOverlap(int[] rep1, int[] rep2) { int overlap = 0; for (int index : rep1) { for (int index2 : rep2) if (index == index2) overlap++; } return overlap; } /** * Check if the given overlap between bucket indices i and j are acceptable. * * @param i The index of the bucket to be compared * @param j The index of the bucket to be compared * @param overlap The overlap between buckets at index i and j * @return {@code true} if overlap is acceptable, else {@code false} */ public boolean overlapOK(int i, int j, int overlap) { if (Math.abs(i - j) < getW() && overlap == (getW() - Math.abs(i - j))) return true; if (Math.abs(i - j) >= getW() && overlap <= getMaxOverlap()) return true; return false; } /** * Check if the overlap between the buckets at indices i and j are * acceptable. The overlap is calculate from the bucketMap. * * @param i The index of the bucket to be compared * @param j The index of the bucket to be compared * @return {@code true} if the given overlap is acceptable, else {@code false} * @throws IllegalStateException */ public boolean overlapOK(int i, int j) throws IllegalStateException { return overlapOK(i, j, countOverlapIndices(i, j)); } /** * Get the overlap between bucket at indices i and j * * @param i The index of the bucket * @param j The index of the bucket * @return the overlap between bucket at indices i and j * @throws IllegalStateException */ public int countOverlapIndices(int i, int j) throws IllegalStateException { boolean containsI = bucketMap.containsKey(i); boolean containsJ = bucketMap.containsKey(j); if (containsI && containsJ) { List<Integer> rep1 = bucketMap.get(i); List<Integer> rep2 = bucketMap.get(j); return countOverlap(rep1, rep2); } else if (!containsI && !containsJ) throw new IllegalStateException("index " + i + " and " + j + " don't exist"); else if(!containsI) throw new IllegalStateException("index " + i + " doesn't exist"); else throw new IllegalStateException("index " + j + " doesn't exist"); } /** * Given a bucket index, return the list of indices of the 'on' bits. If the * bucket index does not exist, it is created. If the index falls outside * our range we clip it. * * @param index The bucket index * @return The list of active bits in the representation * @throws IllegalStateException */ public List<Integer> mapBucketIndexToNonZeroBits(int index) throws IllegalStateException { if (index < 0) index = 0; if (index >= getMaxBuckets()) index = getMaxBuckets() - 1; if (!bucketMap.containsKey(index)) { LOG.trace("Adding additional buckets to handle index={} ", index); createBucket(index); } return bucketMap.get(index); } /** * {@inheritDoc} */ @Override public int[] getBucketIndices(double x) { if (Double.isNaN(x)) x = Encoder.SENTINEL_VALUE_FOR_MISSING_DATA; int test = Double.compare(x, Encoder.SENTINEL_VALUE_FOR_MISSING_DATA); if (test == 0) return new int[0]; if (getOffset() == null) setOffset(x); /* * Difference in the round function behavior for Python and Java In * Python, the absolute value is rounded up and sign is applied in Java, * value is rounded to next biggest integer * * so for Python, round(-0.5) => -1.0 whereas in Java, Math.round(-0.5) * => 0.0 */ double deltaIndex = (x - getOffset()) / getResolution(); int sign = (int) (deltaIndex / Math.abs(deltaIndex)); int bucketIdx = (getMaxBuckets() / 2) + (sign * (int) Math.round(Math.abs(deltaIndex))); if (bucketIdx < 0) bucketIdx = 0; else if (bucketIdx >= getMaxBuckets()) bucketIdx = getMaxBuckets() - 1; int[] bucketIdxArray = new int[1]; bucketIdxArray[0] = bucketIdx; return bucketIdxArray; } /** * {@inheritDoc} */ @Override public int getWidth() { return getN(); } /** * {@inheritDoc} */ @Override public boolean isDelta() { return false; } /** * {@inheritDoc} */ @Override public void setLearning(boolean learningEnabled) { setLearningEnabled(learningEnabled); } /** * {@inheritDoc} */ @Override public List<Tuple> getDescription() { String name = getName(); if (name == null || name.isEmpty()) setName("[" + getResolution() + "]"); name = getName(); return new ArrayList<Tuple>(Arrays.asList(new Tuple[] { new Tuple(name, 0) })); } /** * @return maxOverlap for this RDSE */ public int getMaxOverlap() { return maxOverlap; } /** * @return the maxBuckets for this RDSE */ public int getMaxBuckets() { return maxBuckets; } /** * @return the seed for the random number generator */ public long getSeed() { return seed; } /** * @return the offset */ public Double getOffset() { return offset; } private int getMinIndex() { return minIndex; } private int getMaxIndex() { return maxIndex; } /** * @return the number of retry to create new bucket */ public int getNumRetry() { return numRetry; } /** * @param maxOverlap The maximum permissible overlap between representations */ public void setMaxOverlap(int maxOverlap) { this.maxOverlap = maxOverlap; } /** * @param maxBuckets the new maximum number of buckets allowed */ public void setMaxBuckets(int maxBuckets) { this.maxBuckets = maxBuckets; } /** * @param seed */ public void setSeed(long seed) { this.seed = seed; } /** * @param offset */ public void setOffset(Double offset) { this.offset = offset; } private void setMinIndex(int minIndex) { this.minIndex = minIndex; } private void setMaxIndex(int maxIndex) { this.maxIndex = maxIndex; } /** * @param numRetry New number of retries for new representation */ public void setNumRetry(int numRetry) { this.numRetry = numRetry; } @Override public String toString() { // TODO don't mix StringBuilder appending with String concatenation StringBuilder dumpString = new StringBuilder(50); dumpString.append("RandomDistributedScalarEncoder:\n"); dumpString.append(" minIndex: " + getMinIndex() + "\n"); dumpString.append(" maxIndex: " + getMaxIndex() + "\n"); dumpString.append(" w: " + getW() + "\n"); dumpString.append(" n: " + getWidth() + "\n"); dumpString.append(" resolution: " + getResolution() + "\n"); dumpString.append(" offset: " + getOffset() + "\n"); dumpString.append(" numTries: " + getNumRetry() + "\n"); dumpString.append(" name: " + getName() + "\n"); dumpString.append(" buckets : \n"); for (int index : bucketMap.keySet()) { dumpString.append(" [ " + index + " ]: " + Arrays.deepToString(bucketMap.get(index).toArray()) + "\n"); } return dumpString.toString(); } /** * <p> * Returns a {@link Encoder.Builder} for constructing * {@link RandomDistributedScalarEncoder}s. * </p> * <p> * The base class architecture is put together in such a way where * boilerplate initialization can be kept to a minimum for implementing * subclasses, while avoiding the mistake-proneness of extremely long * argument lists. * </p> * * @author Anubhav Chaturvedi */ public static class Builder extends Encoder.Builder<RandomDistributedScalarEncoder.Builder, RandomDistributedScalarEncoder> { private int maxOverlap; private int maxBuckets; private Double offset; private long seed; int minIndex; int maxIndex; private Builder() { this.n(400); this.w(21); seed = 42; maxBuckets = 1000; maxOverlap = 2; offset = null; } private Builder(int n, int w) { this(); this.n(n); this.w(w); } @Override public RandomDistributedScalarEncoder build() { // Must be instantiated so that super class can initialize // boilerplate variables. encoder = new RandomDistributedScalarEncoder(); // Call super class here RandomDistributedScalarEncoder partialBuild = super.build(); //////////////////////////////////////////////////////// // Implementing classes would do setting of specific // // vars here together with any sanity checking // //////////////////////////////////////////////////////// partialBuild.setSeed(seed); partialBuild.setMaxOverlap(maxOverlap); partialBuild.setMaxBuckets(maxBuckets); partialBuild.setOffset(offset); partialBuild.setNumRetry(0); partialBuild.init(); return partialBuild; } public RandomDistributedScalarEncoder.Builder setOffset(double offset) { this.offset = Double.valueOf(offset); return this; } public RandomDistributedScalarEncoder.Builder setMaxBuckets( int maxBuckets) { this.maxBuckets = maxBuckets; return this; } public RandomDistributedScalarEncoder.Builder setMaxOverlap( int maxOverlap) { this.maxOverlap = maxOverlap; return this; } public RandomDistributedScalarEncoder.Builder setSeed(long seed) { this.seed = seed; return this; } } /** * {@inheritDoc} */ @Override public void encodeIntoArray(Double inputData, int[] output) { int[] bucketIdx = getBucketIndices(inputData); Arrays.fill(output, 0); if (bucketIdx.length == 0) return; if (bucketIdx[0] != Integer.MIN_VALUE) { List<Integer> indices; try { indices = mapBucketIndexToNonZeroBits(bucketIdx[0]); for (int index : indices) output[index] = 1; } catch (IllegalStateException e) { e.printStackTrace(); } } } /** * {@inheritDoc} */ @SuppressWarnings("unchecked") @Override public <S> List<S> getBucketValues(Class<S> returnType) { return new ArrayList<>((Collection<S>)this.bucketMap.keySet()); } /** * {@inheritDoc} */ @Override public Set<FieldMetaType> getDecoderOutputFieldTypes() { return new LinkedHashSet<FieldMetaType>(Arrays.asList(FieldMetaType.FLOAT, FieldMetaType.INTEGER)); } }
agpl-3.0
xasx/wildfly
testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jca/beanvalidation/ra/ValidGroup.java
152
package org.jboss.as.test.integration.jca.beanvalidation.ra; import javax.validation.groups.Default; public interface ValidGroup extends Default { }
lgpl-2.1
xasx/wildfly
testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/ejb/transaction/methodparams/Local.java
1264
/* * JBoss, Home of Professional Open Source. * Copyright 2011, 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.test.integration.ejb.transaction.methodparams; import javax.ejb.EJBLocalObject; public interface Local extends EJBLocalObject { boolean test(String[] s); boolean test(String s); boolean test(int x); }
lgpl-2.1
aloubyansky/wildfly-core
testsuite/patching/src/test/java/org/jboss/as/test/patching/RollbackLastUnitTestCase.java
9549
/* * JBoss, Home of Professional Open Source. * Copyright 2013, 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.test.patching; import static org.jboss.as.patching.Constants.BASE; import static org.jboss.as.patching.Constants.LAYERS; import static org.jboss.as.patching.Constants.MODULES; import static org.jboss.as.patching.Constants.SYSTEM; import static org.jboss.as.patching.IoUtils.mkdir; import static org.jboss.as.patching.IoUtils.newFile; import static org.jboss.as.test.patching.PatchingTestUtil.MODULES_PATH; import static org.jboss.as.test.patching.PatchingTestUtil.assertPatchElements; import static org.jboss.as.test.patching.PatchingTestUtil.createPatchXMLFile; import static org.jboss.as.test.patching.PatchingTestUtil.createZippedPatchFile; import static org.jboss.as.test.patching.PatchingTestUtil.dump; import static org.jboss.as.test.patching.PatchingTestUtil.randomString; import static org.jboss.as.test.patching.PatchingTestUtil.touch; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.fail; import java.io.File; import java.nio.charset.StandardCharsets; import org.jboss.as.cli.CommandContext; import org.jboss.as.patching.HashUtils; import org.jboss.as.patching.metadata.ContentModification; import org.jboss.as.patching.metadata.Patch; import org.jboss.as.patching.metadata.PatchBuilder; import org.jboss.as.test.integration.management.util.CLITestUtil; import org.jboss.as.test.patching.util.module.Module; import org.jboss.as.version.ProductConfig; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.wildfly.core.testrunner.ServerControl; import org.wildfly.core.testrunner.WildflyTestRunner; /** * @author Alexey Loubyansky */ @RunWith(WildflyTestRunner.class) @ServerControl(manual = true) public class RollbackLastUnitTestCase extends AbstractPatchingTestCase { protected ProductConfig productConfig; @Before public void setup() throws Exception { productConfig = new ProductConfig(PatchingTestUtil.PRODUCT, PatchingTestUtil.AS_VERSION, "main"); } @Test public void testMain() throws Exception { // build a one-off patch for the base installation // with 1 updated file String patchID = randomString(); String patchElementId = randomString(); File patchDir = mkdir(tempDir, patchID); // create a module to be updated w/o a conflict File baseModuleDir = newFile(new File(PatchingTestUtil.AS_DISTRIBUTION), MODULES, SYSTEM, LAYERS, BASE); String moduleName = "module-test"; Module module = new Module.Builder(moduleName) .miscFile(new ResourceItem("resource-test", "new resource in the module".getBytes(StandardCharsets.UTF_8))) .build(); File moduleDir = module.writeToDisk(new File(MODULES_PATH)); // create the patch with the updated module ContentModification moduleModified = ContentModificationUtils.modifyModule(patchDir, patchElementId, HashUtils.hashFile(moduleDir), module); // create a file for the conflict String fileName = "file-test.txt"; File miscFile = touch(new File(PatchingTestUtil.AS_DISTRIBUTION, "bin"), fileName); dump(miscFile, "original script to run standalone AS7"); byte[] originalFileHash = HashUtils.hashFile(miscFile); // patch the file ContentModification fileModified = ContentModificationUtils.modifyMisc(patchDir, patchID, "updated script", miscFile, "bin", fileName); Patch patch = PatchBuilder.create() .setPatchId(patchID) .setDescription(randomString()) .upgradeIdentity(productConfig.getProductName(), productConfig.getProductVersion(), productConfig.getProductVersion() + "CP1") .getParent() .addContentModification(fileModified) .upgradeElement(patchElementId, "base", false) .addContentModification(moduleModified) .getParent() .build(); // create the patch createPatchXMLFile(patchDir, patch); File zippedPatch = createZippedPatchFile(patchDir, patch.getPatchId()); // no patches applied assertPatchElements(baseModuleDir, null); controller.start(); // apply the patch using the cli CommandContext ctx = CLITestUtil.getCommandContext(); try { ctx.connectController(); ctx.handle("patch apply " + zippedPatch.getAbsolutePath()); } catch (Exception e) { ctx.terminateSession(); throw e; } finally { controller.stop(); } // first patch applied assertPatchElements(baseModuleDir, new String[]{patchElementId}, false); byte[] patch1FileHash = HashUtils.hashFile(miscFile); assertNotEqual(originalFileHash, patch1FileHash); // next patch final String patchID2 = randomString(); final String patchElementId2 = randomString(); final File patchedModule = newFile(baseModuleDir, ".overlays", patchElementId, moduleName); Module modifiedModule = new Module.Builder(moduleName) .miscFile(new ResourceItem("resource-test", "another module update".getBytes(StandardCharsets.UTF_8))) .build(); ContentModification fileModified2 = ContentModificationUtils.modifyMisc(patchDir, patchID2, "another file update", miscFile, "bin", fileName); ContentModification moduleModified2 = ContentModificationUtils.modifyModule(patchDir, patchElementId2, HashUtils.hashFile(patchedModule), modifiedModule); Patch patch2 = PatchBuilder.create() .setPatchId(patchID2) .setDescription(randomString()) .upgradeIdentity(productConfig.getProductName(), productConfig.getProductVersion() + "CP1", productConfig.getProductName() + "CP2") .getParent() .addContentModification(fileModified2) .upgradeElement(patchElementId2, "base", false) .addContentModification(moduleModified2) .getParent() .build(); createPatchXMLFile(patchDir, patch2); File zippedPatch2 = createZippedPatchFile(patchDir, patch2.getPatchId()); controller.start(); try { ctx.handle("patch apply " + zippedPatch2.getAbsolutePath()); } catch (Exception e) { e.printStackTrace(); ctx.terminateSession(); throw e; } finally { controller.stop(); } // both patches applied assertPatchElements(baseModuleDir, new String[]{patchElementId, patchElementId2}, false); byte[] patch2FileHash = HashUtils.hashFile(miscFile); assertNotEqual(patch1FileHash, patch2FileHash); assertNotEqual(originalFileHash, patch2FileHash); controller.start(); try { ctx.handle("patch rollback --reset-configuration=false"); } catch (Exception e) { ctx.terminateSession(); throw e; } finally { controller.stop(); } byte[] curFileHash = HashUtils.hashFile(miscFile); assertNotEqual(curFileHash, patch2FileHash); assertArrayEquals(curFileHash, patch1FileHash); assertNotEqual(curFileHash, originalFileHash); controller.start(); try { // only the first patch is present assertPatchElements(baseModuleDir, new String[]{patchElementId}, false); ctx.handle("patch rollback --reset-configuration=false"); } catch (Exception e) { ctx.terminateSession(); throw e; } finally { ctx.terminateSession(); controller.stop(); } try { controller.start(); // no patches present assertPatchElements(baseModuleDir, null, false); } finally { controller.stop(); } curFileHash = HashUtils.hashFile(miscFile); assertNotEqual(curFileHash, patch2FileHash); assertNotEqual(curFileHash, patch1FileHash); assertArrayEquals(curFileHash, originalFileHash); } private static void assertNotEqual(byte[] a1, byte[] a2) { if (a1.length != a2.length) { return; } for (int i = 0; i < a1.length; ++i) { if (a1[i] != a2[i]) { return; } } fail("arrays are equal"); } }
lgpl-2.1
roele/sling
bundles/extensions/models/api/src/main/java/org/apache/sling/models/factory/ModelFactory.java
11599
/* * 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.sling.models.factory; import javax.annotation.Nonnull; import org.apache.sling.api.SlingHttpServletRequest; import org.apache.sling.api.resource.Resource; import aQute.bnd.annotation.ProviderType; import java.util.Map; /** * The ModelFactory instantiates Sling Model classes similar to #adaptTo but will throw an exception in case * instantiation fails for some reason. */ @ProviderType public interface ModelFactory { /** * Instantiates the given Sling Model class from the given adaptable. * @param adaptable the adaptable to use to instantiate the Sling Model Class * @param type the class to instantiate * @return a new instance for the required model (never {@code null}) * @throws MissingElementsException in case no injector was able to inject some required values with the given types * @throws InvalidAdaptableException in case the given class cannot be instantiated from the given adaptable (different adaptable on the model annotation) * @throws ModelClassException in case the model could not be instantiated because model annotation was missing, reflection failed, no valid constructor was found, model was not registered as adapter factory yet, or post-construct could not be called * @throws PostConstructException in case the post-construct method has thrown an exception itself * @throws ValidationException in case validation could not be performed for some reason (e.g. no validation information available) * @throws InvalidModelException in case the given model type could not be validated through the model validation */ public @Nonnull <ModelType> ModelType createModel(@Nonnull Object adaptable, @Nonnull Class<ModelType> type) throws MissingElementsException, InvalidAdaptableException, ModelClassException, PostConstructException, ValidationException, InvalidModelException; /** * * @param adaptable the adaptable to check * @param type the class to check * @return {@code true} in case the given class can be created from the given adaptable, otherwise {@code false} */ public boolean canCreateFromAdaptable(@Nonnull Object adaptable, @Nonnull Class<?> type); /** * * @param adaptable the adaptable to check * @param type the class to check * @return false in case no class with the Model annotation adapts to the requested type * * @see org.apache.sling.models.annotations.Model * @deprecated Use {@link #isModelClass(Class)} instead! */ @Deprecated public boolean isModelClass(@Nonnull Object adaptable, @Nonnull Class<?> type); /** * Checks if a given type can be instantiated though Sling Models. This checks that * <ul> * <li>there is a class annotated with <code>Model</code> which adapts to the given type</li> * <li>this class is registered as Sling Model (i.e. the package is listed in the "Sling-Model-Packages" header from the bundles manifest and has been picked up already by the bundle listener)</li> * </ul> * Only if both conditions are fulfilled this method will return {@code true}. * @param type the class to check * @return {@code true} in case the given type can be instantiated though Sling Models. * */ public boolean isModelClass(@Nonnull Class<?> type); /** * Determine is a model class is available for the resource's resource type. * * @param resource a resource * @return {@code true} if a model class is mapped to the resource type */ public boolean isModelAvailableForResource(@Nonnull Resource resource); /** * Determine is a model class is available for the request's resource's resource type. * * @param request a request * @return {@code true} if a model class is mapped to the resource type */ public boolean isModelAvailableForRequest(@Nonnull SlingHttpServletRequest request); /** * Obtain an adapted model class based on the resource type of the provided resource. * * @param resource a resource * @return an adapted model object * @throws MissingElementsException in case no injector was able to inject some required values with the given types * @throws InvalidAdaptableException in case the given class cannot be instantiated from the given adaptable (different adaptable on the model annotation) * @throws ModelClassException in case the model could not be instantiated because model annotation was missing, reflection failed, no valid constructor was found, model was not registered as adapter factory yet, or post-construct could not be called * @throws PostConstructException in case the post-construct method has thrown an exception itself * @throws ValidationException in case validation could not be performed for some reason (e.g. no validation information available) * @throws InvalidModelException in case the given model type could not be validated through the model validation */ public Object getModelFromResource(@Nonnull Resource resource) throws MissingElementsException, InvalidAdaptableException, ModelClassException, PostConstructException, ValidationException, InvalidModelException; /** * Obtain an adapted model class based on the resource type of the request's resource. * * @param request a request * @return an adapted model object * @throws MissingElementsException in case no injector was able to inject some required values with the given types * @throws InvalidAdaptableException in case the given class cannot be instantiated from the given adaptable (different adaptable on the model annotation) * @throws ModelClassException in case the model could not be instantiated because model annotation was missing, reflection failed, no valid constructor was found, model was not registered as adapter factory yet, or post-construct could not be called * @throws PostConstructException in case the post-construct method has thrown an exception itself * @throws ValidationException in case validation could not be performed for some reason (e.g. no validation information available) * @throws InvalidModelException in case the given model type could not be validated through the model validation */ public Object getModelFromRequest(@Nonnull SlingHttpServletRequest request) throws MissingElementsException, InvalidAdaptableException, ModelClassException, PostConstructException, ValidationException, InvalidModelException; /** * Export the model object using the defined target class using the named exporter. * * @param model the model object * @param exporterName the exporter name * @param targetClass the target class * @param options any exporter options * @param <T> the target class * @return an instance of the target class * @throws ExportException if the export fails * @throws MissingExporterException if the named exporter can't be found */ public <T> T exportModel(Object model, String exporterName, Class<T> targetClass, Map<String, String> options) throws ExportException, MissingExporterException; /** * Export the model object registered to the resource's type using the defined target class using the named exporter. * * @param resource the resource * @param exporterName the exporter name * @param targetClass the target class * @param options any exporter options * @param <T> the target class * @return an instance of the target class * @throws MissingElementsException in case no injector was able to inject some required values with the given types * @throws InvalidAdaptableException in case the given class cannot be instantiated from the given adaptable (different adaptable on the model annotation) * @throws ModelClassException in case the model could not be instantiated because model annotation was missing, reflection failed, no valid constructor was found, model was not registered as adapter factory yet, or post-construct could not be called * @throws PostConstructException in case the post-construct method has thrown an exception itself * @throws ValidationException in case validation could not be performed for some reason (e.g. no validation information available) * @throws InvalidModelException in case the given model type could not be validated through the model validation * @throws ExportException if the export fails * @throws MissingExporterException if the named exporter can't be found */ public <T> T exportModelForResource(Resource resource, String exporterName, Class<T> targetClass, Map<String, String> options) throws MissingElementsException, InvalidAdaptableException, ModelClassException, PostConstructException, ValidationException, InvalidModelException, ExportException, MissingExporterException; /** * Export the model object registered to the request's resource's type using the defined target class using the named exporter. * * @param request the request * @param exporterName the exporter name * @param targetClass the target class * @param options any exporter options * @param <T> the target class * @return an instance of the target class * @throws MissingElementsException in case no injector was able to inject some required values with the given types * @throws InvalidAdaptableException in case the given class cannot be instantiated from the given adaptable (different adaptable on the model annotation) * @throws ModelClassException in case the model could not be instantiated because model annotation was missing, reflection failed, no valid constructor was found, model was not registered as adapter factory yet, or post-construct could not be called * @throws PostConstructException in case the post-construct method has thrown an exception itself * @throws ValidationException in case validation could not be performed for some reason (e.g. no validation information available) * @throws InvalidModelException in case the given model type could not be validated through the model validation * @throws ExportException if the export fails * @throws MissingExporterException if the named exporter can't be found */ public <T> T exportModelForRequest(SlingHttpServletRequest request, String exporterName, Class<T> targetClass, Map<String, String> options) throws MissingElementsException, InvalidAdaptableException, ModelClassException, PostConstructException, ValidationException, InvalidModelException, ExportException, MissingExporterException; }
apache-2.0
tuoshao/floodlight-ratelimiter
src/main/java/net/floodlightcontroller/loadbalancer/LBVipSerializer.java
1592
/** * Copyright 2013, Big Switch Networks, 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 net.floodlightcontroller.loadbalancer; import java.io.IOException; import org.codehaus.jackson.JsonGenerator; import org.codehaus.jackson.JsonProcessingException; import org.codehaus.jackson.map.JsonSerializer; import org.codehaus.jackson.map.SerializerProvider; public class LBVipSerializer extends JsonSerializer<LBVip>{ @Override public void serialize(LBVip vip, JsonGenerator jGen, SerializerProvider serializer) throws IOException, JsonProcessingException { jGen.writeStartObject(); jGen.writeStringField("name", vip.name); jGen.writeStringField("id", vip.id); jGen.writeStringField("address", String.valueOf(vip.address)); jGen.writeStringField("protocol", Byte.toString(vip.protocol)); jGen.writeStringField("port", Short.toString(vip.port)); jGen.writeEndObject(); } }
apache-2.0
lsinfo3/onos
core/api/src/main/java/org/onosproject/ui/chart/ChartRequestHandler.java
3407
/* * Copyright 2016-present Open Networking Laboratory * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onosproject.ui.chart; import com.fasterxml.jackson.databind.node.ObjectNode; import org.onosproject.ui.RequestHandler; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * Message handler specifically for the chart views. */ public abstract class ChartRequestHandler extends RequestHandler { private final String respType; private final String nodeName; protected static final String LABEL = "label"; private static final String ANNOTS = "annots"; /** * Constructs a chart model handler for a specific graph view. When chart * requests come in, the handler will generate the appropriate chart data * points and send back the response to the client. * * @param reqType type of the request event * @param respType type of the response event * @param nodeName name of JSON node holding data point */ public ChartRequestHandler(String reqType, String respType, String nodeName) { super(reqType); this.respType = respType; this.nodeName = nodeName; } @Override public void process(long sid, ObjectNode payload) { ChartModel cm = createChartModel(); populateChart(cm, payload); ObjectNode rootNode = MAPPER.createObjectNode(); rootNode.set(nodeName, ChartUtils.generateDataPointArrayNode(cm)); rootNode.set(ANNOTS, ChartUtils.generateAnnotObjectNode(cm)); sendMessage(respType, 0, rootNode); } /** * Creates the chart model using {@link #getSeries()} * to initialize it, ready to be populated. * <p> * This default implementation returns a chart model for all series. * </p> * * @return an empty chart model */ protected ChartModel createChartModel() { List<String> series = new ArrayList<>(); series.addAll(Arrays.asList(getSeries())); series.add(LABEL); String[] seiresArray = new String[series.size()]; return new ChartModel(series.toArray(seiresArray)); } /** * Subclasses should return the array of series with which to initialize * their chart model. * * @return the series name */ protected abstract String[] getSeries(); /** * Subclasses should populate the chart model by adding * {@link ChartModel.DataPoint datapoints}. * <pre> * cm.addDataPoint() * .data(SERIES_ONE, ...) * .data(SERIES_TWO, ...) * ... ; * </pre> * The request payload is provided in case there are request filtering * parameters. * * @param cm the chart model * @param payload request payload */ protected abstract void populateChart(ChartModel cm, ObjectNode payload); }
apache-2.0
wangcy6/storm_app
frame/java/netty-4.1/codec-http2/src/main/java/io/netty/handler/codec/http2/DefaultHttp2SettingsFrame.java
1431
/* * 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: * * 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.netty.handler.codec.http2; import io.netty.util.internal.ObjectUtil; import io.netty.util.internal.StringUtil; import io.netty.util.internal.UnstableApi; /** * The default {@link Http2SettingsFrame} implementation. */ @UnstableApi public class DefaultHttp2SettingsFrame implements Http2SettingsFrame { private final Http2Settings settings; public DefaultHttp2SettingsFrame(Http2Settings settings) { this.settings = ObjectUtil.checkNotNull(settings, "settings"); } @Override public Http2Settings settings() { return settings; } @Override public String name() { return "SETTINGS"; } @Override public String toString() { return StringUtil.simpleClassName(this) + "(settings=" + settings + ')'; } }
apache-2.0
WangTaoTheTonic/flink
flink-java/src/main/java/org/apache/flink/api/java/summarize/aggregation/IntegerSummaryAggregator.java
3029
/* * 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.api.java.summarize.aggregation; import org.apache.flink.annotation.Internal; /** * Aggregator that can handle Integer types */ @Internal public class IntegerSummaryAggregator extends NumericSummaryAggregator<Integer> { private static final long serialVersionUID = 1L; // Nested classes are only "public static" for Kryo serialization, otherwise they'd be private public static class MinIntegerAggregator implements Aggregator<Integer,Integer> { private int min = Integer.MAX_VALUE; @Override public void aggregate(Integer value) { min = Math.min(min, value); } @Override public void combine(Aggregator<Integer, Integer> other) { min = Math.min(min,((MinIntegerAggregator)other).min); } @Override public Integer result() { return min; } } public static class MaxIntegerAggregator implements Aggregator<Integer,Integer> { private int max = Integer.MIN_VALUE; @Override public void aggregate(Integer value) { max = Math.max(max, value); } @Override public void combine(Aggregator<Integer, Integer> other) { max = Math.max(max, ((MaxIntegerAggregator) other).max); } @Override public Integer result() { return max; } } public static class SumIntegerAggregator implements Aggregator<Integer,Integer> { private int sum = 0; @Override public void aggregate(Integer value) { sum += value; } @Override public void combine(Aggregator<Integer, Integer> other) { sum += ((SumIntegerAggregator)other).sum; } @Override public Integer result() { return sum; } } @Override protected Aggregator<Integer, Integer> initMin() { return new MinIntegerAggregator(); } @Override protected Aggregator<Integer, Integer> initMax() { return new MaxIntegerAggregator(); } @Override protected Aggregator<Integer, Integer> initSum() { return new SumIntegerAggregator(); } @Override protected boolean isNan(Integer number) { // NaN never applies here because only types like Float and Double have NaN return false; } @Override protected boolean isInfinite(Integer number) { // Infinity never applies here because only types like Float and Double have Infinity return false; } }
apache-2.0
greg-dove/flex-falcon
flex-compiler-oem/src/main/java/flex2/compiler/config/ConfigurationValue.java
2791
/* * * 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 flex2.compiler.config; import java.util.List; import java.util.LinkedList; /** * This class represents an instance of a configuration option. For * example, "-debug=true". * * @author Roger Gonzalez */ public class ConfigurationValue { protected ConfigurationValue( ConfigurationBuffer buffer, String var, List<String> args, String source, int line, String context ) { this.buffer = buffer; this.var = var; this.args = new LinkedList<String>( args ); this.source = source; this.line = line; this.context = context; } /** * getArgs * * @return list of values provided, in schema order */ public final List<String> getArgs() { return args; } /** * getBuffer * * @return a handle to the associated buffer holding this value */ public final ConfigurationBuffer getBuffer() { return buffer; } /** * getSource * * @return a string representing the origin of this value, or null if unknown */ public final String getSource() { return source; } /** * getLine * * @return the line number of the origin of this value, or -1 if unknown */ public final int getLine() { return line; } /** * getVar * * @return the full name of this configuration variable in the hierarchy */ public final String getVar() { return var; } /** * getContext * * @return the path of the enclosing context where the variable was set * (i.e. the directory where the config file was found) */ public final String getContext() { return context; } private final ConfigurationBuffer buffer; private final String var; private final List<String> args; private final String source; private final int line; private final String context; }
apache-2.0
zogwei/diamond-dsp
diamond/diamond-client/src/main/java/com/taobao/diamond/client/processor/SnapshotConfigInfoProcessor.java
4679
/* * (C) 2007-2012 Alibaba Group Holding Limited. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * Authors: * leiwen <chrisredfield1985@126.com> , boyan <killme2008@gmail.com> */ package com.taobao.diamond.client.processor; import java.io.BufferedOutputStream; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintWriter; import org.apache.commons.lang.StringUtils; import com.taobao.diamond.common.Constants; public class SnapshotConfigInfoProcessor { private final String dir; public SnapshotConfigInfoProcessor(String dir) { super(); this.dir = dir; File file = new File(this.dir); if (!file.exists()) { file.mkdir(); } } public String getConfigInfomation(String dataId, String group) throws IOException { if (StringUtils.isBlank(dataId)) { return null; } if (StringUtils.isBlank(group)) { return null; } String path = dir + File.separator + group; final File dir = new File(path); if (!dir.exists()) { return null; } String filePath = path + File.separator + dataId; final File file = new File(filePath); if (!file.exists()) { return null; } FileInputStream in = null; StringBuilder sb = new StringBuilder(512); try { in = new FileInputStream(file); byte[] data = new byte[8192]; int n = -1; while ((n = in.read(data)) != -1) { sb.append(new String(data, 0, n, Constants.ENCODE)); } return sb.toString(); } finally { if (in != null) { in.close(); } } } /** * ±£´æsnapshot * * @param dataId * @param group * @param config * @throws IOException */ public void saveSnaptshot(String dataId, String group, String config) throws IOException { if (StringUtils.isBlank(dataId)) { throw new IllegalArgumentException("blank dataId"); } if (StringUtils.isBlank(group)) { throw new IllegalArgumentException("blank group"); } if (config == null) { config = ""; } File file = getTargetFile(dataId, group); FileOutputStream out = null; PrintWriter writer = null; try { out = new FileOutputStream(file); BufferedOutputStream stream = new BufferedOutputStream(out); writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(stream, Constants.ENCODE))); writer.write(config); writer.flush(); } finally { if (writer != null) writer.close(); if (out != null) { out.close(); } } } /** * ɾ³ýsnapshot * * @param dataId * @param group */ public void removeSnapshot(String dataId, String group) { if (StringUtils.isBlank(dataId)) { return; } if (StringUtils.isBlank(group)) { return; } String path = dir + File.separator + group; final File dir = new File(path); if (!dir.exists()) { return; } String filePath = path + File.separator + dataId; final File file = new File(filePath); if (!file.exists()) { return; } file.delete(); // Èç¹ûĿ¼ûÓÐÎļþÁË£¬É¾³ýĿ¼ String[] list = dir.list(); if (list == null || list.length == 0) { dir.delete(); } } private File getTargetFile(String dataId, String group) throws IOException { String path = dir + File.separator + group; createDirIfNessary(path); String filePath = path + File.separator + dataId; File file = createFileIfNessary(filePath); return file; } private void createDirIfNessary(String path) { final File dir = new File(path); if (!dir.exists()) { dir.mkdir(); } } private File createFileIfNessary(String path) throws IOException { final File file = new File(path); if (!file.exists()) { file.createNewFile(); } return file; } }
apache-2.0
WilliamNouet/nifi
nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-framework-cluster/src/main/java/org/apache/nifi/cluster/coordination/http/endpoints/FunnelsEndpointMerger.java
3449
/* * 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.cluster.coordination.http.endpoints; import org.apache.nifi.cluster.coordination.http.EndpointResponseMerger; import org.apache.nifi.cluster.manager.FunnelsEntityMerger; import org.apache.nifi.cluster.manager.NodeResponse; import org.apache.nifi.cluster.protocol.NodeIdentifier; import org.apache.nifi.web.api.entity.FunnelEntity; import org.apache.nifi.web.api.entity.FunnelsEntity; import java.net.URI; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.regex.Pattern; public class FunnelsEndpointMerger implements EndpointResponseMerger { public static final Pattern FUNNELS_URI_PATTERN = Pattern.compile("/nifi-api/process-groups/(?:(?:root)|(?:[a-f0-9\\-]{36}))/funnels"); @Override public boolean canHandle(URI uri, String method) { return "GET".equalsIgnoreCase(method) && FUNNELS_URI_PATTERN.matcher(uri.getPath()).matches(); } @Override public NodeResponse merge(URI uri, String method, Set<NodeResponse> successfulResponses, Set<NodeResponse> problematicResponses, NodeResponse clientResponse) { if (!canHandle(uri, method)) { throw new IllegalArgumentException("Cannot use Endpoint Mapper of type " + getClass().getSimpleName() + " to map responses for URI " + uri + ", HTTP Method " + method); } final FunnelsEntity responseEntity = clientResponse.getClientResponse().getEntity(FunnelsEntity.class); final Set<FunnelEntity> funnelEntities = responseEntity.getFunnels(); final Map<String, Map<NodeIdentifier, FunnelEntity>> entityMap = new HashMap<>(); for (final NodeResponse nodeResponse : successfulResponses) { final FunnelsEntity nodeResponseEntity = nodeResponse == clientResponse ? responseEntity : nodeResponse.getClientResponse().getEntity(FunnelsEntity.class); final Set<FunnelEntity> nodeFunnelEntities = nodeResponseEntity.getFunnels(); for (final FunnelEntity nodeFunnelEntity : nodeFunnelEntities) { final String nodeFunnelEntityId = nodeFunnelEntity.getId(); Map<NodeIdentifier, FunnelEntity> innerMap = entityMap.get(nodeFunnelEntityId); if (innerMap == null) { innerMap = new HashMap<>(); entityMap.put(nodeFunnelEntityId, innerMap); } innerMap.put(nodeResponse.getNodeId(), nodeFunnelEntity); } } FunnelsEntityMerger.mergeFunnels(funnelEntities, entityMap); // create a new client response return new NodeResponse(clientResponse, responseEntity); } }
apache-2.0
pleacu/jbpm
jbpm-services/jbpm-kie-services/src/test/java/org/jbpm/kie/services/test/RuntimeManagerIdentifierFilterTest.java
5642
/* * 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. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jbpm.kie.services.test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.ServiceLoader; import org.jbpm.kie.services.api.DeploymentIdResolver; import org.jbpm.runtime.manager.impl.filter.RegExRuntimeManagerIdFilter; import org.junit.Test; import org.kie.internal.runtime.manager.RuntimeManagerIdFilter; public class RuntimeManagerIdentifierFilterTest { private static final ServiceLoader<RuntimeManagerIdFilter> runtimeManagerIdFilters = ServiceLoader.load(RuntimeManagerIdFilter.class); @Test public void testNumberOfFilterImplementationsFound() { assertNotNull(runtimeManagerIdFilters); List<String> collected = new ArrayList<String>(); for (RuntimeManagerIdFilter filter : runtimeManagerIdFilters) { collected.add(filter.getClass().getName()); } assertEquals(2, collected.size()); assertTrue(collected.contains(RegExRuntimeManagerIdFilter.class.getName())); assertTrue(collected.contains(DeploymentIdResolver.class.getName())); } @Test public void testGAVFilteringLatest() { assertNotNull(runtimeManagerIdFilters); Collection<String> input = new ArrayList<String>(); input.add("org.jbpm:test:2.0"); input.add("org.jbpm:test:1.0"); input.add("org.jbpm:another:1.0"); ArrayList<String> collected = new ArrayList<String>(); String pattern = "org.jbpm:test:latest"; for (RuntimeManagerIdFilter filter : runtimeManagerIdFilters) { collected.addAll(filter.filter(pattern, input)); } assertEquals(1, collected.size()); assertEquals("org.jbpm:test:2.0", collected.get(0)); } @Test public void testRegExFilteringAll() { assertNotNull(runtimeManagerIdFilters); ArrayList<String> input = new ArrayList<String>(); input.add("org.jbpm:test:2.0"); input.add("org.jbpm:test:1.0"); input.add("org.jbpm:another:1.0"); ArrayList<String> collected = new ArrayList<String>(); String pattern = ".*"; for (RuntimeManagerIdFilter filter : runtimeManagerIdFilters) { collected.addAll(filter.filter(pattern, input)); } assertEquals(3, collected.size()); assertTrue(collected.contains(input.get(0))); assertTrue(collected.contains(input.get(1))); assertTrue(collected.contains(input.get(2))); } @Test public void testRegExFilteringAllVersions() { assertNotNull(runtimeManagerIdFilters); ArrayList<String> input = new ArrayList<String>(); input.add("org.jbpm:test:2.0"); input.add("org.jbpm:test:1.0"); input.add("org.jbpm:another:1.0"); ArrayList<String> collected = new ArrayList<String>(); String pattern = "org.jbpm:test:.*"; for (RuntimeManagerIdFilter filter : runtimeManagerIdFilters) { collected.addAll(filter.filter(pattern, input)); } assertEquals(2, collected.size()); assertTrue(collected.contains(input.get(0))); assertTrue(collected.contains(input.get(1))); } @Test public void testRegExFilteringAllArtifactsAndVersions() { assertNotNull(runtimeManagerIdFilters); ArrayList<String> input = new ArrayList<String>(); input.add("org.jbpm:test:2.0"); input.add("org.jbpm:test:1.0"); input.add("org.jbpm:another:1.0"); ArrayList<String> collected = new ArrayList<String>(); String pattern = "org.jbpm:.*"; for (RuntimeManagerIdFilter filter : runtimeManagerIdFilters) { collected.addAll(filter.filter(pattern, input)); } assertEquals(3, collected.size()); assertTrue(collected.contains(input.get(0))); assertTrue(collected.contains(input.get(1))); assertTrue(collected.contains(input.get(2))); } @Test public void testRegExFilteringAllArtifactsWithGivenVersions() { assertNotNull(runtimeManagerIdFilters); ArrayList<String> input = new ArrayList<String>(); input.add("org.jbpm:test:2.0"); input.add("org.jbpm:test:1.0"); input.add("org.jbpm:another:1.0"); ArrayList<String> collected = new ArrayList<String>(); String pattern = "org.jbpm:.*:1.0"; for (RuntimeManagerIdFilter filter : runtimeManagerIdFilters) { collected.addAll(filter.filter(pattern, input)); } assertEquals(2, collected.size()); assertTrue(collected.contains(input.get(1))); assertTrue(collected.contains(input.get(2))); } }
apache-2.0
nikhilvibhav/camel
components/camel-google/camel-google-mail/src/main/java/org/apache/camel/component/google/mail/stream/GoogleMailStreamComponentVerifierExtension.java
3856
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.google.mail.stream; import java.util.Map; import com.google.api.services.gmail.Gmail; import org.apache.camel.component.extension.verifier.DefaultComponentVerifierExtension; import org.apache.camel.component.extension.verifier.ResultBuilder; import org.apache.camel.component.extension.verifier.ResultErrorBuilder; import org.apache.camel.component.extension.verifier.ResultErrorHelper; import org.apache.camel.component.google.mail.BatchGoogleMailClientFactory; import org.apache.camel.component.google.mail.GoogleMailClientFactory; import org.apache.camel.component.google.mail.GoogleMailConfiguration; public class GoogleMailStreamComponentVerifierExtension extends DefaultComponentVerifierExtension { public GoogleMailStreamComponentVerifierExtension() { this("google-mail-stream"); } public GoogleMailStreamComponentVerifierExtension(String scheme) { super(scheme); } // ********************************* // Parameters validation // ********************************* @Override protected Result verifyParameters(Map<String, Object> parameters) { ResultBuilder builder = ResultBuilder.withStatusAndScope(Result.Status.OK, Scope.PARAMETERS) .error(ResultErrorHelper.requiresOption("applicationName", parameters)) .error(ResultErrorHelper.requiresOption("clientId", parameters)) .error(ResultErrorHelper.requiresOption("clientSecret", parameters)); return builder.build(); } // ********************************* // Connectivity validation // ********************************* @Override @SuppressWarnings("PMD.AvoidCatchingGenericException") protected Result verifyConnectivity(Map<String, Object> parameters) { ResultBuilder builder = ResultBuilder.withStatusAndScope(Result.Status.OK, Scope.CONNECTIVITY); try { GoogleMailConfiguration configuration = setProperties(new GoogleMailConfiguration(), parameters); GoogleMailClientFactory clientFactory = new BatchGoogleMailClientFactory(); Gmail client = clientFactory.makeClient(configuration.getClientId(), configuration.getClientSecret(), configuration.getApplicationName(), configuration.getRefreshToken(), configuration.getAccessToken()); client.users().getProfile((String) parameters.get("userId")).execute(); } catch (Exception e) { ResultErrorBuilder errorBuilder = ResultErrorBuilder.withCodeAndDescription(VerificationError.StandardCode.AUTHENTICATION, e.getMessage()) .detail("gmail_exception_message", e.getMessage()) .detail(VerificationError.ExceptionAttribute.EXCEPTION_CLASS, e.getClass().getName()) .detail(VerificationError.ExceptionAttribute.EXCEPTION_INSTANCE, e); builder.error(errorBuilder.build()); } return builder.build(); } }
apache-2.0
tubemogul/druid
processing/src/test/java/io/druid/query/search/SearchQueryRunnerWithCaseTest.java
8353
/* * Licensed to Metamarkets Group Inc. (Metamarkets) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. Metamarkets 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.druid.query.search; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.google.common.io.CharSource; import com.metamx.common.guava.Sequences; import io.druid.query.Druids; import io.druid.query.QueryRunner; import io.druid.query.Result; import io.druid.query.search.search.SearchHit; import io.druid.query.search.search.SearchQuery; import io.druid.query.search.search.SearchQueryConfig; import io.druid.segment.IncrementalIndexSegment; import io.druid.segment.QueryableIndex; import io.druid.segment.QueryableIndexSegment; import io.druid.segment.TestIndex; import io.druid.segment.incremental.IncrementalIndex; import org.joda.time.DateTime; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.io.IOException; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import static io.druid.query.QueryRunnerTestHelper.NOOP_QUERYWATCHER; import static io.druid.query.QueryRunnerTestHelper.NoopIntervalChunkingQueryRunnerDecorator; import static io.druid.query.QueryRunnerTestHelper.allGran; import static io.druid.query.QueryRunnerTestHelper.dataSource; import static io.druid.query.QueryRunnerTestHelper.fullOnInterval; import static io.druid.query.QueryRunnerTestHelper.makeQueryRunner; import static io.druid.query.QueryRunnerTestHelper.marketDimension; import static io.druid.query.QueryRunnerTestHelper.placementDimension; import static io.druid.query.QueryRunnerTestHelper.placementishDimension; import static io.druid.query.QueryRunnerTestHelper.qualityDimension; import static io.druid.query.QueryRunnerTestHelper.transformToConstructionFeeder; /** */ @RunWith(Parameterized.class) public class SearchQueryRunnerWithCaseTest { @Parameterized.Parameters public static Iterable<Object[]> constructorFeeder() throws IOException { SearchQueryRunnerFactory factory = new SearchQueryRunnerFactory( new SearchQueryQueryToolChest( new SearchQueryConfig(), NoopIntervalChunkingQueryRunnerDecorator() ), NOOP_QUERYWATCHER ); CharSource input = CharSource.wrap( "2011-01-12T00:00:00.000Z\tspot\tAutoMotive\tPREFERRED\ta\u0001preferred\t100.000000\n" + "2011-01-12T00:00:00.000Z\tSPot\tbusiness\tpreferred\tb\u0001Preferred\t100.000000\n" + "2011-01-12T00:00:00.000Z\tspot\tentertainment\tPREFERRed\te\u0001preferred\t100.000000\n" + "2011-01-13T00:00:00.000Z\tspot\tautomotive\tpreferred\ta\u0001preferred\t94.874713" ); IncrementalIndex index1 = TestIndex.makeRealtimeIndex(input); IncrementalIndex index2 = TestIndex.makeRealtimeIndex(input); QueryableIndex index3 = TestIndex.persistRealtimeAndLoadMMapped(index1); QueryableIndex index4 = TestIndex.persistRealtimeAndLoadMMapped(index2); return transformToConstructionFeeder( Arrays.asList( makeQueryRunner(factory, "index1", new IncrementalIndexSegment(index1, "index1")), makeQueryRunner(factory, "index2", new IncrementalIndexSegment(index2, "index2")), makeQueryRunner(factory, "index3", new QueryableIndexSegment("index3", index3)), makeQueryRunner(factory, "index4", new QueryableIndexSegment("index4", index4)) ) ); } private final QueryRunner runner; public SearchQueryRunnerWithCaseTest( QueryRunner runner ) { this.runner = runner; } private Druids.SearchQueryBuilder testBuilder() { return Druids.newSearchQueryBuilder() .dataSource(dataSource) .granularity(allGran) .intervals(fullOnInterval); } @Test public void testSearch() { Druids.SearchQueryBuilder builder = testBuilder(); Map<String, Set<String>> expectedResults = Maps.newTreeMap(String.CASE_INSENSITIVE_ORDER); SearchQuery searchQuery; searchQuery = builder.query("SPOT").build(); expectedResults.put(marketDimension, Sets.newHashSet("spot", "SPot")); checkSearchQuery(searchQuery, expectedResults); searchQuery = builder.query("spot", true).build(); expectedResults.put(marketDimension, Sets.newHashSet("spot")); checkSearchQuery(searchQuery, expectedResults); searchQuery = builder.query("SPot", true).build(); expectedResults.put(marketDimension, Sets.newHashSet("SPot")); checkSearchQuery(searchQuery, expectedResults); } @Test public void testSearchSameValueInMultiDims() { SearchQuery searchQuery; Druids.SearchQueryBuilder builder = testBuilder() .dimensions(Arrays.asList(placementDimension, placementishDimension)); Map<String, Set<String>> expectedResults = Maps.newTreeMap(String.CASE_INSENSITIVE_ORDER); searchQuery = builder.query("PREFERRED").build(); expectedResults.put(placementDimension, Sets.newHashSet("PREFERRED", "preferred", "PREFERRed")); expectedResults.put(placementishDimension, Sets.newHashSet("preferred", "Preferred")); checkSearchQuery(searchQuery, expectedResults); searchQuery = builder.query("preferred", true).build(); expectedResults.put(placementDimension, Sets.newHashSet("preferred")); expectedResults.put(placementishDimension, Sets.newHashSet("preferred")); checkSearchQuery(searchQuery, expectedResults); } @Test public void testFragmentSearch() { Druids.SearchQueryBuilder builder = testBuilder(); Map<String, Set<String>> expectedResults = Maps.newTreeMap(String.CASE_INSENSITIVE_ORDER); SearchQuery searchQuery; searchQuery = builder.fragments(Arrays.asList("auto", "ve")).build(); expectedResults.put(qualityDimension, Sets.newHashSet("automotive", "AutoMotive")); checkSearchQuery(searchQuery, expectedResults); searchQuery = builder.fragments(Arrays.asList("auto", "ve"), true).build(); expectedResults.put(qualityDimension, Sets.newHashSet("automotive")); checkSearchQuery(searchQuery, expectedResults); } private void checkSearchQuery(SearchQuery searchQuery, Map<String, Set<String>> expectedResults) { HashMap<String, List> context = new HashMap<>(); Iterable<Result<SearchResultValue>> results = Sequences.toList( runner.run(searchQuery, context), Lists.<Result<SearchResultValue>>newArrayList() ); for (Result<SearchResultValue> result : results) { Assert.assertEquals(new DateTime("2011-01-12T00:00:00.000Z"), result.getTimestamp()); Assert.assertNotNull(result.getValue()); Iterable<SearchHit> resultValues = result.getValue(); for (SearchHit resultValue : resultValues) { String dimension = resultValue.getDimension(); String theValue = resultValue.getValue(); Assert.assertTrue( String.format("Result had unknown dimension[%s]", dimension), expectedResults.containsKey(dimension) ); Set<String> expectedSet = expectedResults.get(dimension); Assert.assertTrue( String.format("Couldn't remove dim[%s], value[%s]", dimension, theValue), expectedSet.remove(theValue) ); } } for (Map.Entry<String, Set<String>> entry : expectedResults.entrySet()) { Assert.assertTrue( String.format( "Dimension[%s] should have had everything removed, still has[%s]", entry.getKey(), entry.getValue() ), entry.getValue().isEmpty() ); } expectedResults.clear(); } }
apache-2.0
shakamunyi/hadoop-20
src/contrib/mumak/src/test/org/apache/hadoop/mapred/CheckedEventQueue.java
8266
/** * 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.mapred; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.SortedMap; import java.util.TreeMap; import junit.framework.Assert; import org.apache.hadoop.mapred.TaskStatus.State; import org.apache.hadoop.mapred.TaskStatus.Phase; import org.apache.hadoop.mapreduce.TaskAttemptID; /** * An EventQueue that checks events against a list of expected events upon * enqueueing. Also contains routines for creating expected HeartbeatEvents and * all expected events related to running map or reduce tasks on a task tracker. */ class CheckedEventQueue extends SimulatorEventQueue { /** * expected list of events to be returned from all EventListener.accept() * called at time t, t is the key if no events are generated an empty list * needs to be put there * * IMPORTANT: this is NOT the events to be delivered at time t from the event * queue, it is the list events to be inserted into the event queue at time t */ private SortedMap<Long, List<SimulatorEvent>> expectedEvents = new TreeMap<Long, List<SimulatorEvent>>(); // current simulation time private long now; private long simulationStartTime; /** * We need the simulation start time so that we know the time of the first * add(). * * @param simulationStartTime * Simulation start time. */ public CheckedEventQueue(long simulationStartTime) { now = simulationStartTime; this.simulationStartTime = simulationStartTime; } void check(SimulatorEvent event) { for (Iterator<Map.Entry<Long, List<SimulatorEvent>>> it = expectedEvents.entrySet() .iterator(); it.hasNext();) { Map.Entry<Long, List<SimulatorEvent>> entry = it.next(); long insertTime = entry.getKey(); Assert.assertTrue(insertTime <= now); if (insertTime < now) { List<SimulatorEvent> events = entry.getValue(); if (!events.isEmpty()) { Assert.fail("There are " + events.size() + " events at time " + insertTime + " before " + now + ". First event: "+events.get(0)); } it.remove(); } else { // insertTime == now break; } } List<SimulatorEvent> expected = expectedEvents.get(now); boolean found = false; for (SimulatorEvent ee : expected) { if (isSameEvent(ee, event)) { expected.remove(ee); found = true; break; } } Assert.assertTrue("Unexpected event to enqueue, now=" + now + ", event=" + event + ", expecting=" + expected, found); } /** * We intercept the main routine of the real EventQueue and check the new * event returned by accept() against the expectedEvents table */ @Override public boolean add(SimulatorEvent event) { check(event); return super.add(event); } @Override public boolean addAll(Collection<? extends SimulatorEvent> events) { for (SimulatorEvent event : events) { check(event); } return super.addAll(events); } // We need to override get() to track the current simulation time @Override public SimulatorEvent get() { SimulatorEvent ret = super.get(); if (ret != null) { now = ret.getTimeStamp(); } return ret; } /** * Auxiliary function for populating the expectedEvents table If event is null * then just marks that an accept happens at time 'when', and the list of new * events is empty */ public void addExpected(long when, SimulatorEvent event) { Assert.assertNotNull(event); List<SimulatorEvent> expected = expectedEvents.get(when); if (expected == null) { expected = new ArrayList<SimulatorEvent>(); expectedEvents.put(when, expected); } expected.add(event); } public long getLastCheckTime() { return expectedEvents.lastKey(); } // there should be an empty expected event list left for the last // time to check public void checkMissingExpected() { Assert.assertTrue(expectedEvents.size() <= 1); for (List<SimulatorEvent> events : expectedEvents.values()) { Assert.assertTrue(events.isEmpty()); } } // fills in the expected events corresponding to the execution of a map task public void expectMapTask(SimulatorTaskTracker taskTracker, TaskAttemptID taskId, long mapStart, long mapRuntime) { long mapDone = mapStart + mapRuntime; org.apache.hadoop.mapred.TaskAttemptID taskIdOldApi = org.apache.hadoop.mapred.TaskAttemptID.downgrade(taskId); MapTaskStatus status = new MapTaskStatus(taskIdOldApi, 1.0f, 1, State.SUCCEEDED, null, null, null, Phase.MAP, null); status.setFinishTime(mapDone); TaskAttemptCompletionEvent completionEvent = new TaskAttemptCompletionEvent(taskTracker, status); addExpected(mapStart, completionEvent); } // fills in the expected events corresponding to the execution of a reduce // task public void expectReduceTask(SimulatorTaskTracker taskTracker, TaskAttemptID taskId, long mapDone, long reduceRuntime) { long reduceDone = mapDone + reduceRuntime; org.apache.hadoop.mapred.TaskAttemptID taskIdOldApi = org.apache.hadoop.mapred.TaskAttemptID.downgrade(taskId); ReduceTaskStatus status = new ReduceTaskStatus(taskIdOldApi, 1.0f, 1, State.SUCCEEDED, null, null, null, Phase.REDUCE, null); status.setFinishTime(reduceDone); TaskAttemptCompletionEvent completionEvent = new TaskAttemptCompletionEvent(taskTracker, status); addExpected(mapDone, completionEvent); } /** * Fills in the events corresponding to the self heartbeats numAccepts is the * number of times accept() will be called, it must be >= 1 */ public void expectHeartbeats(SimulatorTaskTracker taskTracker, int numAccepts, int heartbeatInterval) { // initial heartbeat addExpected(simulationStartTime, new HeartbeatEvent(taskTracker, simulationStartTime)); long simulationTime = simulationStartTime; for(int i=0; i<numAccepts; i++) { long heartbeatTime = simulationTime + heartbeatInterval; HeartbeatEvent he = new HeartbeatEvent(taskTracker, heartbeatTime); addExpected(simulationTime, he); simulationTime = heartbeatTime; } } /** * Returns true iff two events are the same. We did not use equals() because * we may want to test for partial equality only, and we don't want to bother * writing new hashCode()s either. */ protected boolean isSameEvent(SimulatorEvent event, SimulatorEvent otherEvent) { // check for null reference Assert.assertNotNull(event); Assert.assertNotNull(otherEvent); // type check if (!event.getClass().equals(otherEvent.getClass())) { return false; } // compare significant fields if (event.listener != otherEvent.listener || event.timestamp != otherEvent.timestamp) { return false; } if (event instanceof TaskAttemptCompletionEvent) { TaskStatus s = ((TaskAttemptCompletionEvent)event).getStatus(); TaskStatus os = ((TaskAttemptCompletionEvent)otherEvent).getStatus(); if (!s.getTaskID().equals(os.getTaskID())) { return false; } } return true; } }
apache-2.0
asedunov/intellij-community
jps/jps-builders-6/src/org/jetbrains/jps/javac/JavacRemoteProto.java
315650
/* * Copyright 2000-2016 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. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: javac_remote_proto.proto package org.jetbrains.jps.javac; public final class JavacRemoteProto { private JavacRemoteProto() {} public static void registerAllExtensions( com.google.protobuf.ExtensionRegistryLite registry) { } public interface MessageOrBuilder extends com.google.protobuf.MessageLiteOrBuilder { // required .org.jetbrains.javac.Message.UUID session_id = 1; /** * <code>required .org.jetbrains.javac.Message.UUID session_id = 1;</code> */ boolean hasSessionId(); /** * <code>required .org.jetbrains.javac.Message.UUID session_id = 1;</code> */ org.jetbrains.jps.javac.JavacRemoteProto.Message.UUID getSessionId(); // required .org.jetbrains.javac.Message.Type message_type = 2; /** * <code>required .org.jetbrains.javac.Message.Type message_type = 2;</code> */ boolean hasMessageType(); /** * <code>required .org.jetbrains.javac.Message.Type message_type = 2;</code> */ org.jetbrains.jps.javac.JavacRemoteProto.Message.Type getMessageType(); // optional .org.jetbrains.javac.Message.Request request = 3; /** * <code>optional .org.jetbrains.javac.Message.Request request = 3;</code> */ boolean hasRequest(); /** * <code>optional .org.jetbrains.javac.Message.Request request = 3;</code> */ org.jetbrains.jps.javac.JavacRemoteProto.Message.Request getRequest(); // optional .org.jetbrains.javac.Message.Response response = 4; /** * <code>optional .org.jetbrains.javac.Message.Response response = 4;</code> */ boolean hasResponse(); /** * <code>optional .org.jetbrains.javac.Message.Response response = 4;</code> */ org.jetbrains.jps.javac.JavacRemoteProto.Message.Response getResponse(); // optional .org.jetbrains.javac.Message.Failure failure = 5; /** * <code>optional .org.jetbrains.javac.Message.Failure failure = 5;</code> */ boolean hasFailure(); /** * <code>optional .org.jetbrains.javac.Message.Failure failure = 5;</code> */ org.jetbrains.jps.javac.JavacRemoteProto.Message.Failure getFailure(); } /** * Protobuf type {@code org.jetbrains.javac.Message} */ public static final class Message extends com.google.protobuf.GeneratedMessageLite implements MessageOrBuilder { // Use Message.newBuilder() to construct. private Message(com.google.protobuf.GeneratedMessageLite.Builder builder) { super(builder); } private Message(boolean noInit) {} private static final Message defaultInstance; public static Message getDefaultInstance() { return defaultInstance; } public Message getDefaultInstanceForType() { return defaultInstance; } private Message( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { initFields(); int mutable_bitField0_ = 0; try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownField(input, extensionRegistry, tag)) { done = true; } break; } case 10: { org.jetbrains.jps.javac.JavacRemoteProto.Message.UUID.Builder subBuilder = null; if (((bitField0_ & 0x00000001) == 0x00000001)) { subBuilder = sessionId_.toBuilder(); } sessionId_ = input.readMessage(org.jetbrains.jps.javac.JavacRemoteProto.Message.UUID.PARSER, extensionRegistry); if (subBuilder != null) { subBuilder.mergeFrom(sessionId_); sessionId_ = subBuilder.buildPartial(); } bitField0_ |= 0x00000001; break; } case 16: { int rawValue = input.readEnum(); org.jetbrains.jps.javac.JavacRemoteProto.Message.Type value = org.jetbrains.jps.javac.JavacRemoteProto.Message.Type.valueOf(rawValue); if (value != null) { bitField0_ |= 0x00000002; messageType_ = value; } break; } case 26: { org.jetbrains.jps.javac.JavacRemoteProto.Message.Request.Builder subBuilder = null; if (((bitField0_ & 0x00000004) == 0x00000004)) { subBuilder = request_.toBuilder(); } request_ = input.readMessage(org.jetbrains.jps.javac.JavacRemoteProto.Message.Request.PARSER, extensionRegistry); if (subBuilder != null) { subBuilder.mergeFrom(request_); request_ = subBuilder.buildPartial(); } bitField0_ |= 0x00000004; break; } case 34: { org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.Builder subBuilder = null; if (((bitField0_ & 0x00000008) == 0x00000008)) { subBuilder = response_.toBuilder(); } response_ = input.readMessage(org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.PARSER, extensionRegistry); if (subBuilder != null) { subBuilder.mergeFrom(response_); response_ = subBuilder.buildPartial(); } bitField0_ |= 0x00000008; break; } case 42: { org.jetbrains.jps.javac.JavacRemoteProto.Message.Failure.Builder subBuilder = null; if (((bitField0_ & 0x00000010) == 0x00000010)) { subBuilder = failure_.toBuilder(); } failure_ = input.readMessage(org.jetbrains.jps.javac.JavacRemoteProto.Message.Failure.PARSER, extensionRegistry); if (subBuilder != null) { subBuilder.mergeFrom(failure_); failure_ = subBuilder.buildPartial(); } bitField0_ |= 0x00000010; break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e.getMessage()).setUnfinishedMessage(this); } finally { makeExtensionsImmutable(); } } public static com.google.protobuf.Parser<Message> PARSER = new com.google.protobuf.AbstractParser<Message>() { public Message parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new Message(input, extensionRegistry); } }; @java.lang.Override public com.google.protobuf.Parser<Message> getParserForType() { return PARSER; } /** * Protobuf enum {@code org.jetbrains.javac.Message.Type} */ public enum Type implements com.google.protobuf.Internal.EnumLite { /** * <code>REQUEST = 1;</code> */ REQUEST(0, 1), /** * <code>RESPONSE = 2;</code> */ RESPONSE(1, 2), /** * <code>FAILURE = 3;</code> */ FAILURE(2, 3), ; /** * <code>REQUEST = 1;</code> */ public static final int REQUEST_VALUE = 1; /** * <code>RESPONSE = 2;</code> */ public static final int RESPONSE_VALUE = 2; /** * <code>FAILURE = 3;</code> */ public static final int FAILURE_VALUE = 3; public final int getNumber() { return value; } public static Type valueOf(int value) { switch (value) { case 1: return REQUEST; case 2: return RESPONSE; case 3: return FAILURE; default: return null; } } public static com.google.protobuf.Internal.EnumLiteMap<Type> internalGetValueMap() { return internalValueMap; } private static com.google.protobuf.Internal.EnumLiteMap<Type> internalValueMap = new com.google.protobuf.Internal.EnumLiteMap<Type>() { public Type findValueByNumber(int number) { return Type.valueOf(number); } }; private final int value; private Type(int index, int value) { this.value = value; } // @@protoc_insertion_point(enum_scope:org.jetbrains.javac.Message.Type) } public interface UUIDOrBuilder extends com.google.protobuf.MessageLiteOrBuilder { // required sint64 most_sig_bits = 1; /** * <code>required sint64 most_sig_bits = 1;</code> */ boolean hasMostSigBits(); /** * <code>required sint64 most_sig_bits = 1;</code> */ long getMostSigBits(); // required sint64 least_sig_bits = 2; /** * <code>required sint64 least_sig_bits = 2;</code> */ boolean hasLeastSigBits(); /** * <code>required sint64 least_sig_bits = 2;</code> */ long getLeastSigBits(); } /** * Protobuf type {@code org.jetbrains.javac.Message.UUID} */ public static final class UUID extends com.google.protobuf.GeneratedMessageLite implements UUIDOrBuilder { // Use UUID.newBuilder() to construct. private UUID(com.google.protobuf.GeneratedMessageLite.Builder builder) { super(builder); } private UUID(boolean noInit) {} private static final UUID defaultInstance; public static UUID getDefaultInstance() { return defaultInstance; } public UUID getDefaultInstanceForType() { return defaultInstance; } private UUID( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { initFields(); int mutable_bitField0_ = 0; try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownField(input, extensionRegistry, tag)) { done = true; } break; } case 8: { bitField0_ |= 0x00000001; mostSigBits_ = input.readSInt64(); break; } case 16: { bitField0_ |= 0x00000002; leastSigBits_ = input.readSInt64(); break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e.getMessage()).setUnfinishedMessage(this); } finally { makeExtensionsImmutable(); } } public static com.google.protobuf.Parser<UUID> PARSER = new com.google.protobuf.AbstractParser<UUID>() { public UUID parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new UUID(input, extensionRegistry); } }; @java.lang.Override public com.google.protobuf.Parser<UUID> getParserForType() { return PARSER; } private int bitField0_; // required sint64 most_sig_bits = 1; public static final int MOST_SIG_BITS_FIELD_NUMBER = 1; private long mostSigBits_; /** * <code>required sint64 most_sig_bits = 1;</code> */ public boolean hasMostSigBits() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * <code>required sint64 most_sig_bits = 1;</code> */ public long getMostSigBits() { return mostSigBits_; } // required sint64 least_sig_bits = 2; public static final int LEAST_SIG_BITS_FIELD_NUMBER = 2; private long leastSigBits_; /** * <code>required sint64 least_sig_bits = 2;</code> */ public boolean hasLeastSigBits() { return ((bitField0_ & 0x00000002) == 0x00000002); } /** * <code>required sint64 least_sig_bits = 2;</code> */ public long getLeastSigBits() { return leastSigBits_; } private void initFields() { mostSigBits_ = 0L; leastSigBits_ = 0L; } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized != -1) return isInitialized == 1; if (!hasMostSigBits()) { memoizedIsInitialized = 0; return false; } if (!hasLeastSigBits()) { memoizedIsInitialized = 0; return false; } memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getSerializedSize(); if (((bitField0_ & 0x00000001) == 0x00000001)) { output.writeSInt64(1, mostSigBits_); } if (((bitField0_ & 0x00000002) == 0x00000002)) { output.writeSInt64(2, leastSigBits_); } } private int memoizedSerializedSize = -1; public int getSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; if (((bitField0_ & 0x00000001) == 0x00000001)) { size += com.google.protobuf.CodedOutputStream .computeSInt64Size(1, mostSigBits_); } if (((bitField0_ & 0x00000002) == 0x00000002)) { size += com.google.protobuf.CodedOutputStream .computeSInt64Size(2, leastSigBits_); } memoizedSerializedSize = size; return size; } private static final long serialVersionUID = 0L; @java.lang.Override protected java.lang.Object writeReplace() throws java.io.ObjectStreamException { return super.writeReplace(); } public static org.jetbrains.jps.javac.JavacRemoteProto.Message.UUID parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static org.jetbrains.jps.javac.JavacRemoteProto.Message.UUID parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static org.jetbrains.jps.javac.JavacRemoteProto.Message.UUID parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static org.jetbrains.jps.javac.JavacRemoteProto.Message.UUID parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static org.jetbrains.jps.javac.JavacRemoteProto.Message.UUID parseFrom(java.io.InputStream input) throws java.io.IOException { return PARSER.parseFrom(input); } public static org.jetbrains.jps.javac.JavacRemoteProto.Message.UUID parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } public static org.jetbrains.jps.javac.JavacRemoteProto.Message.UUID parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return PARSER.parseDelimitedFrom(input); } public static org.jetbrains.jps.javac.JavacRemoteProto.Message.UUID parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseDelimitedFrom(input, extensionRegistry); } public static org.jetbrains.jps.javac.JavacRemoteProto.Message.UUID parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return PARSER.parseFrom(input); } public static org.jetbrains.jps.javac.JavacRemoteProto.Message.UUID parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } public static Builder newBuilder() { return Builder.create(); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder(org.jetbrains.jps.javac.JavacRemoteProto.Message.UUID prototype) { return newBuilder().mergeFrom(prototype); } public Builder toBuilder() { return newBuilder(this); } /** * Protobuf type {@code org.jetbrains.javac.Message.UUID} */ public static final class Builder extends com.google.protobuf.GeneratedMessageLite.Builder< org.jetbrains.jps.javac.JavacRemoteProto.Message.UUID, Builder> implements org.jetbrains.jps.javac.JavacRemoteProto.Message.UUIDOrBuilder { // Construct using org.jetbrains.jps.javac.JavacRemoteProto.Message.UUID.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { } private static Builder create() { return new Builder(); } public Builder clear() { super.clear(); mostSigBits_ = 0L; bitField0_ = (bitField0_ & ~0x00000001); leastSigBits_ = 0L; bitField0_ = (bitField0_ & ~0x00000002); return this; } public Builder clone() { return create().mergeFrom(buildPartial()); } public org.jetbrains.jps.javac.JavacRemoteProto.Message.UUID getDefaultInstanceForType() { return org.jetbrains.jps.javac.JavacRemoteProto.Message.UUID.getDefaultInstance(); } public org.jetbrains.jps.javac.JavacRemoteProto.Message.UUID build() { org.jetbrains.jps.javac.JavacRemoteProto.Message.UUID result = buildPartial(); if (!result.isInitialized()) { throw Builder.newUninitializedMessageException(result); } return result; } public org.jetbrains.jps.javac.JavacRemoteProto.Message.UUID buildPartial() { org.jetbrains.jps.javac.JavacRemoteProto.Message.UUID result = new org.jetbrains.jps.javac.JavacRemoteProto.Message.UUID(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) == 0x00000001)) { to_bitField0_ |= 0x00000001; } result.mostSigBits_ = mostSigBits_; if (((from_bitField0_ & 0x00000002) == 0x00000002)) { to_bitField0_ |= 0x00000002; } result.leastSigBits_ = leastSigBits_; result.bitField0_ = to_bitField0_; return result; } public Builder mergeFrom(org.jetbrains.jps.javac.JavacRemoteProto.Message.UUID other) { if (other == org.jetbrains.jps.javac.JavacRemoteProto.Message.UUID.getDefaultInstance()) return this; if (other.hasMostSigBits()) { setMostSigBits(other.getMostSigBits()); } if (other.hasLeastSigBits()) { setLeastSigBits(other.getLeastSigBits()); } return this; } public final boolean isInitialized() { if (!hasMostSigBits()) { return false; } if (!hasLeastSigBits()) { return false; } return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { org.jetbrains.jps.javac.JavacRemoteProto.Message.UUID parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (org.jetbrains.jps.javac.JavacRemoteProto.Message.UUID) e.getUnfinishedMessage(); throw e; } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; // required sint64 most_sig_bits = 1; private long mostSigBits_ ; /** * <code>required sint64 most_sig_bits = 1;</code> */ public boolean hasMostSigBits() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * <code>required sint64 most_sig_bits = 1;</code> */ public long getMostSigBits() { return mostSigBits_; } /** * <code>required sint64 most_sig_bits = 1;</code> */ public Builder setMostSigBits(long value) { bitField0_ |= 0x00000001; mostSigBits_ = value; return this; } /** * <code>required sint64 most_sig_bits = 1;</code> */ public Builder clearMostSigBits() { bitField0_ = (bitField0_ & ~0x00000001); mostSigBits_ = 0L; return this; } // required sint64 least_sig_bits = 2; private long leastSigBits_ ; /** * <code>required sint64 least_sig_bits = 2;</code> */ public boolean hasLeastSigBits() { return ((bitField0_ & 0x00000002) == 0x00000002); } /** * <code>required sint64 least_sig_bits = 2;</code> */ public long getLeastSigBits() { return leastSigBits_; } /** * <code>required sint64 least_sig_bits = 2;</code> */ public Builder setLeastSigBits(long value) { bitField0_ |= 0x00000002; leastSigBits_ = value; return this; } /** * <code>required sint64 least_sig_bits = 2;</code> */ public Builder clearLeastSigBits() { bitField0_ = (bitField0_ & ~0x00000002); leastSigBits_ = 0L; return this; } // @@protoc_insertion_point(builder_scope:org.jetbrains.javac.Message.UUID) } static { defaultInstance = new UUID(true); defaultInstance.initFields(); } // @@protoc_insertion_point(class_scope:org.jetbrains.javac.Message.UUID) } public interface FailureOrBuilder extends com.google.protobuf.MessageLiteOrBuilder { // optional int32 error_code = 1; /** * <code>optional int32 error_code = 1;</code> */ boolean hasErrorCode(); /** * <code>optional int32 error_code = 1;</code> */ int getErrorCode(); // optional string description = 2; /** * <code>optional string description = 2;</code> */ boolean hasDescription(); /** * <code>optional string description = 2;</code> */ java.lang.String getDescription(); /** * <code>optional string description = 2;</code> */ com.google.protobuf.ByteString getDescriptionBytes(); // optional string stacktrace = 3; /** * <code>optional string stacktrace = 3;</code> */ boolean hasStacktrace(); /** * <code>optional string stacktrace = 3;</code> */ java.lang.String getStacktrace(); /** * <code>optional string stacktrace = 3;</code> */ com.google.protobuf.ByteString getStacktraceBytes(); } /** * Protobuf type {@code org.jetbrains.javac.Message.Failure} */ public static final class Failure extends com.google.protobuf.GeneratedMessageLite implements FailureOrBuilder { // Use Failure.newBuilder() to construct. private Failure(com.google.protobuf.GeneratedMessageLite.Builder builder) { super(builder); } private Failure(boolean noInit) {} private static final Failure defaultInstance; public static Failure getDefaultInstance() { return defaultInstance; } public Failure getDefaultInstanceForType() { return defaultInstance; } private Failure( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { initFields(); int mutable_bitField0_ = 0; try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownField(input, extensionRegistry, tag)) { done = true; } break; } case 8: { bitField0_ |= 0x00000001; errorCode_ = input.readInt32(); break; } case 18: { bitField0_ |= 0x00000002; description_ = input.readBytes(); break; } case 26: { bitField0_ |= 0x00000004; stacktrace_ = input.readBytes(); break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e.getMessage()).setUnfinishedMessage(this); } finally { makeExtensionsImmutable(); } } public static com.google.protobuf.Parser<Failure> PARSER = new com.google.protobuf.AbstractParser<Failure>() { public Failure parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new Failure(input, extensionRegistry); } }; @java.lang.Override public com.google.protobuf.Parser<Failure> getParserForType() { return PARSER; } private int bitField0_; // optional int32 error_code = 1; public static final int ERROR_CODE_FIELD_NUMBER = 1; private int errorCode_; /** * <code>optional int32 error_code = 1;</code> */ public boolean hasErrorCode() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * <code>optional int32 error_code = 1;</code> */ public int getErrorCode() { return errorCode_; } // optional string description = 2; public static final int DESCRIPTION_FIELD_NUMBER = 2; private java.lang.Object description_; /** * <code>optional string description = 2;</code> */ public boolean hasDescription() { return ((bitField0_ & 0x00000002) == 0x00000002); } /** * <code>optional string description = 2;</code> */ public java.lang.String getDescription() { java.lang.Object ref = description_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { description_ = s; } return s; } } /** * <code>optional string description = 2;</code> */ public com.google.protobuf.ByteString getDescriptionBytes() { java.lang.Object ref = description_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); description_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } // optional string stacktrace = 3; public static final int STACKTRACE_FIELD_NUMBER = 3; private java.lang.Object stacktrace_; /** * <code>optional string stacktrace = 3;</code> */ public boolean hasStacktrace() { return ((bitField0_ & 0x00000004) == 0x00000004); } /** * <code>optional string stacktrace = 3;</code> */ public java.lang.String getStacktrace() { java.lang.Object ref = stacktrace_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { stacktrace_ = s; } return s; } } /** * <code>optional string stacktrace = 3;</code> */ public com.google.protobuf.ByteString getStacktraceBytes() { java.lang.Object ref = stacktrace_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); stacktrace_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private void initFields() { errorCode_ = 0; description_ = ""; stacktrace_ = ""; } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized != -1) return isInitialized == 1; memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getSerializedSize(); if (((bitField0_ & 0x00000001) == 0x00000001)) { output.writeInt32(1, errorCode_); } if (((bitField0_ & 0x00000002) == 0x00000002)) { output.writeBytes(2, getDescriptionBytes()); } if (((bitField0_ & 0x00000004) == 0x00000004)) { output.writeBytes(3, getStacktraceBytes()); } } private int memoizedSerializedSize = -1; public int getSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; if (((bitField0_ & 0x00000001) == 0x00000001)) { size += com.google.protobuf.CodedOutputStream .computeInt32Size(1, errorCode_); } if (((bitField0_ & 0x00000002) == 0x00000002)) { size += com.google.protobuf.CodedOutputStream .computeBytesSize(2, getDescriptionBytes()); } if (((bitField0_ & 0x00000004) == 0x00000004)) { size += com.google.protobuf.CodedOutputStream .computeBytesSize(3, getStacktraceBytes()); } memoizedSerializedSize = size; return size; } private static final long serialVersionUID = 0L; @java.lang.Override protected java.lang.Object writeReplace() throws java.io.ObjectStreamException { return super.writeReplace(); } public static org.jetbrains.jps.javac.JavacRemoteProto.Message.Failure parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static org.jetbrains.jps.javac.JavacRemoteProto.Message.Failure parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static org.jetbrains.jps.javac.JavacRemoteProto.Message.Failure parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static org.jetbrains.jps.javac.JavacRemoteProto.Message.Failure parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static org.jetbrains.jps.javac.JavacRemoteProto.Message.Failure parseFrom(java.io.InputStream input) throws java.io.IOException { return PARSER.parseFrom(input); } public static org.jetbrains.jps.javac.JavacRemoteProto.Message.Failure parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } public static org.jetbrains.jps.javac.JavacRemoteProto.Message.Failure parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return PARSER.parseDelimitedFrom(input); } public static org.jetbrains.jps.javac.JavacRemoteProto.Message.Failure parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseDelimitedFrom(input, extensionRegistry); } public static org.jetbrains.jps.javac.JavacRemoteProto.Message.Failure parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return PARSER.parseFrom(input); } public static org.jetbrains.jps.javac.JavacRemoteProto.Message.Failure parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } public static Builder newBuilder() { return Builder.create(); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder(org.jetbrains.jps.javac.JavacRemoteProto.Message.Failure prototype) { return newBuilder().mergeFrom(prototype); } public Builder toBuilder() { return newBuilder(this); } /** * Protobuf type {@code org.jetbrains.javac.Message.Failure} */ public static final class Builder extends com.google.protobuf.GeneratedMessageLite.Builder< org.jetbrains.jps.javac.JavacRemoteProto.Message.Failure, Builder> implements org.jetbrains.jps.javac.JavacRemoteProto.Message.FailureOrBuilder { // Construct using org.jetbrains.jps.javac.JavacRemoteProto.Message.Failure.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { } private static Builder create() { return new Builder(); } public Builder clear() { super.clear(); errorCode_ = 0; bitField0_ = (bitField0_ & ~0x00000001); description_ = ""; bitField0_ = (bitField0_ & ~0x00000002); stacktrace_ = ""; bitField0_ = (bitField0_ & ~0x00000004); return this; } public Builder clone() { return create().mergeFrom(buildPartial()); } public org.jetbrains.jps.javac.JavacRemoteProto.Message.Failure getDefaultInstanceForType() { return org.jetbrains.jps.javac.JavacRemoteProto.Message.Failure.getDefaultInstance(); } public org.jetbrains.jps.javac.JavacRemoteProto.Message.Failure build() { org.jetbrains.jps.javac.JavacRemoteProto.Message.Failure result = buildPartial(); if (!result.isInitialized()) { throw Builder.newUninitializedMessageException(result); } return result; } public org.jetbrains.jps.javac.JavacRemoteProto.Message.Failure buildPartial() { org.jetbrains.jps.javac.JavacRemoteProto.Message.Failure result = new org.jetbrains.jps.javac.JavacRemoteProto.Message.Failure(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) == 0x00000001)) { to_bitField0_ |= 0x00000001; } result.errorCode_ = errorCode_; if (((from_bitField0_ & 0x00000002) == 0x00000002)) { to_bitField0_ |= 0x00000002; } result.description_ = description_; if (((from_bitField0_ & 0x00000004) == 0x00000004)) { to_bitField0_ |= 0x00000004; } result.stacktrace_ = stacktrace_; result.bitField0_ = to_bitField0_; return result; } public Builder mergeFrom(org.jetbrains.jps.javac.JavacRemoteProto.Message.Failure other) { if (other == org.jetbrains.jps.javac.JavacRemoteProto.Message.Failure.getDefaultInstance()) return this; if (other.hasErrorCode()) { setErrorCode(other.getErrorCode()); } if (other.hasDescription()) { bitField0_ |= 0x00000002; description_ = other.description_; } if (other.hasStacktrace()) { bitField0_ |= 0x00000004; stacktrace_ = other.stacktrace_; } return this; } public final boolean isInitialized() { return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { org.jetbrains.jps.javac.JavacRemoteProto.Message.Failure parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (org.jetbrains.jps.javac.JavacRemoteProto.Message.Failure) e.getUnfinishedMessage(); throw e; } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; // optional int32 error_code = 1; private int errorCode_ ; /** * <code>optional int32 error_code = 1;</code> */ public boolean hasErrorCode() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * <code>optional int32 error_code = 1;</code> */ public int getErrorCode() { return errorCode_; } /** * <code>optional int32 error_code = 1;</code> */ public Builder setErrorCode(int value) { bitField0_ |= 0x00000001; errorCode_ = value; return this; } /** * <code>optional int32 error_code = 1;</code> */ public Builder clearErrorCode() { bitField0_ = (bitField0_ & ~0x00000001); errorCode_ = 0; return this; } // optional string description = 2; private java.lang.Object description_ = ""; /** * <code>optional string description = 2;</code> */ public boolean hasDescription() { return ((bitField0_ & 0x00000002) == 0x00000002); } /** * <code>optional string description = 2;</code> */ public java.lang.String getDescription() { java.lang.Object ref = description_; if (!(ref instanceof java.lang.String)) { java.lang.String s = ((com.google.protobuf.ByteString) ref) .toStringUtf8(); description_ = s; return s; } else { return (java.lang.String) ref; } } /** * <code>optional string description = 2;</code> */ public com.google.protobuf.ByteString getDescriptionBytes() { java.lang.Object ref = description_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); description_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <code>optional string description = 2;</code> */ public Builder setDescription( java.lang.String value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000002; description_ = value; return this; } /** * <code>optional string description = 2;</code> */ public Builder clearDescription() { bitField0_ = (bitField0_ & ~0x00000002); description_ = getDefaultInstance().getDescription(); return this; } /** * <code>optional string description = 2;</code> */ public Builder setDescriptionBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000002; description_ = value; return this; } // optional string stacktrace = 3; private java.lang.Object stacktrace_ = ""; /** * <code>optional string stacktrace = 3;</code> */ public boolean hasStacktrace() { return ((bitField0_ & 0x00000004) == 0x00000004); } /** * <code>optional string stacktrace = 3;</code> */ public java.lang.String getStacktrace() { java.lang.Object ref = stacktrace_; if (!(ref instanceof java.lang.String)) { java.lang.String s = ((com.google.protobuf.ByteString) ref) .toStringUtf8(); stacktrace_ = s; return s; } else { return (java.lang.String) ref; } } /** * <code>optional string stacktrace = 3;</code> */ public com.google.protobuf.ByteString getStacktraceBytes() { java.lang.Object ref = stacktrace_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); stacktrace_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <code>optional string stacktrace = 3;</code> */ public Builder setStacktrace( java.lang.String value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000004; stacktrace_ = value; return this; } /** * <code>optional string stacktrace = 3;</code> */ public Builder clearStacktrace() { bitField0_ = (bitField0_ & ~0x00000004); stacktrace_ = getDefaultInstance().getStacktrace(); return this; } /** * <code>optional string stacktrace = 3;</code> */ public Builder setStacktraceBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000004; stacktrace_ = value; return this; } // @@protoc_insertion_point(builder_scope:org.jetbrains.javac.Message.Failure) } static { defaultInstance = new Failure(true); defaultInstance.initFields(); } // @@protoc_insertion_point(class_scope:org.jetbrains.javac.Message.Failure) } public interface RequestOrBuilder extends com.google.protobuf.MessageLiteOrBuilder { // required .org.jetbrains.javac.Message.Request.Type request_type = 1; /** * <code>required .org.jetbrains.javac.Message.Request.Type request_type = 1;</code> */ boolean hasRequestType(); /** * <code>required .org.jetbrains.javac.Message.Request.Type request_type = 1;</code> */ org.jetbrains.jps.javac.JavacRemoteProto.Message.Request.Type getRequestType(); // repeated string option = 2; /** * <code>repeated string option = 2;</code> */ java.util.List<java.lang.String> getOptionList(); /** * <code>repeated string option = 2;</code> */ int getOptionCount(); /** * <code>repeated string option = 2;</code> */ java.lang.String getOption(int index); /** * <code>repeated string option = 2;</code> */ com.google.protobuf.ByteString getOptionBytes(int index); // repeated string file = 3; /** * <code>repeated string file = 3;</code> */ java.util.List<java.lang.String> getFileList(); /** * <code>repeated string file = 3;</code> */ int getFileCount(); /** * <code>repeated string file = 3;</code> */ java.lang.String getFile(int index); /** * <code>repeated string file = 3;</code> */ com.google.protobuf.ByteString getFileBytes(int index); // repeated string platform_classpath = 4; /** * <code>repeated string platform_classpath = 4;</code> */ java.util.List<java.lang.String> getPlatformClasspathList(); /** * <code>repeated string platform_classpath = 4;</code> */ int getPlatformClasspathCount(); /** * <code>repeated string platform_classpath = 4;</code> */ java.lang.String getPlatformClasspath(int index); /** * <code>repeated string platform_classpath = 4;</code> */ com.google.protobuf.ByteString getPlatformClasspathBytes(int index); // repeated string classpath = 5; /** * <code>repeated string classpath = 5;</code> */ java.util.List<java.lang.String> getClasspathList(); /** * <code>repeated string classpath = 5;</code> */ int getClasspathCount(); /** * <code>repeated string classpath = 5;</code> */ java.lang.String getClasspath(int index); /** * <code>repeated string classpath = 5;</code> */ com.google.protobuf.ByteString getClasspathBytes(int index); // repeated string sourcepath = 6; /** * <code>repeated string sourcepath = 6;</code> */ java.util.List<java.lang.String> getSourcepathList(); /** * <code>repeated string sourcepath = 6;</code> */ int getSourcepathCount(); /** * <code>repeated string sourcepath = 6;</code> */ java.lang.String getSourcepath(int index); /** * <code>repeated string sourcepath = 6;</code> */ com.google.protobuf.ByteString getSourcepathBytes(int index); // repeated .org.jetbrains.javac.Message.Request.OutputGroup output = 7; /** * <code>repeated .org.jetbrains.javac.Message.Request.OutputGroup output = 7;</code> */ java.util.List<org.jetbrains.jps.javac.JavacRemoteProto.Message.Request.OutputGroup> getOutputList(); /** * <code>repeated .org.jetbrains.javac.Message.Request.OutputGroup output = 7;</code> */ org.jetbrains.jps.javac.JavacRemoteProto.Message.Request.OutputGroup getOutput(int index); /** * <code>repeated .org.jetbrains.javac.Message.Request.OutputGroup output = 7;</code> */ int getOutputCount(); // repeated string module_path = 8; /** * <code>repeated string module_path = 8;</code> */ java.util.List<java.lang.String> getModulePathList(); /** * <code>repeated string module_path = 8;</code> */ int getModulePathCount(); /** * <code>repeated string module_path = 8;</code> */ java.lang.String getModulePath(int index); /** * <code>repeated string module_path = 8;</code> */ com.google.protobuf.ByteString getModulePathBytes(int index); } /** * Protobuf type {@code org.jetbrains.javac.Message.Request} */ public static final class Request extends com.google.protobuf.GeneratedMessageLite implements RequestOrBuilder { // Use Request.newBuilder() to construct. private Request(com.google.protobuf.GeneratedMessageLite.Builder builder) { super(builder); } private Request(boolean noInit) {} private static final Request defaultInstance; public static Request getDefaultInstance() { return defaultInstance; } public Request getDefaultInstanceForType() { return defaultInstance; } private Request( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { initFields(); int mutable_bitField0_ = 0; try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownField(input, extensionRegistry, tag)) { done = true; } break; } case 8: { int rawValue = input.readEnum(); org.jetbrains.jps.javac.JavacRemoteProto.Message.Request.Type value = org.jetbrains.jps.javac.JavacRemoteProto.Message.Request.Type.valueOf(rawValue); if (value != null) { bitField0_ |= 0x00000001; requestType_ = value; } break; } case 18: { if (!((mutable_bitField0_ & 0x00000002) == 0x00000002)) { option_ = new com.google.protobuf.LazyStringArrayList(); mutable_bitField0_ |= 0x00000002; } option_.add(input.readBytes()); break; } case 26: { if (!((mutable_bitField0_ & 0x00000004) == 0x00000004)) { file_ = new com.google.protobuf.LazyStringArrayList(); mutable_bitField0_ |= 0x00000004; } file_.add(input.readBytes()); break; } case 34: { if (!((mutable_bitField0_ & 0x00000008) == 0x00000008)) { platformClasspath_ = new com.google.protobuf.LazyStringArrayList(); mutable_bitField0_ |= 0x00000008; } platformClasspath_.add(input.readBytes()); break; } case 42: { if (!((mutable_bitField0_ & 0x00000010) == 0x00000010)) { classpath_ = new com.google.protobuf.LazyStringArrayList(); mutable_bitField0_ |= 0x00000010; } classpath_.add(input.readBytes()); break; } case 50: { if (!((mutable_bitField0_ & 0x00000020) == 0x00000020)) { sourcepath_ = new com.google.protobuf.LazyStringArrayList(); mutable_bitField0_ |= 0x00000020; } sourcepath_.add(input.readBytes()); break; } case 58: { if (!((mutable_bitField0_ & 0x00000040) == 0x00000040)) { output_ = new java.util.ArrayList<org.jetbrains.jps.javac.JavacRemoteProto.Message.Request.OutputGroup>(); mutable_bitField0_ |= 0x00000040; } output_.add(input.readMessage(org.jetbrains.jps.javac.JavacRemoteProto.Message.Request.OutputGroup.PARSER, extensionRegistry)); break; } case 66: { if (!((mutable_bitField0_ & 0x00000080) == 0x00000080)) { modulePath_ = new com.google.protobuf.LazyStringArrayList(); mutable_bitField0_ |= 0x00000080; } modulePath_.add(input.readBytes()); break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e.getMessage()).setUnfinishedMessage(this); } finally { if (((mutable_bitField0_ & 0x00000002) == 0x00000002)) { option_ = new com.google.protobuf.UnmodifiableLazyStringList(option_); } if (((mutable_bitField0_ & 0x00000004) == 0x00000004)) { file_ = new com.google.protobuf.UnmodifiableLazyStringList(file_); } if (((mutable_bitField0_ & 0x00000008) == 0x00000008)) { platformClasspath_ = new com.google.protobuf.UnmodifiableLazyStringList(platformClasspath_); } if (((mutable_bitField0_ & 0x00000010) == 0x00000010)) { classpath_ = new com.google.protobuf.UnmodifiableLazyStringList(classpath_); } if (((mutable_bitField0_ & 0x00000020) == 0x00000020)) { sourcepath_ = new com.google.protobuf.UnmodifiableLazyStringList(sourcepath_); } if (((mutable_bitField0_ & 0x00000040) == 0x00000040)) { output_ = java.util.Collections.unmodifiableList(output_); } if (((mutable_bitField0_ & 0x00000080) == 0x00000080)) { modulePath_ = new com.google.protobuf.UnmodifiableLazyStringList(modulePath_); } makeExtensionsImmutable(); } } public static com.google.protobuf.Parser<Request> PARSER = new com.google.protobuf.AbstractParser<Request>() { public Request parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new Request(input, extensionRegistry); } }; @java.lang.Override public com.google.protobuf.Parser<Request> getParserForType() { return PARSER; } /** * Protobuf enum {@code org.jetbrains.javac.Message.Request.Type} */ public enum Type implements com.google.protobuf.Internal.EnumLite { /** * <code>COMPILE = 1;</code> */ COMPILE(0, 1), /** * <code>CANCEL = 2;</code> */ CANCEL(1, 2), /** * <code>SHUTDOWN = 3;</code> */ SHUTDOWN(2, 3), ; /** * <code>COMPILE = 1;</code> */ public static final int COMPILE_VALUE = 1; /** * <code>CANCEL = 2;</code> */ public static final int CANCEL_VALUE = 2; /** * <code>SHUTDOWN = 3;</code> */ public static final int SHUTDOWN_VALUE = 3; public final int getNumber() { return value; } public static Type valueOf(int value) { switch (value) { case 1: return COMPILE; case 2: return CANCEL; case 3: return SHUTDOWN; default: return null; } } public static com.google.protobuf.Internal.EnumLiteMap<Type> internalGetValueMap() { return internalValueMap; } private static com.google.protobuf.Internal.EnumLiteMap<Type> internalValueMap = new com.google.protobuf.Internal.EnumLiteMap<Type>() { public Type findValueByNumber(int number) { return Type.valueOf(number); } }; private final int value; private Type(int index, int value) { this.value = value; } // @@protoc_insertion_point(enum_scope:org.jetbrains.javac.Message.Request.Type) } public interface OutputGroupOrBuilder extends com.google.protobuf.MessageLiteOrBuilder { // required string output_root = 1; /** * <code>required string output_root = 1;</code> */ boolean hasOutputRoot(); /** * <code>required string output_root = 1;</code> */ java.lang.String getOutputRoot(); /** * <code>required string output_root = 1;</code> */ com.google.protobuf.ByteString getOutputRootBytes(); // repeated string source_root = 2; /** * <code>repeated string source_root = 2;</code> */ java.util.List<java.lang.String> getSourceRootList(); /** * <code>repeated string source_root = 2;</code> */ int getSourceRootCount(); /** * <code>repeated string source_root = 2;</code> */ java.lang.String getSourceRoot(int index); /** * <code>repeated string source_root = 2;</code> */ com.google.protobuf.ByteString getSourceRootBytes(int index); } /** * Protobuf type {@code org.jetbrains.javac.Message.Request.OutputGroup} */ public static final class OutputGroup extends com.google.protobuf.GeneratedMessageLite implements OutputGroupOrBuilder { // Use OutputGroup.newBuilder() to construct. private OutputGroup(com.google.protobuf.GeneratedMessageLite.Builder builder) { super(builder); } private OutputGroup(boolean noInit) {} private static final OutputGroup defaultInstance; public static OutputGroup getDefaultInstance() { return defaultInstance; } public OutputGroup getDefaultInstanceForType() { return defaultInstance; } private OutputGroup( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { initFields(); int mutable_bitField0_ = 0; try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownField(input, extensionRegistry, tag)) { done = true; } break; } case 10: { bitField0_ |= 0x00000001; outputRoot_ = input.readBytes(); break; } case 18: { if (!((mutable_bitField0_ & 0x00000002) == 0x00000002)) { sourceRoot_ = new com.google.protobuf.LazyStringArrayList(); mutable_bitField0_ |= 0x00000002; } sourceRoot_.add(input.readBytes()); break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e.getMessage()).setUnfinishedMessage(this); } finally { if (((mutable_bitField0_ & 0x00000002) == 0x00000002)) { sourceRoot_ = new com.google.protobuf.UnmodifiableLazyStringList(sourceRoot_); } makeExtensionsImmutable(); } } public static com.google.protobuf.Parser<OutputGroup> PARSER = new com.google.protobuf.AbstractParser<OutputGroup>() { public OutputGroup parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new OutputGroup(input, extensionRegistry); } }; @java.lang.Override public com.google.protobuf.Parser<OutputGroup> getParserForType() { return PARSER; } private int bitField0_; // required string output_root = 1; public static final int OUTPUT_ROOT_FIELD_NUMBER = 1; private java.lang.Object outputRoot_; /** * <code>required string output_root = 1;</code> */ public boolean hasOutputRoot() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * <code>required string output_root = 1;</code> */ public java.lang.String getOutputRoot() { java.lang.Object ref = outputRoot_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { outputRoot_ = s; } return s; } } /** * <code>required string output_root = 1;</code> */ public com.google.protobuf.ByteString getOutputRootBytes() { java.lang.Object ref = outputRoot_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); outputRoot_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } // repeated string source_root = 2; public static final int SOURCE_ROOT_FIELD_NUMBER = 2; private com.google.protobuf.LazyStringList sourceRoot_; /** * <code>repeated string source_root = 2;</code> */ public java.util.List<java.lang.String> getSourceRootList() { return sourceRoot_; } /** * <code>repeated string source_root = 2;</code> */ public int getSourceRootCount() { return sourceRoot_.size(); } /** * <code>repeated string source_root = 2;</code> */ public java.lang.String getSourceRoot(int index) { return sourceRoot_.get(index); } /** * <code>repeated string source_root = 2;</code> */ public com.google.protobuf.ByteString getSourceRootBytes(int index) { return sourceRoot_.getByteString(index); } private void initFields() { outputRoot_ = ""; sourceRoot_ = com.google.protobuf.LazyStringArrayList.EMPTY; } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized != -1) return isInitialized == 1; if (!hasOutputRoot()) { memoizedIsInitialized = 0; return false; } memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getSerializedSize(); if (((bitField0_ & 0x00000001) == 0x00000001)) { output.writeBytes(1, getOutputRootBytes()); } for (int i = 0; i < sourceRoot_.size(); i++) { output.writeBytes(2, sourceRoot_.getByteString(i)); } } private int memoizedSerializedSize = -1; public int getSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; if (((bitField0_ & 0x00000001) == 0x00000001)) { size += com.google.protobuf.CodedOutputStream .computeBytesSize(1, getOutputRootBytes()); } { int dataSize = 0; for (int i = 0; i < sourceRoot_.size(); i++) { dataSize += com.google.protobuf.CodedOutputStream .computeBytesSizeNoTag(sourceRoot_.getByteString(i)); } size += dataSize; size += 1 * getSourceRootList().size(); } memoizedSerializedSize = size; return size; } private static final long serialVersionUID = 0L; @java.lang.Override protected java.lang.Object writeReplace() throws java.io.ObjectStreamException { return super.writeReplace(); } public static org.jetbrains.jps.javac.JavacRemoteProto.Message.Request.OutputGroup parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static org.jetbrains.jps.javac.JavacRemoteProto.Message.Request.OutputGroup parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static org.jetbrains.jps.javac.JavacRemoteProto.Message.Request.OutputGroup parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static org.jetbrains.jps.javac.JavacRemoteProto.Message.Request.OutputGroup parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static org.jetbrains.jps.javac.JavacRemoteProto.Message.Request.OutputGroup parseFrom(java.io.InputStream input) throws java.io.IOException { return PARSER.parseFrom(input); } public static org.jetbrains.jps.javac.JavacRemoteProto.Message.Request.OutputGroup parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } public static org.jetbrains.jps.javac.JavacRemoteProto.Message.Request.OutputGroup parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return PARSER.parseDelimitedFrom(input); } public static org.jetbrains.jps.javac.JavacRemoteProto.Message.Request.OutputGroup parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseDelimitedFrom(input, extensionRegistry); } public static org.jetbrains.jps.javac.JavacRemoteProto.Message.Request.OutputGroup parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return PARSER.parseFrom(input); } public static org.jetbrains.jps.javac.JavacRemoteProto.Message.Request.OutputGroup parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } public static Builder newBuilder() { return Builder.create(); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder(org.jetbrains.jps.javac.JavacRemoteProto.Message.Request.OutputGroup prototype) { return newBuilder().mergeFrom(prototype); } public Builder toBuilder() { return newBuilder(this); } /** * Protobuf type {@code org.jetbrains.javac.Message.Request.OutputGroup} */ public static final class Builder extends com.google.protobuf.GeneratedMessageLite.Builder< org.jetbrains.jps.javac.JavacRemoteProto.Message.Request.OutputGroup, Builder> implements org.jetbrains.jps.javac.JavacRemoteProto.Message.Request.OutputGroupOrBuilder { // Construct using org.jetbrains.jps.javac.JavacRemoteProto.Message.Request.OutputGroup.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { } private static Builder create() { return new Builder(); } public Builder clear() { super.clear(); outputRoot_ = ""; bitField0_ = (bitField0_ & ~0x00000001); sourceRoot_ = com.google.protobuf.LazyStringArrayList.EMPTY; bitField0_ = (bitField0_ & ~0x00000002); return this; } public Builder clone() { return create().mergeFrom(buildPartial()); } public org.jetbrains.jps.javac.JavacRemoteProto.Message.Request.OutputGroup getDefaultInstanceForType() { return org.jetbrains.jps.javac.JavacRemoteProto.Message.Request.OutputGroup.getDefaultInstance(); } public org.jetbrains.jps.javac.JavacRemoteProto.Message.Request.OutputGroup build() { org.jetbrains.jps.javac.JavacRemoteProto.Message.Request.OutputGroup result = buildPartial(); if (!result.isInitialized()) { throw Builder.newUninitializedMessageException(result); } return result; } public org.jetbrains.jps.javac.JavacRemoteProto.Message.Request.OutputGroup buildPartial() { org.jetbrains.jps.javac.JavacRemoteProto.Message.Request.OutputGroup result = new org.jetbrains.jps.javac.JavacRemoteProto.Message.Request.OutputGroup(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) == 0x00000001)) { to_bitField0_ |= 0x00000001; } result.outputRoot_ = outputRoot_; if (((bitField0_ & 0x00000002) == 0x00000002)) { sourceRoot_ = new com.google.protobuf.UnmodifiableLazyStringList( sourceRoot_); bitField0_ = (bitField0_ & ~0x00000002); } result.sourceRoot_ = sourceRoot_; result.bitField0_ = to_bitField0_; return result; } public Builder mergeFrom(org.jetbrains.jps.javac.JavacRemoteProto.Message.Request.OutputGroup other) { if (other == org.jetbrains.jps.javac.JavacRemoteProto.Message.Request.OutputGroup.getDefaultInstance()) return this; if (other.hasOutputRoot()) { bitField0_ |= 0x00000001; outputRoot_ = other.outputRoot_; } if (!other.sourceRoot_.isEmpty()) { if (sourceRoot_.isEmpty()) { sourceRoot_ = other.sourceRoot_; bitField0_ = (bitField0_ & ~0x00000002); } else { ensureSourceRootIsMutable(); sourceRoot_.addAll(other.sourceRoot_); } } return this; } public final boolean isInitialized() { if (!hasOutputRoot()) { return false; } return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { org.jetbrains.jps.javac.JavacRemoteProto.Message.Request.OutputGroup parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (org.jetbrains.jps.javac.JavacRemoteProto.Message.Request.OutputGroup) e.getUnfinishedMessage(); throw e; } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; // required string output_root = 1; private java.lang.Object outputRoot_ = ""; /** * <code>required string output_root = 1;</code> */ public boolean hasOutputRoot() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * <code>required string output_root = 1;</code> */ public java.lang.String getOutputRoot() { java.lang.Object ref = outputRoot_; if (!(ref instanceof java.lang.String)) { java.lang.String s = ((com.google.protobuf.ByteString) ref) .toStringUtf8(); outputRoot_ = s; return s; } else { return (java.lang.String) ref; } } /** * <code>required string output_root = 1;</code> */ public com.google.protobuf.ByteString getOutputRootBytes() { java.lang.Object ref = outputRoot_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); outputRoot_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <code>required string output_root = 1;</code> */ public Builder setOutputRoot( java.lang.String value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000001; outputRoot_ = value; return this; } /** * <code>required string output_root = 1;</code> */ public Builder clearOutputRoot() { bitField0_ = (bitField0_ & ~0x00000001); outputRoot_ = getDefaultInstance().getOutputRoot(); return this; } /** * <code>required string output_root = 1;</code> */ public Builder setOutputRootBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000001; outputRoot_ = value; return this; } // repeated string source_root = 2; private com.google.protobuf.LazyStringList sourceRoot_ = com.google.protobuf.LazyStringArrayList.EMPTY; private void ensureSourceRootIsMutable() { if (!((bitField0_ & 0x00000002) == 0x00000002)) { sourceRoot_ = new com.google.protobuf.LazyStringArrayList(sourceRoot_); bitField0_ |= 0x00000002; } } /** * <code>repeated string source_root = 2;</code> */ public java.util.List<java.lang.String> getSourceRootList() { return java.util.Collections.unmodifiableList(sourceRoot_); } /** * <code>repeated string source_root = 2;</code> */ public int getSourceRootCount() { return sourceRoot_.size(); } /** * <code>repeated string source_root = 2;</code> */ public java.lang.String getSourceRoot(int index) { return sourceRoot_.get(index); } /** * <code>repeated string source_root = 2;</code> */ public com.google.protobuf.ByteString getSourceRootBytes(int index) { return sourceRoot_.getByteString(index); } /** * <code>repeated string source_root = 2;</code> */ public Builder setSourceRoot( int index, java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureSourceRootIsMutable(); sourceRoot_.set(index, value); return this; } /** * <code>repeated string source_root = 2;</code> */ public Builder addSourceRoot( java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureSourceRootIsMutable(); sourceRoot_.add(value); return this; } /** * <code>repeated string source_root = 2;</code> */ public Builder addAllSourceRoot( java.lang.Iterable<java.lang.String> values) { ensureSourceRootIsMutable(); super.addAll(values, sourceRoot_); return this; } /** * <code>repeated string source_root = 2;</code> */ public Builder clearSourceRoot() { sourceRoot_ = com.google.protobuf.LazyStringArrayList.EMPTY; bitField0_ = (bitField0_ & ~0x00000002); return this; } /** * <code>repeated string source_root = 2;</code> */ public Builder addSourceRootBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } ensureSourceRootIsMutable(); sourceRoot_.add(value); return this; } // @@protoc_insertion_point(builder_scope:org.jetbrains.javac.Message.Request.OutputGroup) } static { defaultInstance = new OutputGroup(true); defaultInstance.initFields(); } // @@protoc_insertion_point(class_scope:org.jetbrains.javac.Message.Request.OutputGroup) } private int bitField0_; // required .org.jetbrains.javac.Message.Request.Type request_type = 1; public static final int REQUEST_TYPE_FIELD_NUMBER = 1; private org.jetbrains.jps.javac.JavacRemoteProto.Message.Request.Type requestType_; /** * <code>required .org.jetbrains.javac.Message.Request.Type request_type = 1;</code> */ public boolean hasRequestType() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * <code>required .org.jetbrains.javac.Message.Request.Type request_type = 1;</code> */ public org.jetbrains.jps.javac.JavacRemoteProto.Message.Request.Type getRequestType() { return requestType_; } // repeated string option = 2; public static final int OPTION_FIELD_NUMBER = 2; private com.google.protobuf.LazyStringList option_; /** * <code>repeated string option = 2;</code> */ public java.util.List<java.lang.String> getOptionList() { return option_; } /** * <code>repeated string option = 2;</code> */ public int getOptionCount() { return option_.size(); } /** * <code>repeated string option = 2;</code> */ public java.lang.String getOption(int index) { return option_.get(index); } /** * <code>repeated string option = 2;</code> */ public com.google.protobuf.ByteString getOptionBytes(int index) { return option_.getByteString(index); } // repeated string file = 3; public static final int FILE_FIELD_NUMBER = 3; private com.google.protobuf.LazyStringList file_; /** * <code>repeated string file = 3;</code> */ public java.util.List<java.lang.String> getFileList() { return file_; } /** * <code>repeated string file = 3;</code> */ public int getFileCount() { return file_.size(); } /** * <code>repeated string file = 3;</code> */ public java.lang.String getFile(int index) { return file_.get(index); } /** * <code>repeated string file = 3;</code> */ public com.google.protobuf.ByteString getFileBytes(int index) { return file_.getByteString(index); } // repeated string platform_classpath = 4; public static final int PLATFORM_CLASSPATH_FIELD_NUMBER = 4; private com.google.protobuf.LazyStringList platformClasspath_; /** * <code>repeated string platform_classpath = 4;</code> */ public java.util.List<java.lang.String> getPlatformClasspathList() { return platformClasspath_; } /** * <code>repeated string platform_classpath = 4;</code> */ public int getPlatformClasspathCount() { return platformClasspath_.size(); } /** * <code>repeated string platform_classpath = 4;</code> */ public java.lang.String getPlatformClasspath(int index) { return platformClasspath_.get(index); } /** * <code>repeated string platform_classpath = 4;</code> */ public com.google.protobuf.ByteString getPlatformClasspathBytes(int index) { return platformClasspath_.getByteString(index); } // repeated string classpath = 5; public static final int CLASSPATH_FIELD_NUMBER = 5; private com.google.protobuf.LazyStringList classpath_; /** * <code>repeated string classpath = 5;</code> */ public java.util.List<java.lang.String> getClasspathList() { return classpath_; } /** * <code>repeated string classpath = 5;</code> */ public int getClasspathCount() { return classpath_.size(); } /** * <code>repeated string classpath = 5;</code> */ public java.lang.String getClasspath(int index) { return classpath_.get(index); } /** * <code>repeated string classpath = 5;</code> */ public com.google.protobuf.ByteString getClasspathBytes(int index) { return classpath_.getByteString(index); } // repeated string sourcepath = 6; public static final int SOURCEPATH_FIELD_NUMBER = 6; private com.google.protobuf.LazyStringList sourcepath_; /** * <code>repeated string sourcepath = 6;</code> */ public java.util.List<java.lang.String> getSourcepathList() { return sourcepath_; } /** * <code>repeated string sourcepath = 6;</code> */ public int getSourcepathCount() { return sourcepath_.size(); } /** * <code>repeated string sourcepath = 6;</code> */ public java.lang.String getSourcepath(int index) { return sourcepath_.get(index); } /** * <code>repeated string sourcepath = 6;</code> */ public com.google.protobuf.ByteString getSourcepathBytes(int index) { return sourcepath_.getByteString(index); } // repeated .org.jetbrains.javac.Message.Request.OutputGroup output = 7; public static final int OUTPUT_FIELD_NUMBER = 7; private java.util.List<org.jetbrains.jps.javac.JavacRemoteProto.Message.Request.OutputGroup> output_; /** * <code>repeated .org.jetbrains.javac.Message.Request.OutputGroup output = 7;</code> */ public java.util.List<org.jetbrains.jps.javac.JavacRemoteProto.Message.Request.OutputGroup> getOutputList() { return output_; } /** * <code>repeated .org.jetbrains.javac.Message.Request.OutputGroup output = 7;</code> */ public java.util.List<? extends org.jetbrains.jps.javac.JavacRemoteProto.Message.Request.OutputGroupOrBuilder> getOutputOrBuilderList() { return output_; } /** * <code>repeated .org.jetbrains.javac.Message.Request.OutputGroup output = 7;</code> */ public int getOutputCount() { return output_.size(); } /** * <code>repeated .org.jetbrains.javac.Message.Request.OutputGroup output = 7;</code> */ public org.jetbrains.jps.javac.JavacRemoteProto.Message.Request.OutputGroup getOutput(int index) { return output_.get(index); } /** * <code>repeated .org.jetbrains.javac.Message.Request.OutputGroup output = 7;</code> */ public org.jetbrains.jps.javac.JavacRemoteProto.Message.Request.OutputGroupOrBuilder getOutputOrBuilder( int index) { return output_.get(index); } // repeated string module_path = 8; public static final int MODULE_PATH_FIELD_NUMBER = 8; private com.google.protobuf.LazyStringList modulePath_; /** * <code>repeated string module_path = 8;</code> */ public java.util.List<java.lang.String> getModulePathList() { return modulePath_; } /** * <code>repeated string module_path = 8;</code> */ public int getModulePathCount() { return modulePath_.size(); } /** * <code>repeated string module_path = 8;</code> */ public java.lang.String getModulePath(int index) { return modulePath_.get(index); } /** * <code>repeated string module_path = 8;</code> */ public com.google.protobuf.ByteString getModulePathBytes(int index) { return modulePath_.getByteString(index); } private void initFields() { requestType_ = org.jetbrains.jps.javac.JavacRemoteProto.Message.Request.Type.COMPILE; option_ = com.google.protobuf.LazyStringArrayList.EMPTY; file_ = com.google.protobuf.LazyStringArrayList.EMPTY; platformClasspath_ = com.google.protobuf.LazyStringArrayList.EMPTY; classpath_ = com.google.protobuf.LazyStringArrayList.EMPTY; sourcepath_ = com.google.protobuf.LazyStringArrayList.EMPTY; output_ = java.util.Collections.emptyList(); modulePath_ = com.google.protobuf.LazyStringArrayList.EMPTY; } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized != -1) return isInitialized == 1; if (!hasRequestType()) { memoizedIsInitialized = 0; return false; } for (int i = 0; i < getOutputCount(); i++) { if (!getOutput(i).isInitialized()) { memoizedIsInitialized = 0; return false; } } memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getSerializedSize(); if (((bitField0_ & 0x00000001) == 0x00000001)) { output.writeEnum(1, requestType_.getNumber()); } for (int i = 0; i < option_.size(); i++) { output.writeBytes(2, option_.getByteString(i)); } for (int i = 0; i < file_.size(); i++) { output.writeBytes(3, file_.getByteString(i)); } for (int i = 0; i < platformClasspath_.size(); i++) { output.writeBytes(4, platformClasspath_.getByteString(i)); } for (int i = 0; i < classpath_.size(); i++) { output.writeBytes(5, classpath_.getByteString(i)); } for (int i = 0; i < sourcepath_.size(); i++) { output.writeBytes(6, sourcepath_.getByteString(i)); } for (int i = 0; i < output_.size(); i++) { output.writeMessage(7, output_.get(i)); } for (int i = 0; i < modulePath_.size(); i++) { output.writeBytes(8, modulePath_.getByteString(i)); } } private int memoizedSerializedSize = -1; public int getSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; if (((bitField0_ & 0x00000001) == 0x00000001)) { size += com.google.protobuf.CodedOutputStream .computeEnumSize(1, requestType_.getNumber()); } { int dataSize = 0; for (int i = 0; i < option_.size(); i++) { dataSize += com.google.protobuf.CodedOutputStream .computeBytesSizeNoTag(option_.getByteString(i)); } size += dataSize; size += 1 * getOptionList().size(); } { int dataSize = 0; for (int i = 0; i < file_.size(); i++) { dataSize += com.google.protobuf.CodedOutputStream .computeBytesSizeNoTag(file_.getByteString(i)); } size += dataSize; size += 1 * getFileList().size(); } { int dataSize = 0; for (int i = 0; i < platformClasspath_.size(); i++) { dataSize += com.google.protobuf.CodedOutputStream .computeBytesSizeNoTag(platformClasspath_.getByteString(i)); } size += dataSize; size += 1 * getPlatformClasspathList().size(); } { int dataSize = 0; for (int i = 0; i < classpath_.size(); i++) { dataSize += com.google.protobuf.CodedOutputStream .computeBytesSizeNoTag(classpath_.getByteString(i)); } size += dataSize; size += 1 * getClasspathList().size(); } { int dataSize = 0; for (int i = 0; i < sourcepath_.size(); i++) { dataSize += com.google.protobuf.CodedOutputStream .computeBytesSizeNoTag(sourcepath_.getByteString(i)); } size += dataSize; size += 1 * getSourcepathList().size(); } for (int i = 0; i < output_.size(); i++) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(7, output_.get(i)); } { int dataSize = 0; for (int i = 0; i < modulePath_.size(); i++) { dataSize += com.google.protobuf.CodedOutputStream .computeBytesSizeNoTag(modulePath_.getByteString(i)); } size += dataSize; size += 1 * getModulePathList().size(); } memoizedSerializedSize = size; return size; } private static final long serialVersionUID = 0L; @java.lang.Override protected java.lang.Object writeReplace() throws java.io.ObjectStreamException { return super.writeReplace(); } public static org.jetbrains.jps.javac.JavacRemoteProto.Message.Request parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static org.jetbrains.jps.javac.JavacRemoteProto.Message.Request parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static org.jetbrains.jps.javac.JavacRemoteProto.Message.Request parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static org.jetbrains.jps.javac.JavacRemoteProto.Message.Request parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static org.jetbrains.jps.javac.JavacRemoteProto.Message.Request parseFrom(java.io.InputStream input) throws java.io.IOException { return PARSER.parseFrom(input); } public static org.jetbrains.jps.javac.JavacRemoteProto.Message.Request parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } public static org.jetbrains.jps.javac.JavacRemoteProto.Message.Request parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return PARSER.parseDelimitedFrom(input); } public static org.jetbrains.jps.javac.JavacRemoteProto.Message.Request parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseDelimitedFrom(input, extensionRegistry); } public static org.jetbrains.jps.javac.JavacRemoteProto.Message.Request parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return PARSER.parseFrom(input); } public static org.jetbrains.jps.javac.JavacRemoteProto.Message.Request parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } public static Builder newBuilder() { return Builder.create(); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder(org.jetbrains.jps.javac.JavacRemoteProto.Message.Request prototype) { return newBuilder().mergeFrom(prototype); } public Builder toBuilder() { return newBuilder(this); } /** * Protobuf type {@code org.jetbrains.javac.Message.Request} */ public static final class Builder extends com.google.protobuf.GeneratedMessageLite.Builder< org.jetbrains.jps.javac.JavacRemoteProto.Message.Request, Builder> implements org.jetbrains.jps.javac.JavacRemoteProto.Message.RequestOrBuilder { // Construct using org.jetbrains.jps.javac.JavacRemoteProto.Message.Request.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { } private static Builder create() { return new Builder(); } public Builder clear() { super.clear(); requestType_ = org.jetbrains.jps.javac.JavacRemoteProto.Message.Request.Type.COMPILE; bitField0_ = (bitField0_ & ~0x00000001); option_ = com.google.protobuf.LazyStringArrayList.EMPTY; bitField0_ = (bitField0_ & ~0x00000002); file_ = com.google.protobuf.LazyStringArrayList.EMPTY; bitField0_ = (bitField0_ & ~0x00000004); platformClasspath_ = com.google.protobuf.LazyStringArrayList.EMPTY; bitField0_ = (bitField0_ & ~0x00000008); classpath_ = com.google.protobuf.LazyStringArrayList.EMPTY; bitField0_ = (bitField0_ & ~0x00000010); sourcepath_ = com.google.protobuf.LazyStringArrayList.EMPTY; bitField0_ = (bitField0_ & ~0x00000020); output_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000040); modulePath_ = com.google.protobuf.LazyStringArrayList.EMPTY; bitField0_ = (bitField0_ & ~0x00000080); return this; } public Builder clone() { return create().mergeFrom(buildPartial()); } public org.jetbrains.jps.javac.JavacRemoteProto.Message.Request getDefaultInstanceForType() { return org.jetbrains.jps.javac.JavacRemoteProto.Message.Request.getDefaultInstance(); } public org.jetbrains.jps.javac.JavacRemoteProto.Message.Request build() { org.jetbrains.jps.javac.JavacRemoteProto.Message.Request result = buildPartial(); if (!result.isInitialized()) { throw Builder.newUninitializedMessageException(result); } return result; } public org.jetbrains.jps.javac.JavacRemoteProto.Message.Request buildPartial() { org.jetbrains.jps.javac.JavacRemoteProto.Message.Request result = new org.jetbrains.jps.javac.JavacRemoteProto.Message.Request(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) == 0x00000001)) { to_bitField0_ |= 0x00000001; } result.requestType_ = requestType_; if (((bitField0_ & 0x00000002) == 0x00000002)) { option_ = new com.google.protobuf.UnmodifiableLazyStringList( option_); bitField0_ = (bitField0_ & ~0x00000002); } result.option_ = option_; if (((bitField0_ & 0x00000004) == 0x00000004)) { file_ = new com.google.protobuf.UnmodifiableLazyStringList( file_); bitField0_ = (bitField0_ & ~0x00000004); } result.file_ = file_; if (((bitField0_ & 0x00000008) == 0x00000008)) { platformClasspath_ = new com.google.protobuf.UnmodifiableLazyStringList( platformClasspath_); bitField0_ = (bitField0_ & ~0x00000008); } result.platformClasspath_ = platformClasspath_; if (((bitField0_ & 0x00000010) == 0x00000010)) { classpath_ = new com.google.protobuf.UnmodifiableLazyStringList( classpath_); bitField0_ = (bitField0_ & ~0x00000010); } result.classpath_ = classpath_; if (((bitField0_ & 0x00000020) == 0x00000020)) { sourcepath_ = new com.google.protobuf.UnmodifiableLazyStringList( sourcepath_); bitField0_ = (bitField0_ & ~0x00000020); } result.sourcepath_ = sourcepath_; if (((bitField0_ & 0x00000040) == 0x00000040)) { output_ = java.util.Collections.unmodifiableList(output_); bitField0_ = (bitField0_ & ~0x00000040); } result.output_ = output_; if (((bitField0_ & 0x00000080) == 0x00000080)) { modulePath_ = new com.google.protobuf.UnmodifiableLazyStringList( modulePath_); bitField0_ = (bitField0_ & ~0x00000080); } result.modulePath_ = modulePath_; result.bitField0_ = to_bitField0_; return result; } public Builder mergeFrom(org.jetbrains.jps.javac.JavacRemoteProto.Message.Request other) { if (other == org.jetbrains.jps.javac.JavacRemoteProto.Message.Request.getDefaultInstance()) return this; if (other.hasRequestType()) { setRequestType(other.getRequestType()); } if (!other.option_.isEmpty()) { if (option_.isEmpty()) { option_ = other.option_; bitField0_ = (bitField0_ & ~0x00000002); } else { ensureOptionIsMutable(); option_.addAll(other.option_); } } if (!other.file_.isEmpty()) { if (file_.isEmpty()) { file_ = other.file_; bitField0_ = (bitField0_ & ~0x00000004); } else { ensureFileIsMutable(); file_.addAll(other.file_); } } if (!other.platformClasspath_.isEmpty()) { if (platformClasspath_.isEmpty()) { platformClasspath_ = other.platformClasspath_; bitField0_ = (bitField0_ & ~0x00000008); } else { ensurePlatformClasspathIsMutable(); platformClasspath_.addAll(other.platformClasspath_); } } if (!other.classpath_.isEmpty()) { if (classpath_.isEmpty()) { classpath_ = other.classpath_; bitField0_ = (bitField0_ & ~0x00000010); } else { ensureClasspathIsMutable(); classpath_.addAll(other.classpath_); } } if (!other.sourcepath_.isEmpty()) { if (sourcepath_.isEmpty()) { sourcepath_ = other.sourcepath_; bitField0_ = (bitField0_ & ~0x00000020); } else { ensureSourcepathIsMutable(); sourcepath_.addAll(other.sourcepath_); } } if (!other.output_.isEmpty()) { if (output_.isEmpty()) { output_ = other.output_; bitField0_ = (bitField0_ & ~0x00000040); } else { ensureOutputIsMutable(); output_.addAll(other.output_); } } if (!other.modulePath_.isEmpty()) { if (modulePath_.isEmpty()) { modulePath_ = other.modulePath_; bitField0_ = (bitField0_ & ~0x00000080); } else { ensureModulePathIsMutable(); modulePath_.addAll(other.modulePath_); } } return this; } public final boolean isInitialized() { if (!hasRequestType()) { return false; } for (int i = 0; i < getOutputCount(); i++) { if (!getOutput(i).isInitialized()) { return false; } } return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { org.jetbrains.jps.javac.JavacRemoteProto.Message.Request parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (org.jetbrains.jps.javac.JavacRemoteProto.Message.Request) e.getUnfinishedMessage(); throw e; } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; // required .org.jetbrains.javac.Message.Request.Type request_type = 1; private org.jetbrains.jps.javac.JavacRemoteProto.Message.Request.Type requestType_ = org.jetbrains.jps.javac.JavacRemoteProto.Message.Request.Type.COMPILE; /** * <code>required .org.jetbrains.javac.Message.Request.Type request_type = 1;</code> */ public boolean hasRequestType() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * <code>required .org.jetbrains.javac.Message.Request.Type request_type = 1;</code> */ public org.jetbrains.jps.javac.JavacRemoteProto.Message.Request.Type getRequestType() { return requestType_; } /** * <code>required .org.jetbrains.javac.Message.Request.Type request_type = 1;</code> */ public Builder setRequestType(org.jetbrains.jps.javac.JavacRemoteProto.Message.Request.Type value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000001; requestType_ = value; return this; } /** * <code>required .org.jetbrains.javac.Message.Request.Type request_type = 1;</code> */ public Builder clearRequestType() { bitField0_ = (bitField0_ & ~0x00000001); requestType_ = org.jetbrains.jps.javac.JavacRemoteProto.Message.Request.Type.COMPILE; return this; } // repeated string option = 2; private com.google.protobuf.LazyStringList option_ = com.google.protobuf.LazyStringArrayList.EMPTY; private void ensureOptionIsMutable() { if (!((bitField0_ & 0x00000002) == 0x00000002)) { option_ = new com.google.protobuf.LazyStringArrayList(option_); bitField0_ |= 0x00000002; } } /** * <code>repeated string option = 2;</code> */ public java.util.List<java.lang.String> getOptionList() { return java.util.Collections.unmodifiableList(option_); } /** * <code>repeated string option = 2;</code> */ public int getOptionCount() { return option_.size(); } /** * <code>repeated string option = 2;</code> */ public java.lang.String getOption(int index) { return option_.get(index); } /** * <code>repeated string option = 2;</code> */ public com.google.protobuf.ByteString getOptionBytes(int index) { return option_.getByteString(index); } /** * <code>repeated string option = 2;</code> */ public Builder setOption( int index, java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureOptionIsMutable(); option_.set(index, value); return this; } /** * <code>repeated string option = 2;</code> */ public Builder addOption( java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureOptionIsMutable(); option_.add(value); return this; } /** * <code>repeated string option = 2;</code> */ public Builder addAllOption( java.lang.Iterable<java.lang.String> values) { ensureOptionIsMutable(); super.addAll(values, option_); return this; } /** * <code>repeated string option = 2;</code> */ public Builder clearOption() { option_ = com.google.protobuf.LazyStringArrayList.EMPTY; bitField0_ = (bitField0_ & ~0x00000002); return this; } /** * <code>repeated string option = 2;</code> */ public Builder addOptionBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } ensureOptionIsMutable(); option_.add(value); return this; } // repeated string file = 3; private com.google.protobuf.LazyStringList file_ = com.google.protobuf.LazyStringArrayList.EMPTY; private void ensureFileIsMutable() { if (!((bitField0_ & 0x00000004) == 0x00000004)) { file_ = new com.google.protobuf.LazyStringArrayList(file_); bitField0_ |= 0x00000004; } } /** * <code>repeated string file = 3;</code> */ public java.util.List<java.lang.String> getFileList() { return java.util.Collections.unmodifiableList(file_); } /** * <code>repeated string file = 3;</code> */ public int getFileCount() { return file_.size(); } /** * <code>repeated string file = 3;</code> */ public java.lang.String getFile(int index) { return file_.get(index); } /** * <code>repeated string file = 3;</code> */ public com.google.protobuf.ByteString getFileBytes(int index) { return file_.getByteString(index); } /** * <code>repeated string file = 3;</code> */ public Builder setFile( int index, java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureFileIsMutable(); file_.set(index, value); return this; } /** * <code>repeated string file = 3;</code> */ public Builder addFile( java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureFileIsMutable(); file_.add(value); return this; } /** * <code>repeated string file = 3;</code> */ public Builder addAllFile( java.lang.Iterable<java.lang.String> values) { ensureFileIsMutable(); super.addAll(values, file_); return this; } /** * <code>repeated string file = 3;</code> */ public Builder clearFile() { file_ = com.google.protobuf.LazyStringArrayList.EMPTY; bitField0_ = (bitField0_ & ~0x00000004); return this; } /** * <code>repeated string file = 3;</code> */ public Builder addFileBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } ensureFileIsMutable(); file_.add(value); return this; } // repeated string platform_classpath = 4; private com.google.protobuf.LazyStringList platformClasspath_ = com.google.protobuf.LazyStringArrayList.EMPTY; private void ensurePlatformClasspathIsMutable() { if (!((bitField0_ & 0x00000008) == 0x00000008)) { platformClasspath_ = new com.google.protobuf.LazyStringArrayList(platformClasspath_); bitField0_ |= 0x00000008; } } /** * <code>repeated string platform_classpath = 4;</code> */ public java.util.List<java.lang.String> getPlatformClasspathList() { return java.util.Collections.unmodifiableList(platformClasspath_); } /** * <code>repeated string platform_classpath = 4;</code> */ public int getPlatformClasspathCount() { return platformClasspath_.size(); } /** * <code>repeated string platform_classpath = 4;</code> */ public java.lang.String getPlatformClasspath(int index) { return platformClasspath_.get(index); } /** * <code>repeated string platform_classpath = 4;</code> */ public com.google.protobuf.ByteString getPlatformClasspathBytes(int index) { return platformClasspath_.getByteString(index); } /** * <code>repeated string platform_classpath = 4;</code> */ public Builder setPlatformClasspath( int index, java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensurePlatformClasspathIsMutable(); platformClasspath_.set(index, value); return this; } /** * <code>repeated string platform_classpath = 4;</code> */ public Builder addPlatformClasspath( java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensurePlatformClasspathIsMutable(); platformClasspath_.add(value); return this; } /** * <code>repeated string platform_classpath = 4;</code> */ public Builder addAllPlatformClasspath( java.lang.Iterable<java.lang.String> values) { ensurePlatformClasspathIsMutable(); super.addAll(values, platformClasspath_); return this; } /** * <code>repeated string platform_classpath = 4;</code> */ public Builder clearPlatformClasspath() { platformClasspath_ = com.google.protobuf.LazyStringArrayList.EMPTY; bitField0_ = (bitField0_ & ~0x00000008); return this; } /** * <code>repeated string platform_classpath = 4;</code> */ public Builder addPlatformClasspathBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } ensurePlatformClasspathIsMutable(); platformClasspath_.add(value); return this; } // repeated string classpath = 5; private com.google.protobuf.LazyStringList classpath_ = com.google.protobuf.LazyStringArrayList.EMPTY; private void ensureClasspathIsMutable() { if (!((bitField0_ & 0x00000010) == 0x00000010)) { classpath_ = new com.google.protobuf.LazyStringArrayList(classpath_); bitField0_ |= 0x00000010; } } /** * <code>repeated string classpath = 5;</code> */ public java.util.List<java.lang.String> getClasspathList() { return java.util.Collections.unmodifiableList(classpath_); } /** * <code>repeated string classpath = 5;</code> */ public int getClasspathCount() { return classpath_.size(); } /** * <code>repeated string classpath = 5;</code> */ public java.lang.String getClasspath(int index) { return classpath_.get(index); } /** * <code>repeated string classpath = 5;</code> */ public com.google.protobuf.ByteString getClasspathBytes(int index) { return classpath_.getByteString(index); } /** * <code>repeated string classpath = 5;</code> */ public Builder setClasspath( int index, java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureClasspathIsMutable(); classpath_.set(index, value); return this; } /** * <code>repeated string classpath = 5;</code> */ public Builder addClasspath( java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureClasspathIsMutable(); classpath_.add(value); return this; } /** * <code>repeated string classpath = 5;</code> */ public Builder addAllClasspath( java.lang.Iterable<java.lang.String> values) { ensureClasspathIsMutable(); super.addAll(values, classpath_); return this; } /** * <code>repeated string classpath = 5;</code> */ public Builder clearClasspath() { classpath_ = com.google.protobuf.LazyStringArrayList.EMPTY; bitField0_ = (bitField0_ & ~0x00000010); return this; } /** * <code>repeated string classpath = 5;</code> */ public Builder addClasspathBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } ensureClasspathIsMutable(); classpath_.add(value); return this; } // repeated string sourcepath = 6; private com.google.protobuf.LazyStringList sourcepath_ = com.google.protobuf.LazyStringArrayList.EMPTY; private void ensureSourcepathIsMutable() { if (!((bitField0_ & 0x00000020) == 0x00000020)) { sourcepath_ = new com.google.protobuf.LazyStringArrayList(sourcepath_); bitField0_ |= 0x00000020; } } /** * <code>repeated string sourcepath = 6;</code> */ public java.util.List<java.lang.String> getSourcepathList() { return java.util.Collections.unmodifiableList(sourcepath_); } /** * <code>repeated string sourcepath = 6;</code> */ public int getSourcepathCount() { return sourcepath_.size(); } /** * <code>repeated string sourcepath = 6;</code> */ public java.lang.String getSourcepath(int index) { return sourcepath_.get(index); } /** * <code>repeated string sourcepath = 6;</code> */ public com.google.protobuf.ByteString getSourcepathBytes(int index) { return sourcepath_.getByteString(index); } /** * <code>repeated string sourcepath = 6;</code> */ public Builder setSourcepath( int index, java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureSourcepathIsMutable(); sourcepath_.set(index, value); return this; } /** * <code>repeated string sourcepath = 6;</code> */ public Builder addSourcepath( java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureSourcepathIsMutable(); sourcepath_.add(value); return this; } /** * <code>repeated string sourcepath = 6;</code> */ public Builder addAllSourcepath( java.lang.Iterable<java.lang.String> values) { ensureSourcepathIsMutable(); super.addAll(values, sourcepath_); return this; } /** * <code>repeated string sourcepath = 6;</code> */ public Builder clearSourcepath() { sourcepath_ = com.google.protobuf.LazyStringArrayList.EMPTY; bitField0_ = (bitField0_ & ~0x00000020); return this; } /** * <code>repeated string sourcepath = 6;</code> */ public Builder addSourcepathBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } ensureSourcepathIsMutable(); sourcepath_.add(value); return this; } // repeated .org.jetbrains.javac.Message.Request.OutputGroup output = 7; private java.util.List<org.jetbrains.jps.javac.JavacRemoteProto.Message.Request.OutputGroup> output_ = java.util.Collections.emptyList(); private void ensureOutputIsMutable() { if (!((bitField0_ & 0x00000040) == 0x00000040)) { output_ = new java.util.ArrayList<org.jetbrains.jps.javac.JavacRemoteProto.Message.Request.OutputGroup>(output_); bitField0_ |= 0x00000040; } } /** * <code>repeated .org.jetbrains.javac.Message.Request.OutputGroup output = 7;</code> */ public java.util.List<org.jetbrains.jps.javac.JavacRemoteProto.Message.Request.OutputGroup> getOutputList() { return java.util.Collections.unmodifiableList(output_); } /** * <code>repeated .org.jetbrains.javac.Message.Request.OutputGroup output = 7;</code> */ public int getOutputCount() { return output_.size(); } /** * <code>repeated .org.jetbrains.javac.Message.Request.OutputGroup output = 7;</code> */ public org.jetbrains.jps.javac.JavacRemoteProto.Message.Request.OutputGroup getOutput(int index) { return output_.get(index); } /** * <code>repeated .org.jetbrains.javac.Message.Request.OutputGroup output = 7;</code> */ public Builder setOutput( int index, org.jetbrains.jps.javac.JavacRemoteProto.Message.Request.OutputGroup value) { if (value == null) { throw new NullPointerException(); } ensureOutputIsMutable(); output_.set(index, value); return this; } /** * <code>repeated .org.jetbrains.javac.Message.Request.OutputGroup output = 7;</code> */ public Builder setOutput( int index, org.jetbrains.jps.javac.JavacRemoteProto.Message.Request.OutputGroup.Builder builderForValue) { ensureOutputIsMutable(); output_.set(index, builderForValue.build()); return this; } /** * <code>repeated .org.jetbrains.javac.Message.Request.OutputGroup output = 7;</code> */ public Builder addOutput(org.jetbrains.jps.javac.JavacRemoteProto.Message.Request.OutputGroup value) { if (value == null) { throw new NullPointerException(); } ensureOutputIsMutable(); output_.add(value); return this; } /** * <code>repeated .org.jetbrains.javac.Message.Request.OutputGroup output = 7;</code> */ public Builder addOutput( int index, org.jetbrains.jps.javac.JavacRemoteProto.Message.Request.OutputGroup value) { if (value == null) { throw new NullPointerException(); } ensureOutputIsMutable(); output_.add(index, value); return this; } /** * <code>repeated .org.jetbrains.javac.Message.Request.OutputGroup output = 7;</code> */ public Builder addOutput( org.jetbrains.jps.javac.JavacRemoteProto.Message.Request.OutputGroup.Builder builderForValue) { ensureOutputIsMutable(); output_.add(builderForValue.build()); return this; } /** * <code>repeated .org.jetbrains.javac.Message.Request.OutputGroup output = 7;</code> */ public Builder addOutput( int index, org.jetbrains.jps.javac.JavacRemoteProto.Message.Request.OutputGroup.Builder builderForValue) { ensureOutputIsMutable(); output_.add(index, builderForValue.build()); return this; } /** * <code>repeated .org.jetbrains.javac.Message.Request.OutputGroup output = 7;</code> */ public Builder addAllOutput( java.lang.Iterable<? extends org.jetbrains.jps.javac.JavacRemoteProto.Message.Request.OutputGroup> values) { ensureOutputIsMutable(); super.addAll(values, output_); return this; } /** * <code>repeated .org.jetbrains.javac.Message.Request.OutputGroup output = 7;</code> */ public Builder clearOutput() { output_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000040); return this; } /** * <code>repeated .org.jetbrains.javac.Message.Request.OutputGroup output = 7;</code> */ public Builder removeOutput(int index) { ensureOutputIsMutable(); output_.remove(index); return this; } // repeated string module_path = 8; private com.google.protobuf.LazyStringList modulePath_ = com.google.protobuf.LazyStringArrayList.EMPTY; private void ensureModulePathIsMutable() { if (!((bitField0_ & 0x00000080) == 0x00000080)) { modulePath_ = new com.google.protobuf.LazyStringArrayList(modulePath_); bitField0_ |= 0x00000080; } } /** * <code>repeated string module_path = 8;</code> */ public java.util.List<java.lang.String> getModulePathList() { return java.util.Collections.unmodifiableList(modulePath_); } /** * <code>repeated string module_path = 8;</code> */ public int getModulePathCount() { return modulePath_.size(); } /** * <code>repeated string module_path = 8;</code> */ public java.lang.String getModulePath(int index) { return modulePath_.get(index); } /** * <code>repeated string module_path = 8;</code> */ public com.google.protobuf.ByteString getModulePathBytes(int index) { return modulePath_.getByteString(index); } /** * <code>repeated string module_path = 8;</code> */ public Builder setModulePath( int index, java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureModulePathIsMutable(); modulePath_.set(index, value); return this; } /** * <code>repeated string module_path = 8;</code> */ public Builder addModulePath( java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureModulePathIsMutable(); modulePath_.add(value); return this; } /** * <code>repeated string module_path = 8;</code> */ public Builder addAllModulePath( java.lang.Iterable<java.lang.String> values) { ensureModulePathIsMutable(); super.addAll(values, modulePath_); return this; } /** * <code>repeated string module_path = 8;</code> */ public Builder clearModulePath() { modulePath_ = com.google.protobuf.LazyStringArrayList.EMPTY; bitField0_ = (bitField0_ & ~0x00000080); return this; } /** * <code>repeated string module_path = 8;</code> */ public Builder addModulePathBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } ensureModulePathIsMutable(); modulePath_.add(value); return this; } // @@protoc_insertion_point(builder_scope:org.jetbrains.javac.Message.Request) } static { defaultInstance = new Request(true); defaultInstance.initFields(); } // @@protoc_insertion_point(class_scope:org.jetbrains.javac.Message.Request) } public interface ResponseOrBuilder extends com.google.protobuf.MessageLiteOrBuilder { // required .org.jetbrains.javac.Message.Response.Type response_type = 1; /** * <code>required .org.jetbrains.javac.Message.Response.Type response_type = 1;</code> */ boolean hasResponseType(); /** * <code>required .org.jetbrains.javac.Message.Response.Type response_type = 1;</code> */ org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.Type getResponseType(); // optional .org.jetbrains.javac.Message.Response.CompileMessage compile_message = 2; /** * <code>optional .org.jetbrains.javac.Message.Response.CompileMessage compile_message = 2;</code> */ boolean hasCompileMessage(); /** * <code>optional .org.jetbrains.javac.Message.Response.CompileMessage compile_message = 2;</code> */ org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.CompileMessage getCompileMessage(); // optional .org.jetbrains.javac.Message.Response.OutputObject output_object = 3; /** * <code>optional .org.jetbrains.javac.Message.Response.OutputObject output_object = 3;</code> */ boolean hasOutputObject(); /** * <code>optional .org.jetbrains.javac.Message.Response.OutputObject output_object = 3;</code> */ org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.OutputObject getOutputObject(); // optional .org.jetbrains.javac.Message.Response.ClassData class_data = 4; /** * <code>optional .org.jetbrains.javac.Message.Response.ClassData class_data = 4;</code> */ boolean hasClassData(); /** * <code>optional .org.jetbrains.javac.Message.Response.ClassData class_data = 4;</code> */ org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.ClassData getClassData(); // optional bool completion_status = 5; /** * <code>optional bool completion_status = 5;</code> */ boolean hasCompletionStatus(); /** * <code>optional bool completion_status = 5;</code> */ boolean getCompletionStatus(); } /** * Protobuf type {@code org.jetbrains.javac.Message.Response} */ public static final class Response extends com.google.protobuf.GeneratedMessageLite implements ResponseOrBuilder { // Use Response.newBuilder() to construct. private Response(com.google.protobuf.GeneratedMessageLite.Builder builder) { super(builder); } private Response(boolean noInit) {} private static final Response defaultInstance; public static Response getDefaultInstance() { return defaultInstance; } public Response getDefaultInstanceForType() { return defaultInstance; } private Response( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { initFields(); int mutable_bitField0_ = 0; try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownField(input, extensionRegistry, tag)) { done = true; } break; } case 8: { int rawValue = input.readEnum(); org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.Type value = org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.Type.valueOf(rawValue); if (value != null) { bitField0_ |= 0x00000001; responseType_ = value; } break; } case 18: { org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.CompileMessage.Builder subBuilder = null; if (((bitField0_ & 0x00000002) == 0x00000002)) { subBuilder = compileMessage_.toBuilder(); } compileMessage_ = input.readMessage(org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.CompileMessage.PARSER, extensionRegistry); if (subBuilder != null) { subBuilder.mergeFrom(compileMessage_); compileMessage_ = subBuilder.buildPartial(); } bitField0_ |= 0x00000002; break; } case 26: { org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.OutputObject.Builder subBuilder = null; if (((bitField0_ & 0x00000004) == 0x00000004)) { subBuilder = outputObject_.toBuilder(); } outputObject_ = input.readMessage(org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.OutputObject.PARSER, extensionRegistry); if (subBuilder != null) { subBuilder.mergeFrom(outputObject_); outputObject_ = subBuilder.buildPartial(); } bitField0_ |= 0x00000004; break; } case 34: { org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.ClassData.Builder subBuilder = null; if (((bitField0_ & 0x00000008) == 0x00000008)) { subBuilder = classData_.toBuilder(); } classData_ = input.readMessage(org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.ClassData.PARSER, extensionRegistry); if (subBuilder != null) { subBuilder.mergeFrom(classData_); classData_ = subBuilder.buildPartial(); } bitField0_ |= 0x00000008; break; } case 40: { bitField0_ |= 0x00000010; completionStatus_ = input.readBool(); break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e.getMessage()).setUnfinishedMessage(this); } finally { makeExtensionsImmutable(); } } public static com.google.protobuf.Parser<Response> PARSER = new com.google.protobuf.AbstractParser<Response>() { public Response parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new Response(input, extensionRegistry); } }; @java.lang.Override public com.google.protobuf.Parser<Response> getParserForType() { return PARSER; } /** * Protobuf enum {@code org.jetbrains.javac.Message.Response.Type} */ public enum Type implements com.google.protobuf.Internal.EnumLite { /** * <code>BUILD_MESSAGE = 1;</code> */ BUILD_MESSAGE(0, 1), /** * <code>OUTPUT_OBJECT = 2;</code> */ OUTPUT_OBJECT(1, 2), /** * <code>CLASS_DATA = 3;</code> */ CLASS_DATA(2, 3), /** * <code>BUILD_COMPLETED = 4;</code> */ BUILD_COMPLETED(3, 4), /** * <code>REQUEST_ACK = 5;</code> */ REQUEST_ACK(4, 5), /** * <code>SRC_FILE_LOADED = 6;</code> */ SRC_FILE_LOADED(5, 6), /** * <code>CUSTOM_OUTPUT_OBJECT = 7;</code> */ CUSTOM_OUTPUT_OBJECT(6, 7), ; /** * <code>BUILD_MESSAGE = 1;</code> */ public static final int BUILD_MESSAGE_VALUE = 1; /** * <code>OUTPUT_OBJECT = 2;</code> */ public static final int OUTPUT_OBJECT_VALUE = 2; /** * <code>CLASS_DATA = 3;</code> */ public static final int CLASS_DATA_VALUE = 3; /** * <code>BUILD_COMPLETED = 4;</code> */ public static final int BUILD_COMPLETED_VALUE = 4; /** * <code>REQUEST_ACK = 5;</code> */ public static final int REQUEST_ACK_VALUE = 5; /** * <code>SRC_FILE_LOADED = 6;</code> */ public static final int SRC_FILE_LOADED_VALUE = 6; /** * <code>CUSTOM_OUTPUT_OBJECT = 7;</code> */ public static final int CUSTOM_OUTPUT_OBJECT_VALUE = 7; public final int getNumber() { return value; } public static Type valueOf(int value) { switch (value) { case 1: return BUILD_MESSAGE; case 2: return OUTPUT_OBJECT; case 3: return CLASS_DATA; case 4: return BUILD_COMPLETED; case 5: return REQUEST_ACK; case 6: return SRC_FILE_LOADED; case 7: return CUSTOM_OUTPUT_OBJECT; default: return null; } } public static com.google.protobuf.Internal.EnumLiteMap<Type> internalGetValueMap() { return internalValueMap; } private static com.google.protobuf.Internal.EnumLiteMap<Type> internalValueMap = new com.google.protobuf.Internal.EnumLiteMap<Type>() { public Type findValueByNumber(int number) { return Type.valueOf(number); } }; private final int value; private Type(int index, int value) { this.value = value; } // @@protoc_insertion_point(enum_scope:org.jetbrains.javac.Message.Response.Type) } public interface CompileMessageOrBuilder extends com.google.protobuf.MessageLiteOrBuilder { // required .org.jetbrains.javac.Message.Response.CompileMessage.Kind kind = 1; /** * <code>required .org.jetbrains.javac.Message.Response.CompileMessage.Kind kind = 1;</code> */ boolean hasKind(); /** * <code>required .org.jetbrains.javac.Message.Response.CompileMessage.Kind kind = 1;</code> */ org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.CompileMessage.Kind getKind(); // optional string text = 2; /** * <code>optional string text = 2;</code> */ boolean hasText(); /** * <code>optional string text = 2;</code> */ java.lang.String getText(); /** * <code>optional string text = 2;</code> */ com.google.protobuf.ByteString getTextBytes(); // optional string source_uri = 3; /** * <code>optional string source_uri = 3;</code> */ boolean hasSourceUri(); /** * <code>optional string source_uri = 3;</code> */ java.lang.String getSourceUri(); /** * <code>optional string source_uri = 3;</code> */ com.google.protobuf.ByteString getSourceUriBytes(); // optional uint64 problem_begin_offset = 4; /** * <code>optional uint64 problem_begin_offset = 4;</code> */ boolean hasProblemBeginOffset(); /** * <code>optional uint64 problem_begin_offset = 4;</code> */ long getProblemBeginOffset(); // optional uint64 problem_end_offset = 5; /** * <code>optional uint64 problem_end_offset = 5;</code> */ boolean hasProblemEndOffset(); /** * <code>optional uint64 problem_end_offset = 5;</code> */ long getProblemEndOffset(); // optional uint64 problem_location_offset = 6; /** * <code>optional uint64 problem_location_offset = 6;</code> */ boolean hasProblemLocationOffset(); /** * <code>optional uint64 problem_location_offset = 6;</code> */ long getProblemLocationOffset(); // optional uint64 line = 7; /** * <code>optional uint64 line = 7;</code> */ boolean hasLine(); /** * <code>optional uint64 line = 7;</code> */ long getLine(); // optional uint64 column = 8; /** * <code>optional uint64 column = 8;</code> */ boolean hasColumn(); /** * <code>optional uint64 column = 8;</code> */ long getColumn(); } /** * Protobuf type {@code org.jetbrains.javac.Message.Response.CompileMessage} */ public static final class CompileMessage extends com.google.protobuf.GeneratedMessageLite implements CompileMessageOrBuilder { // Use CompileMessage.newBuilder() to construct. private CompileMessage(com.google.protobuf.GeneratedMessageLite.Builder builder) { super(builder); } private CompileMessage(boolean noInit) {} private static final CompileMessage defaultInstance; public static CompileMessage getDefaultInstance() { return defaultInstance; } public CompileMessage getDefaultInstanceForType() { return defaultInstance; } private CompileMessage( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { initFields(); int mutable_bitField0_ = 0; try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownField(input, extensionRegistry, tag)) { done = true; } break; } case 8: { int rawValue = input.readEnum(); org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.CompileMessage.Kind value = org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.CompileMessage.Kind.valueOf(rawValue); if (value != null) { bitField0_ |= 0x00000001; kind_ = value; } break; } case 18: { bitField0_ |= 0x00000002; text_ = input.readBytes(); break; } case 26: { bitField0_ |= 0x00000004; sourceUri_ = input.readBytes(); break; } case 32: { bitField0_ |= 0x00000008; problemBeginOffset_ = input.readUInt64(); break; } case 40: { bitField0_ |= 0x00000010; problemEndOffset_ = input.readUInt64(); break; } case 48: { bitField0_ |= 0x00000020; problemLocationOffset_ = input.readUInt64(); break; } case 56: { bitField0_ |= 0x00000040; line_ = input.readUInt64(); break; } case 64: { bitField0_ |= 0x00000080; column_ = input.readUInt64(); break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e.getMessage()).setUnfinishedMessage(this); } finally { makeExtensionsImmutable(); } } public static com.google.protobuf.Parser<CompileMessage> PARSER = new com.google.protobuf.AbstractParser<CompileMessage>() { public CompileMessage parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new CompileMessage(input, extensionRegistry); } }; @java.lang.Override public com.google.protobuf.Parser<CompileMessage> getParserForType() { return PARSER; } /** * Protobuf enum {@code org.jetbrains.javac.Message.Response.CompileMessage.Kind} */ public enum Kind implements com.google.protobuf.Internal.EnumLite { /** * <code>ERROR = 1;</code> */ ERROR(0, 1), /** * <code>WARNING = 2;</code> */ WARNING(1, 2), /** * <code>MANDATORY_WARNING = 3;</code> */ MANDATORY_WARNING(2, 3), /** * <code>NOTE = 4;</code> */ NOTE(3, 4), /** * <code>OTHER = 5;</code> */ OTHER(4, 5), /** * <code>STD_OUT = 6;</code> */ STD_OUT(5, 6), ; /** * <code>ERROR = 1;</code> */ public static final int ERROR_VALUE = 1; /** * <code>WARNING = 2;</code> */ public static final int WARNING_VALUE = 2; /** * <code>MANDATORY_WARNING = 3;</code> */ public static final int MANDATORY_WARNING_VALUE = 3; /** * <code>NOTE = 4;</code> */ public static final int NOTE_VALUE = 4; /** * <code>OTHER = 5;</code> */ public static final int OTHER_VALUE = 5; /** * <code>STD_OUT = 6;</code> */ public static final int STD_OUT_VALUE = 6; public final int getNumber() { return value; } public static Kind valueOf(int value) { switch (value) { case 1: return ERROR; case 2: return WARNING; case 3: return MANDATORY_WARNING; case 4: return NOTE; case 5: return OTHER; case 6: return STD_OUT; default: return null; } } public static com.google.protobuf.Internal.EnumLiteMap<Kind> internalGetValueMap() { return internalValueMap; } private static com.google.protobuf.Internal.EnumLiteMap<Kind> internalValueMap = new com.google.protobuf.Internal.EnumLiteMap<Kind>() { public Kind findValueByNumber(int number) { return Kind.valueOf(number); } }; private final int value; private Kind(int index, int value) { this.value = value; } // @@protoc_insertion_point(enum_scope:org.jetbrains.javac.Message.Response.CompileMessage.Kind) } private int bitField0_; // required .org.jetbrains.javac.Message.Response.CompileMessage.Kind kind = 1; public static final int KIND_FIELD_NUMBER = 1; private org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.CompileMessage.Kind kind_; /** * <code>required .org.jetbrains.javac.Message.Response.CompileMessage.Kind kind = 1;</code> */ public boolean hasKind() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * <code>required .org.jetbrains.javac.Message.Response.CompileMessage.Kind kind = 1;</code> */ public org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.CompileMessage.Kind getKind() { return kind_; } // optional string text = 2; public static final int TEXT_FIELD_NUMBER = 2; private java.lang.Object text_; /** * <code>optional string text = 2;</code> */ public boolean hasText() { return ((bitField0_ & 0x00000002) == 0x00000002); } /** * <code>optional string text = 2;</code> */ public java.lang.String getText() { java.lang.Object ref = text_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { text_ = s; } return s; } } /** * <code>optional string text = 2;</code> */ public com.google.protobuf.ByteString getTextBytes() { java.lang.Object ref = text_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); text_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } // optional string source_uri = 3; public static final int SOURCE_URI_FIELD_NUMBER = 3; private java.lang.Object sourceUri_; /** * <code>optional string source_uri = 3;</code> */ public boolean hasSourceUri() { return ((bitField0_ & 0x00000004) == 0x00000004); } /** * <code>optional string source_uri = 3;</code> */ public java.lang.String getSourceUri() { java.lang.Object ref = sourceUri_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { sourceUri_ = s; } return s; } } /** * <code>optional string source_uri = 3;</code> */ public com.google.protobuf.ByteString getSourceUriBytes() { java.lang.Object ref = sourceUri_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); sourceUri_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } // optional uint64 problem_begin_offset = 4; public static final int PROBLEM_BEGIN_OFFSET_FIELD_NUMBER = 4; private long problemBeginOffset_; /** * <code>optional uint64 problem_begin_offset = 4;</code> */ public boolean hasProblemBeginOffset() { return ((bitField0_ & 0x00000008) == 0x00000008); } /** * <code>optional uint64 problem_begin_offset = 4;</code> */ public long getProblemBeginOffset() { return problemBeginOffset_; } // optional uint64 problem_end_offset = 5; public static final int PROBLEM_END_OFFSET_FIELD_NUMBER = 5; private long problemEndOffset_; /** * <code>optional uint64 problem_end_offset = 5;</code> */ public boolean hasProblemEndOffset() { return ((bitField0_ & 0x00000010) == 0x00000010); } /** * <code>optional uint64 problem_end_offset = 5;</code> */ public long getProblemEndOffset() { return problemEndOffset_; } // optional uint64 problem_location_offset = 6; public static final int PROBLEM_LOCATION_OFFSET_FIELD_NUMBER = 6; private long problemLocationOffset_; /** * <code>optional uint64 problem_location_offset = 6;</code> */ public boolean hasProblemLocationOffset() { return ((bitField0_ & 0x00000020) == 0x00000020); } /** * <code>optional uint64 problem_location_offset = 6;</code> */ public long getProblemLocationOffset() { return problemLocationOffset_; } // optional uint64 line = 7; public static final int LINE_FIELD_NUMBER = 7; private long line_; /** * <code>optional uint64 line = 7;</code> */ public boolean hasLine() { return ((bitField0_ & 0x00000040) == 0x00000040); } /** * <code>optional uint64 line = 7;</code> */ public long getLine() { return line_; } // optional uint64 column = 8; public static final int COLUMN_FIELD_NUMBER = 8; private long column_; /** * <code>optional uint64 column = 8;</code> */ public boolean hasColumn() { return ((bitField0_ & 0x00000080) == 0x00000080); } /** * <code>optional uint64 column = 8;</code> */ public long getColumn() { return column_; } private void initFields() { kind_ = org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.CompileMessage.Kind.ERROR; text_ = ""; sourceUri_ = ""; problemBeginOffset_ = 0L; problemEndOffset_ = 0L; problemLocationOffset_ = 0L; line_ = 0L; column_ = 0L; } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized != -1) return isInitialized == 1; if (!hasKind()) { memoizedIsInitialized = 0; return false; } memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getSerializedSize(); if (((bitField0_ & 0x00000001) == 0x00000001)) { output.writeEnum(1, kind_.getNumber()); } if (((bitField0_ & 0x00000002) == 0x00000002)) { output.writeBytes(2, getTextBytes()); } if (((bitField0_ & 0x00000004) == 0x00000004)) { output.writeBytes(3, getSourceUriBytes()); } if (((bitField0_ & 0x00000008) == 0x00000008)) { output.writeUInt64(4, problemBeginOffset_); } if (((bitField0_ & 0x00000010) == 0x00000010)) { output.writeUInt64(5, problemEndOffset_); } if (((bitField0_ & 0x00000020) == 0x00000020)) { output.writeUInt64(6, problemLocationOffset_); } if (((bitField0_ & 0x00000040) == 0x00000040)) { output.writeUInt64(7, line_); } if (((bitField0_ & 0x00000080) == 0x00000080)) { output.writeUInt64(8, column_); } } private int memoizedSerializedSize = -1; public int getSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; if (((bitField0_ & 0x00000001) == 0x00000001)) { size += com.google.protobuf.CodedOutputStream .computeEnumSize(1, kind_.getNumber()); } if (((bitField0_ & 0x00000002) == 0x00000002)) { size += com.google.protobuf.CodedOutputStream .computeBytesSize(2, getTextBytes()); } if (((bitField0_ & 0x00000004) == 0x00000004)) { size += com.google.protobuf.CodedOutputStream .computeBytesSize(3, getSourceUriBytes()); } if (((bitField0_ & 0x00000008) == 0x00000008)) { size += com.google.protobuf.CodedOutputStream .computeUInt64Size(4, problemBeginOffset_); } if (((bitField0_ & 0x00000010) == 0x00000010)) { size += com.google.protobuf.CodedOutputStream .computeUInt64Size(5, problemEndOffset_); } if (((bitField0_ & 0x00000020) == 0x00000020)) { size += com.google.protobuf.CodedOutputStream .computeUInt64Size(6, problemLocationOffset_); } if (((bitField0_ & 0x00000040) == 0x00000040)) { size += com.google.protobuf.CodedOutputStream .computeUInt64Size(7, line_); } if (((bitField0_ & 0x00000080) == 0x00000080)) { size += com.google.protobuf.CodedOutputStream .computeUInt64Size(8, column_); } memoizedSerializedSize = size; return size; } private static final long serialVersionUID = 0L; @java.lang.Override protected java.lang.Object writeReplace() throws java.io.ObjectStreamException { return super.writeReplace(); } public static org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.CompileMessage parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.CompileMessage parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.CompileMessage parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.CompileMessage parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.CompileMessage parseFrom(java.io.InputStream input) throws java.io.IOException { return PARSER.parseFrom(input); } public static org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.CompileMessage parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } public static org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.CompileMessage parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return PARSER.parseDelimitedFrom(input); } public static org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.CompileMessage parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseDelimitedFrom(input, extensionRegistry); } public static org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.CompileMessage parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return PARSER.parseFrom(input); } public static org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.CompileMessage parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } public static Builder newBuilder() { return Builder.create(); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder(org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.CompileMessage prototype) { return newBuilder().mergeFrom(prototype); } public Builder toBuilder() { return newBuilder(this); } /** * Protobuf type {@code org.jetbrains.javac.Message.Response.CompileMessage} */ public static final class Builder extends com.google.protobuf.GeneratedMessageLite.Builder< org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.CompileMessage, Builder> implements org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.CompileMessageOrBuilder { // Construct using org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.CompileMessage.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { } private static Builder create() { return new Builder(); } public Builder clear() { super.clear(); kind_ = org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.CompileMessage.Kind.ERROR; bitField0_ = (bitField0_ & ~0x00000001); text_ = ""; bitField0_ = (bitField0_ & ~0x00000002); sourceUri_ = ""; bitField0_ = (bitField0_ & ~0x00000004); problemBeginOffset_ = 0L; bitField0_ = (bitField0_ & ~0x00000008); problemEndOffset_ = 0L; bitField0_ = (bitField0_ & ~0x00000010); problemLocationOffset_ = 0L; bitField0_ = (bitField0_ & ~0x00000020); line_ = 0L; bitField0_ = (bitField0_ & ~0x00000040); column_ = 0L; bitField0_ = (bitField0_ & ~0x00000080); return this; } public Builder clone() { return create().mergeFrom(buildPartial()); } public org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.CompileMessage getDefaultInstanceForType() { return org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.CompileMessage.getDefaultInstance(); } public org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.CompileMessage build() { org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.CompileMessage result = buildPartial(); if (!result.isInitialized()) { throw Builder.newUninitializedMessageException(result); } return result; } public org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.CompileMessage buildPartial() { org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.CompileMessage result = new org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.CompileMessage(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) == 0x00000001)) { to_bitField0_ |= 0x00000001; } result.kind_ = kind_; if (((from_bitField0_ & 0x00000002) == 0x00000002)) { to_bitField0_ |= 0x00000002; } result.text_ = text_; if (((from_bitField0_ & 0x00000004) == 0x00000004)) { to_bitField0_ |= 0x00000004; } result.sourceUri_ = sourceUri_; if (((from_bitField0_ & 0x00000008) == 0x00000008)) { to_bitField0_ |= 0x00000008; } result.problemBeginOffset_ = problemBeginOffset_; if (((from_bitField0_ & 0x00000010) == 0x00000010)) { to_bitField0_ |= 0x00000010; } result.problemEndOffset_ = problemEndOffset_; if (((from_bitField0_ & 0x00000020) == 0x00000020)) { to_bitField0_ |= 0x00000020; } result.problemLocationOffset_ = problemLocationOffset_; if (((from_bitField0_ & 0x00000040) == 0x00000040)) { to_bitField0_ |= 0x00000040; } result.line_ = line_; if (((from_bitField0_ & 0x00000080) == 0x00000080)) { to_bitField0_ |= 0x00000080; } result.column_ = column_; result.bitField0_ = to_bitField0_; return result; } public Builder mergeFrom(org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.CompileMessage other) { if (other == org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.CompileMessage.getDefaultInstance()) return this; if (other.hasKind()) { setKind(other.getKind()); } if (other.hasText()) { bitField0_ |= 0x00000002; text_ = other.text_; } if (other.hasSourceUri()) { bitField0_ |= 0x00000004; sourceUri_ = other.sourceUri_; } if (other.hasProblemBeginOffset()) { setProblemBeginOffset(other.getProblemBeginOffset()); } if (other.hasProblemEndOffset()) { setProblemEndOffset(other.getProblemEndOffset()); } if (other.hasProblemLocationOffset()) { setProblemLocationOffset(other.getProblemLocationOffset()); } if (other.hasLine()) { setLine(other.getLine()); } if (other.hasColumn()) { setColumn(other.getColumn()); } return this; } public final boolean isInitialized() { if (!hasKind()) { return false; } return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.CompileMessage parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.CompileMessage) e.getUnfinishedMessage(); throw e; } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; // required .org.jetbrains.javac.Message.Response.CompileMessage.Kind kind = 1; private org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.CompileMessage.Kind kind_ = org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.CompileMessage.Kind.ERROR; /** * <code>required .org.jetbrains.javac.Message.Response.CompileMessage.Kind kind = 1;</code> */ public boolean hasKind() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * <code>required .org.jetbrains.javac.Message.Response.CompileMessage.Kind kind = 1;</code> */ public org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.CompileMessage.Kind getKind() { return kind_; } /** * <code>required .org.jetbrains.javac.Message.Response.CompileMessage.Kind kind = 1;</code> */ public Builder setKind(org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.CompileMessage.Kind value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000001; kind_ = value; return this; } /** * <code>required .org.jetbrains.javac.Message.Response.CompileMessage.Kind kind = 1;</code> */ public Builder clearKind() { bitField0_ = (bitField0_ & ~0x00000001); kind_ = org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.CompileMessage.Kind.ERROR; return this; } // optional string text = 2; private java.lang.Object text_ = ""; /** * <code>optional string text = 2;</code> */ public boolean hasText() { return ((bitField0_ & 0x00000002) == 0x00000002); } /** * <code>optional string text = 2;</code> */ public java.lang.String getText() { java.lang.Object ref = text_; if (!(ref instanceof java.lang.String)) { java.lang.String s = ((com.google.protobuf.ByteString) ref) .toStringUtf8(); text_ = s; return s; } else { return (java.lang.String) ref; } } /** * <code>optional string text = 2;</code> */ public com.google.protobuf.ByteString getTextBytes() { java.lang.Object ref = text_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); text_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <code>optional string text = 2;</code> */ public Builder setText( java.lang.String value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000002; text_ = value; return this; } /** * <code>optional string text = 2;</code> */ public Builder clearText() { bitField0_ = (bitField0_ & ~0x00000002); text_ = getDefaultInstance().getText(); return this; } /** * <code>optional string text = 2;</code> */ public Builder setTextBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000002; text_ = value; return this; } // optional string source_uri = 3; private java.lang.Object sourceUri_ = ""; /** * <code>optional string source_uri = 3;</code> */ public boolean hasSourceUri() { return ((bitField0_ & 0x00000004) == 0x00000004); } /** * <code>optional string source_uri = 3;</code> */ public java.lang.String getSourceUri() { java.lang.Object ref = sourceUri_; if (!(ref instanceof java.lang.String)) { java.lang.String s = ((com.google.protobuf.ByteString) ref) .toStringUtf8(); sourceUri_ = s; return s; } else { return (java.lang.String) ref; } } /** * <code>optional string source_uri = 3;</code> */ public com.google.protobuf.ByteString getSourceUriBytes() { java.lang.Object ref = sourceUri_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); sourceUri_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <code>optional string source_uri = 3;</code> */ public Builder setSourceUri( java.lang.String value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000004; sourceUri_ = value; return this; } /** * <code>optional string source_uri = 3;</code> */ public Builder clearSourceUri() { bitField0_ = (bitField0_ & ~0x00000004); sourceUri_ = getDefaultInstance().getSourceUri(); return this; } /** * <code>optional string source_uri = 3;</code> */ public Builder setSourceUriBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000004; sourceUri_ = value; return this; } // optional uint64 problem_begin_offset = 4; private long problemBeginOffset_ ; /** * <code>optional uint64 problem_begin_offset = 4;</code> */ public boolean hasProblemBeginOffset() { return ((bitField0_ & 0x00000008) == 0x00000008); } /** * <code>optional uint64 problem_begin_offset = 4;</code> */ public long getProblemBeginOffset() { return problemBeginOffset_; } /** * <code>optional uint64 problem_begin_offset = 4;</code> */ public Builder setProblemBeginOffset(long value) { bitField0_ |= 0x00000008; problemBeginOffset_ = value; return this; } /** * <code>optional uint64 problem_begin_offset = 4;</code> */ public Builder clearProblemBeginOffset() { bitField0_ = (bitField0_ & ~0x00000008); problemBeginOffset_ = 0L; return this; } // optional uint64 problem_end_offset = 5; private long problemEndOffset_ ; /** * <code>optional uint64 problem_end_offset = 5;</code> */ public boolean hasProblemEndOffset() { return ((bitField0_ & 0x00000010) == 0x00000010); } /** * <code>optional uint64 problem_end_offset = 5;</code> */ public long getProblemEndOffset() { return problemEndOffset_; } /** * <code>optional uint64 problem_end_offset = 5;</code> */ public Builder setProblemEndOffset(long value) { bitField0_ |= 0x00000010; problemEndOffset_ = value; return this; } /** * <code>optional uint64 problem_end_offset = 5;</code> */ public Builder clearProblemEndOffset() { bitField0_ = (bitField0_ & ~0x00000010); problemEndOffset_ = 0L; return this; } // optional uint64 problem_location_offset = 6; private long problemLocationOffset_ ; /** * <code>optional uint64 problem_location_offset = 6;</code> */ public boolean hasProblemLocationOffset() { return ((bitField0_ & 0x00000020) == 0x00000020); } /** * <code>optional uint64 problem_location_offset = 6;</code> */ public long getProblemLocationOffset() { return problemLocationOffset_; } /** * <code>optional uint64 problem_location_offset = 6;</code> */ public Builder setProblemLocationOffset(long value) { bitField0_ |= 0x00000020; problemLocationOffset_ = value; return this; } /** * <code>optional uint64 problem_location_offset = 6;</code> */ public Builder clearProblemLocationOffset() { bitField0_ = (bitField0_ & ~0x00000020); problemLocationOffset_ = 0L; return this; } // optional uint64 line = 7; private long line_ ; /** * <code>optional uint64 line = 7;</code> */ public boolean hasLine() { return ((bitField0_ & 0x00000040) == 0x00000040); } /** * <code>optional uint64 line = 7;</code> */ public long getLine() { return line_; } /** * <code>optional uint64 line = 7;</code> */ public Builder setLine(long value) { bitField0_ |= 0x00000040; line_ = value; return this; } /** * <code>optional uint64 line = 7;</code> */ public Builder clearLine() { bitField0_ = (bitField0_ & ~0x00000040); line_ = 0L; return this; } // optional uint64 column = 8; private long column_ ; /** * <code>optional uint64 column = 8;</code> */ public boolean hasColumn() { return ((bitField0_ & 0x00000080) == 0x00000080); } /** * <code>optional uint64 column = 8;</code> */ public long getColumn() { return column_; } /** * <code>optional uint64 column = 8;</code> */ public Builder setColumn(long value) { bitField0_ |= 0x00000080; column_ = value; return this; } /** * <code>optional uint64 column = 8;</code> */ public Builder clearColumn() { bitField0_ = (bitField0_ & ~0x00000080); column_ = 0L; return this; } // @@protoc_insertion_point(builder_scope:org.jetbrains.javac.Message.Response.CompileMessage) } static { defaultInstance = new CompileMessage(true); defaultInstance.initFields(); } // @@protoc_insertion_point(class_scope:org.jetbrains.javac.Message.Response.CompileMessage) } public interface OutputObjectOrBuilder extends com.google.protobuf.MessageLiteOrBuilder { // required .org.jetbrains.javac.Message.Response.OutputObject.Kind kind = 1; /** * <code>required .org.jetbrains.javac.Message.Response.OutputObject.Kind kind = 1;</code> */ boolean hasKind(); /** * <code>required .org.jetbrains.javac.Message.Response.OutputObject.Kind kind = 1;</code> */ org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.OutputObject.Kind getKind(); // required string file_path = 2; /** * <code>required string file_path = 2;</code> */ boolean hasFilePath(); /** * <code>required string file_path = 2;</code> */ java.lang.String getFilePath(); /** * <code>required string file_path = 2;</code> */ com.google.protobuf.ByteString getFilePathBytes(); // optional string output_root = 3; /** * <code>optional string output_root = 3;</code> */ boolean hasOutputRoot(); /** * <code>optional string output_root = 3;</code> */ java.lang.String getOutputRoot(); /** * <code>optional string output_root = 3;</code> */ com.google.protobuf.ByteString getOutputRootBytes(); // optional string relative_path = 4; /** * <code>optional string relative_path = 4;</code> */ boolean hasRelativePath(); /** * <code>optional string relative_path = 4;</code> */ java.lang.String getRelativePath(); /** * <code>optional string relative_path = 4;</code> */ com.google.protobuf.ByteString getRelativePathBytes(); // optional string class_name = 5; /** * <code>optional string class_name = 5;</code> */ boolean hasClassName(); /** * <code>optional string class_name = 5;</code> */ java.lang.String getClassName(); /** * <code>optional string class_name = 5;</code> */ com.google.protobuf.ByteString getClassNameBytes(); // optional string source_uri = 6; /** * <code>optional string source_uri = 6;</code> */ boolean hasSourceUri(); /** * <code>optional string source_uri = 6;</code> */ java.lang.String getSourceUri(); /** * <code>optional string source_uri = 6;</code> */ com.google.protobuf.ByteString getSourceUriBytes(); // optional bytes content = 7; /** * <code>optional bytes content = 7;</code> */ boolean hasContent(); /** * <code>optional bytes content = 7;</code> */ com.google.protobuf.ByteString getContent(); } /** * Protobuf type {@code org.jetbrains.javac.Message.Response.OutputObject} */ public static final class OutputObject extends com.google.protobuf.GeneratedMessageLite implements OutputObjectOrBuilder { // Use OutputObject.newBuilder() to construct. private OutputObject(com.google.protobuf.GeneratedMessageLite.Builder builder) { super(builder); } private OutputObject(boolean noInit) {} private static final OutputObject defaultInstance; public static OutputObject getDefaultInstance() { return defaultInstance; } public OutputObject getDefaultInstanceForType() { return defaultInstance; } private OutputObject( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { initFields(); int mutable_bitField0_ = 0; try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownField(input, extensionRegistry, tag)) { done = true; } break; } case 8: { int rawValue = input.readEnum(); org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.OutputObject.Kind value = org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.OutputObject.Kind.valueOf(rawValue); if (value != null) { bitField0_ |= 0x00000001; kind_ = value; } break; } case 18: { bitField0_ |= 0x00000002; filePath_ = input.readBytes(); break; } case 26: { bitField0_ |= 0x00000004; outputRoot_ = input.readBytes(); break; } case 34: { bitField0_ |= 0x00000008; relativePath_ = input.readBytes(); break; } case 42: { bitField0_ |= 0x00000010; className_ = input.readBytes(); break; } case 50: { bitField0_ |= 0x00000020; sourceUri_ = input.readBytes(); break; } case 58: { bitField0_ |= 0x00000040; content_ = input.readBytes(); break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e.getMessage()).setUnfinishedMessage(this); } finally { makeExtensionsImmutable(); } } public static com.google.protobuf.Parser<OutputObject> PARSER = new com.google.protobuf.AbstractParser<OutputObject>() { public OutputObject parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new OutputObject(input, extensionRegistry); } }; @java.lang.Override public com.google.protobuf.Parser<OutputObject> getParserForType() { return PARSER; } /** * Protobuf enum {@code org.jetbrains.javac.Message.Response.OutputObject.Kind} */ public enum Kind implements com.google.protobuf.Internal.EnumLite { /** * <code>SOURCE = 1;</code> */ SOURCE(0, 1), /** * <code>CLASS = 2;</code> */ CLASS(1, 2), /** * <code>HTML = 3;</code> */ HTML(2, 3), /** * <code>OTHER = 4;</code> */ OTHER(3, 4), ; /** * <code>SOURCE = 1;</code> */ public static final int SOURCE_VALUE = 1; /** * <code>CLASS = 2;</code> */ public static final int CLASS_VALUE = 2; /** * <code>HTML = 3;</code> */ public static final int HTML_VALUE = 3; /** * <code>OTHER = 4;</code> */ public static final int OTHER_VALUE = 4; public final int getNumber() { return value; } public static Kind valueOf(int value) { switch (value) { case 1: return SOURCE; case 2: return CLASS; case 3: return HTML; case 4: return OTHER; default: return null; } } public static com.google.protobuf.Internal.EnumLiteMap<Kind> internalGetValueMap() { return internalValueMap; } private static com.google.protobuf.Internal.EnumLiteMap<Kind> internalValueMap = new com.google.protobuf.Internal.EnumLiteMap<Kind>() { public Kind findValueByNumber(int number) { return Kind.valueOf(number); } }; private final int value; private Kind(int index, int value) { this.value = value; } // @@protoc_insertion_point(enum_scope:org.jetbrains.javac.Message.Response.OutputObject.Kind) } private int bitField0_; // required .org.jetbrains.javac.Message.Response.OutputObject.Kind kind = 1; public static final int KIND_FIELD_NUMBER = 1; private org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.OutputObject.Kind kind_; /** * <code>required .org.jetbrains.javac.Message.Response.OutputObject.Kind kind = 1;</code> */ public boolean hasKind() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * <code>required .org.jetbrains.javac.Message.Response.OutputObject.Kind kind = 1;</code> */ public org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.OutputObject.Kind getKind() { return kind_; } // required string file_path = 2; public static final int FILE_PATH_FIELD_NUMBER = 2; private java.lang.Object filePath_; /** * <code>required string file_path = 2;</code> */ public boolean hasFilePath() { return ((bitField0_ & 0x00000002) == 0x00000002); } /** * <code>required string file_path = 2;</code> */ public java.lang.String getFilePath() { java.lang.Object ref = filePath_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { filePath_ = s; } return s; } } /** * <code>required string file_path = 2;</code> */ public com.google.protobuf.ByteString getFilePathBytes() { java.lang.Object ref = filePath_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); filePath_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } // optional string output_root = 3; public static final int OUTPUT_ROOT_FIELD_NUMBER = 3; private java.lang.Object outputRoot_; /** * <code>optional string output_root = 3;</code> */ public boolean hasOutputRoot() { return ((bitField0_ & 0x00000004) == 0x00000004); } /** * <code>optional string output_root = 3;</code> */ public java.lang.String getOutputRoot() { java.lang.Object ref = outputRoot_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { outputRoot_ = s; } return s; } } /** * <code>optional string output_root = 3;</code> */ public com.google.protobuf.ByteString getOutputRootBytes() { java.lang.Object ref = outputRoot_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); outputRoot_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } // optional string relative_path = 4; public static final int RELATIVE_PATH_FIELD_NUMBER = 4; private java.lang.Object relativePath_; /** * <code>optional string relative_path = 4;</code> */ public boolean hasRelativePath() { return ((bitField0_ & 0x00000008) == 0x00000008); } /** * <code>optional string relative_path = 4;</code> */ public java.lang.String getRelativePath() { java.lang.Object ref = relativePath_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { relativePath_ = s; } return s; } } /** * <code>optional string relative_path = 4;</code> */ public com.google.protobuf.ByteString getRelativePathBytes() { java.lang.Object ref = relativePath_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); relativePath_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } // optional string class_name = 5; public static final int CLASS_NAME_FIELD_NUMBER = 5; private java.lang.Object className_; /** * <code>optional string class_name = 5;</code> */ public boolean hasClassName() { return ((bitField0_ & 0x00000010) == 0x00000010); } /** * <code>optional string class_name = 5;</code> */ public java.lang.String getClassName() { java.lang.Object ref = className_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { className_ = s; } return s; } } /** * <code>optional string class_name = 5;</code> */ public com.google.protobuf.ByteString getClassNameBytes() { java.lang.Object ref = className_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); className_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } // optional string source_uri = 6; public static final int SOURCE_URI_FIELD_NUMBER = 6; private java.lang.Object sourceUri_; /** * <code>optional string source_uri = 6;</code> */ public boolean hasSourceUri() { return ((bitField0_ & 0x00000020) == 0x00000020); } /** * <code>optional string source_uri = 6;</code> */ public java.lang.String getSourceUri() { java.lang.Object ref = sourceUri_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { sourceUri_ = s; } return s; } } /** * <code>optional string source_uri = 6;</code> */ public com.google.protobuf.ByteString getSourceUriBytes() { java.lang.Object ref = sourceUri_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); sourceUri_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } // optional bytes content = 7; public static final int CONTENT_FIELD_NUMBER = 7; private com.google.protobuf.ByteString content_; /** * <code>optional bytes content = 7;</code> */ public boolean hasContent() { return ((bitField0_ & 0x00000040) == 0x00000040); } /** * <code>optional bytes content = 7;</code> */ public com.google.protobuf.ByteString getContent() { return content_; } private void initFields() { kind_ = org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.OutputObject.Kind.SOURCE; filePath_ = ""; outputRoot_ = ""; relativePath_ = ""; className_ = ""; sourceUri_ = ""; content_ = com.google.protobuf.ByteString.EMPTY; } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized != -1) return isInitialized == 1; if (!hasKind()) { memoizedIsInitialized = 0; return false; } if (!hasFilePath()) { memoizedIsInitialized = 0; return false; } memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getSerializedSize(); if (((bitField0_ & 0x00000001) == 0x00000001)) { output.writeEnum(1, kind_.getNumber()); } if (((bitField0_ & 0x00000002) == 0x00000002)) { output.writeBytes(2, getFilePathBytes()); } if (((bitField0_ & 0x00000004) == 0x00000004)) { output.writeBytes(3, getOutputRootBytes()); } if (((bitField0_ & 0x00000008) == 0x00000008)) { output.writeBytes(4, getRelativePathBytes()); } if (((bitField0_ & 0x00000010) == 0x00000010)) { output.writeBytes(5, getClassNameBytes()); } if (((bitField0_ & 0x00000020) == 0x00000020)) { output.writeBytes(6, getSourceUriBytes()); } if (((bitField0_ & 0x00000040) == 0x00000040)) { output.writeBytes(7, content_); } } private int memoizedSerializedSize = -1; public int getSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; if (((bitField0_ & 0x00000001) == 0x00000001)) { size += com.google.protobuf.CodedOutputStream .computeEnumSize(1, kind_.getNumber()); } if (((bitField0_ & 0x00000002) == 0x00000002)) { size += com.google.protobuf.CodedOutputStream .computeBytesSize(2, getFilePathBytes()); } if (((bitField0_ & 0x00000004) == 0x00000004)) { size += com.google.protobuf.CodedOutputStream .computeBytesSize(3, getOutputRootBytes()); } if (((bitField0_ & 0x00000008) == 0x00000008)) { size += com.google.protobuf.CodedOutputStream .computeBytesSize(4, getRelativePathBytes()); } if (((bitField0_ & 0x00000010) == 0x00000010)) { size += com.google.protobuf.CodedOutputStream .computeBytesSize(5, getClassNameBytes()); } if (((bitField0_ & 0x00000020) == 0x00000020)) { size += com.google.protobuf.CodedOutputStream .computeBytesSize(6, getSourceUriBytes()); } if (((bitField0_ & 0x00000040) == 0x00000040)) { size += com.google.protobuf.CodedOutputStream .computeBytesSize(7, content_); } memoizedSerializedSize = size; return size; } private static final long serialVersionUID = 0L; @java.lang.Override protected java.lang.Object writeReplace() throws java.io.ObjectStreamException { return super.writeReplace(); } public static org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.OutputObject parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.OutputObject parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.OutputObject parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.OutputObject parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.OutputObject parseFrom(java.io.InputStream input) throws java.io.IOException { return PARSER.parseFrom(input); } public static org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.OutputObject parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } public static org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.OutputObject parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return PARSER.parseDelimitedFrom(input); } public static org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.OutputObject parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseDelimitedFrom(input, extensionRegistry); } public static org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.OutputObject parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return PARSER.parseFrom(input); } public static org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.OutputObject parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } public static Builder newBuilder() { return Builder.create(); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder(org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.OutputObject prototype) { return newBuilder().mergeFrom(prototype); } public Builder toBuilder() { return newBuilder(this); } /** * Protobuf type {@code org.jetbrains.javac.Message.Response.OutputObject} */ public static final class Builder extends com.google.protobuf.GeneratedMessageLite.Builder< org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.OutputObject, Builder> implements org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.OutputObjectOrBuilder { // Construct using org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.OutputObject.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { } private static Builder create() { return new Builder(); } public Builder clear() { super.clear(); kind_ = org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.OutputObject.Kind.SOURCE; bitField0_ = (bitField0_ & ~0x00000001); filePath_ = ""; bitField0_ = (bitField0_ & ~0x00000002); outputRoot_ = ""; bitField0_ = (bitField0_ & ~0x00000004); relativePath_ = ""; bitField0_ = (bitField0_ & ~0x00000008); className_ = ""; bitField0_ = (bitField0_ & ~0x00000010); sourceUri_ = ""; bitField0_ = (bitField0_ & ~0x00000020); content_ = com.google.protobuf.ByteString.EMPTY; bitField0_ = (bitField0_ & ~0x00000040); return this; } public Builder clone() { return create().mergeFrom(buildPartial()); } public org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.OutputObject getDefaultInstanceForType() { return org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.OutputObject.getDefaultInstance(); } public org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.OutputObject build() { org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.OutputObject result = buildPartial(); if (!result.isInitialized()) { throw Builder.newUninitializedMessageException(result); } return result; } public org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.OutputObject buildPartial() { org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.OutputObject result = new org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.OutputObject(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) == 0x00000001)) { to_bitField0_ |= 0x00000001; } result.kind_ = kind_; if (((from_bitField0_ & 0x00000002) == 0x00000002)) { to_bitField0_ |= 0x00000002; } result.filePath_ = filePath_; if (((from_bitField0_ & 0x00000004) == 0x00000004)) { to_bitField0_ |= 0x00000004; } result.outputRoot_ = outputRoot_; if (((from_bitField0_ & 0x00000008) == 0x00000008)) { to_bitField0_ |= 0x00000008; } result.relativePath_ = relativePath_; if (((from_bitField0_ & 0x00000010) == 0x00000010)) { to_bitField0_ |= 0x00000010; } result.className_ = className_; if (((from_bitField0_ & 0x00000020) == 0x00000020)) { to_bitField0_ |= 0x00000020; } result.sourceUri_ = sourceUri_; if (((from_bitField0_ & 0x00000040) == 0x00000040)) { to_bitField0_ |= 0x00000040; } result.content_ = content_; result.bitField0_ = to_bitField0_; return result; } public Builder mergeFrom(org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.OutputObject other) { if (other == org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.OutputObject.getDefaultInstance()) return this; if (other.hasKind()) { setKind(other.getKind()); } if (other.hasFilePath()) { bitField0_ |= 0x00000002; filePath_ = other.filePath_; } if (other.hasOutputRoot()) { bitField0_ |= 0x00000004; outputRoot_ = other.outputRoot_; } if (other.hasRelativePath()) { bitField0_ |= 0x00000008; relativePath_ = other.relativePath_; } if (other.hasClassName()) { bitField0_ |= 0x00000010; className_ = other.className_; } if (other.hasSourceUri()) { bitField0_ |= 0x00000020; sourceUri_ = other.sourceUri_; } if (other.hasContent()) { setContent(other.getContent()); } return this; } public final boolean isInitialized() { if (!hasKind()) { return false; } if (!hasFilePath()) { return false; } return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.OutputObject parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.OutputObject) e.getUnfinishedMessage(); throw e; } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; // required .org.jetbrains.javac.Message.Response.OutputObject.Kind kind = 1; private org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.OutputObject.Kind kind_ = org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.OutputObject.Kind.SOURCE; /** * <code>required .org.jetbrains.javac.Message.Response.OutputObject.Kind kind = 1;</code> */ public boolean hasKind() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * <code>required .org.jetbrains.javac.Message.Response.OutputObject.Kind kind = 1;</code> */ public org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.OutputObject.Kind getKind() { return kind_; } /** * <code>required .org.jetbrains.javac.Message.Response.OutputObject.Kind kind = 1;</code> */ public Builder setKind(org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.OutputObject.Kind value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000001; kind_ = value; return this; } /** * <code>required .org.jetbrains.javac.Message.Response.OutputObject.Kind kind = 1;</code> */ public Builder clearKind() { bitField0_ = (bitField0_ & ~0x00000001); kind_ = org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.OutputObject.Kind.SOURCE; return this; } // required string file_path = 2; private java.lang.Object filePath_ = ""; /** * <code>required string file_path = 2;</code> */ public boolean hasFilePath() { return ((bitField0_ & 0x00000002) == 0x00000002); } /** * <code>required string file_path = 2;</code> */ public java.lang.String getFilePath() { java.lang.Object ref = filePath_; if (!(ref instanceof java.lang.String)) { java.lang.String s = ((com.google.protobuf.ByteString) ref) .toStringUtf8(); filePath_ = s; return s; } else { return (java.lang.String) ref; } } /** * <code>required string file_path = 2;</code> */ public com.google.protobuf.ByteString getFilePathBytes() { java.lang.Object ref = filePath_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); filePath_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <code>required string file_path = 2;</code> */ public Builder setFilePath( java.lang.String value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000002; filePath_ = value; return this; } /** * <code>required string file_path = 2;</code> */ public Builder clearFilePath() { bitField0_ = (bitField0_ & ~0x00000002); filePath_ = getDefaultInstance().getFilePath(); return this; } /** * <code>required string file_path = 2;</code> */ public Builder setFilePathBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000002; filePath_ = value; return this; } // optional string output_root = 3; private java.lang.Object outputRoot_ = ""; /** * <code>optional string output_root = 3;</code> */ public boolean hasOutputRoot() { return ((bitField0_ & 0x00000004) == 0x00000004); } /** * <code>optional string output_root = 3;</code> */ public java.lang.String getOutputRoot() { java.lang.Object ref = outputRoot_; if (!(ref instanceof java.lang.String)) { java.lang.String s = ((com.google.protobuf.ByteString) ref) .toStringUtf8(); outputRoot_ = s; return s; } else { return (java.lang.String) ref; } } /** * <code>optional string output_root = 3;</code> */ public com.google.protobuf.ByteString getOutputRootBytes() { java.lang.Object ref = outputRoot_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); outputRoot_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <code>optional string output_root = 3;</code> */ public Builder setOutputRoot( java.lang.String value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000004; outputRoot_ = value; return this; } /** * <code>optional string output_root = 3;</code> */ public Builder clearOutputRoot() { bitField0_ = (bitField0_ & ~0x00000004); outputRoot_ = getDefaultInstance().getOutputRoot(); return this; } /** * <code>optional string output_root = 3;</code> */ public Builder setOutputRootBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000004; outputRoot_ = value; return this; } // optional string relative_path = 4; private java.lang.Object relativePath_ = ""; /** * <code>optional string relative_path = 4;</code> */ public boolean hasRelativePath() { return ((bitField0_ & 0x00000008) == 0x00000008); } /** * <code>optional string relative_path = 4;</code> */ public java.lang.String getRelativePath() { java.lang.Object ref = relativePath_; if (!(ref instanceof java.lang.String)) { java.lang.String s = ((com.google.protobuf.ByteString) ref) .toStringUtf8(); relativePath_ = s; return s; } else { return (java.lang.String) ref; } } /** * <code>optional string relative_path = 4;</code> */ public com.google.protobuf.ByteString getRelativePathBytes() { java.lang.Object ref = relativePath_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); relativePath_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <code>optional string relative_path = 4;</code> */ public Builder setRelativePath( java.lang.String value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000008; relativePath_ = value; return this; } /** * <code>optional string relative_path = 4;</code> */ public Builder clearRelativePath() { bitField0_ = (bitField0_ & ~0x00000008); relativePath_ = getDefaultInstance().getRelativePath(); return this; } /** * <code>optional string relative_path = 4;</code> */ public Builder setRelativePathBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000008; relativePath_ = value; return this; } // optional string class_name = 5; private java.lang.Object className_ = ""; /** * <code>optional string class_name = 5;</code> */ public boolean hasClassName() { return ((bitField0_ & 0x00000010) == 0x00000010); } /** * <code>optional string class_name = 5;</code> */ public java.lang.String getClassName() { java.lang.Object ref = className_; if (!(ref instanceof java.lang.String)) { java.lang.String s = ((com.google.protobuf.ByteString) ref) .toStringUtf8(); className_ = s; return s; } else { return (java.lang.String) ref; } } /** * <code>optional string class_name = 5;</code> */ public com.google.protobuf.ByteString getClassNameBytes() { java.lang.Object ref = className_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); className_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <code>optional string class_name = 5;</code> */ public Builder setClassName( java.lang.String value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000010; className_ = value; return this; } /** * <code>optional string class_name = 5;</code> */ public Builder clearClassName() { bitField0_ = (bitField0_ & ~0x00000010); className_ = getDefaultInstance().getClassName(); return this; } /** * <code>optional string class_name = 5;</code> */ public Builder setClassNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000010; className_ = value; return this; } // optional string source_uri = 6; private java.lang.Object sourceUri_ = ""; /** * <code>optional string source_uri = 6;</code> */ public boolean hasSourceUri() { return ((bitField0_ & 0x00000020) == 0x00000020); } /** * <code>optional string source_uri = 6;</code> */ public java.lang.String getSourceUri() { java.lang.Object ref = sourceUri_; if (!(ref instanceof java.lang.String)) { java.lang.String s = ((com.google.protobuf.ByteString) ref) .toStringUtf8(); sourceUri_ = s; return s; } else { return (java.lang.String) ref; } } /** * <code>optional string source_uri = 6;</code> */ public com.google.protobuf.ByteString getSourceUriBytes() { java.lang.Object ref = sourceUri_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); sourceUri_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <code>optional string source_uri = 6;</code> */ public Builder setSourceUri( java.lang.String value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000020; sourceUri_ = value; return this; } /** * <code>optional string source_uri = 6;</code> */ public Builder clearSourceUri() { bitField0_ = (bitField0_ & ~0x00000020); sourceUri_ = getDefaultInstance().getSourceUri(); return this; } /** * <code>optional string source_uri = 6;</code> */ public Builder setSourceUriBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000020; sourceUri_ = value; return this; } // optional bytes content = 7; private com.google.protobuf.ByteString content_ = com.google.protobuf.ByteString.EMPTY; /** * <code>optional bytes content = 7;</code> */ public boolean hasContent() { return ((bitField0_ & 0x00000040) == 0x00000040); } /** * <code>optional bytes content = 7;</code> */ public com.google.protobuf.ByteString getContent() { return content_; } /** * <code>optional bytes content = 7;</code> */ public Builder setContent(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000040; content_ = value; return this; } /** * <code>optional bytes content = 7;</code> */ public Builder clearContent() { bitField0_ = (bitField0_ & ~0x00000040); content_ = getDefaultInstance().getContent(); return this; } // @@protoc_insertion_point(builder_scope:org.jetbrains.javac.Message.Response.OutputObject) } static { defaultInstance = new OutputObject(true); defaultInstance.initFields(); } // @@protoc_insertion_point(class_scope:org.jetbrains.javac.Message.Response.OutputObject) } public interface ClassDataOrBuilder extends com.google.protobuf.MessageLiteOrBuilder { // required string class_name = 1; /** * <code>required string class_name = 1;</code> */ boolean hasClassName(); /** * <code>required string class_name = 1;</code> */ java.lang.String getClassName(); /** * <code>required string class_name = 1;</code> */ com.google.protobuf.ByteString getClassNameBytes(); // repeated string import_statement = 2; /** * <code>repeated string import_statement = 2;</code> */ java.util.List<java.lang.String> getImportStatementList(); /** * <code>repeated string import_statement = 2;</code> */ int getImportStatementCount(); /** * <code>repeated string import_statement = 2;</code> */ java.lang.String getImportStatement(int index); /** * <code>repeated string import_statement = 2;</code> */ com.google.protobuf.ByteString getImportStatementBytes(int index); // repeated string static_import = 3; /** * <code>repeated string static_import = 3;</code> */ java.util.List<java.lang.String> getStaticImportList(); /** * <code>repeated string static_import = 3;</code> */ int getStaticImportCount(); /** * <code>repeated string static_import = 3;</code> */ java.lang.String getStaticImport(int index); /** * <code>repeated string static_import = 3;</code> */ com.google.protobuf.ByteString getStaticImportBytes(int index); // repeated string identifier = 4; /** * <code>repeated string identifier = 4;</code> */ java.util.List<java.lang.String> getIdentifierList(); /** * <code>repeated string identifier = 4;</code> */ int getIdentifierCount(); /** * <code>repeated string identifier = 4;</code> */ java.lang.String getIdentifier(int index); /** * <code>repeated string identifier = 4;</code> */ com.google.protobuf.ByteString getIdentifierBytes(int index); } /** * Protobuf type {@code org.jetbrains.javac.Message.Response.ClassData} */ public static final class ClassData extends com.google.protobuf.GeneratedMessageLite implements ClassDataOrBuilder { // Use ClassData.newBuilder() to construct. private ClassData(com.google.protobuf.GeneratedMessageLite.Builder builder) { super(builder); } private ClassData(boolean noInit) {} private static final ClassData defaultInstance; public static ClassData getDefaultInstance() { return defaultInstance; } public ClassData getDefaultInstanceForType() { return defaultInstance; } private ClassData( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { initFields(); int mutable_bitField0_ = 0; try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownField(input, extensionRegistry, tag)) { done = true; } break; } case 10: { bitField0_ |= 0x00000001; className_ = input.readBytes(); break; } case 18: { if (!((mutable_bitField0_ & 0x00000002) == 0x00000002)) { importStatement_ = new com.google.protobuf.LazyStringArrayList(); mutable_bitField0_ |= 0x00000002; } importStatement_.add(input.readBytes()); break; } case 26: { if (!((mutable_bitField0_ & 0x00000004) == 0x00000004)) { staticImport_ = new com.google.protobuf.LazyStringArrayList(); mutable_bitField0_ |= 0x00000004; } staticImport_.add(input.readBytes()); break; } case 34: { if (!((mutable_bitField0_ & 0x00000008) == 0x00000008)) { identifier_ = new com.google.protobuf.LazyStringArrayList(); mutable_bitField0_ |= 0x00000008; } identifier_.add(input.readBytes()); break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e.getMessage()).setUnfinishedMessage(this); } finally { if (((mutable_bitField0_ & 0x00000002) == 0x00000002)) { importStatement_ = new com.google.protobuf.UnmodifiableLazyStringList(importStatement_); } if (((mutable_bitField0_ & 0x00000004) == 0x00000004)) { staticImport_ = new com.google.protobuf.UnmodifiableLazyStringList(staticImport_); } if (((mutable_bitField0_ & 0x00000008) == 0x00000008)) { identifier_ = new com.google.protobuf.UnmodifiableLazyStringList(identifier_); } makeExtensionsImmutable(); } } public static com.google.protobuf.Parser<ClassData> PARSER = new com.google.protobuf.AbstractParser<ClassData>() { public ClassData parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new ClassData(input, extensionRegistry); } }; @java.lang.Override public com.google.protobuf.Parser<ClassData> getParserForType() { return PARSER; } private int bitField0_; // required string class_name = 1; public static final int CLASS_NAME_FIELD_NUMBER = 1; private java.lang.Object className_; /** * <code>required string class_name = 1;</code> */ public boolean hasClassName() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * <code>required string class_name = 1;</code> */ public java.lang.String getClassName() { java.lang.Object ref = className_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { className_ = s; } return s; } } /** * <code>required string class_name = 1;</code> */ public com.google.protobuf.ByteString getClassNameBytes() { java.lang.Object ref = className_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); className_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } // repeated string import_statement = 2; public static final int IMPORT_STATEMENT_FIELD_NUMBER = 2; private com.google.protobuf.LazyStringList importStatement_; /** * <code>repeated string import_statement = 2;</code> */ public java.util.List<java.lang.String> getImportStatementList() { return importStatement_; } /** * <code>repeated string import_statement = 2;</code> */ public int getImportStatementCount() { return importStatement_.size(); } /** * <code>repeated string import_statement = 2;</code> */ public java.lang.String getImportStatement(int index) { return importStatement_.get(index); } /** * <code>repeated string import_statement = 2;</code> */ public com.google.protobuf.ByteString getImportStatementBytes(int index) { return importStatement_.getByteString(index); } // repeated string static_import = 3; public static final int STATIC_IMPORT_FIELD_NUMBER = 3; private com.google.protobuf.LazyStringList staticImport_; /** * <code>repeated string static_import = 3;</code> */ public java.util.List<java.lang.String> getStaticImportList() { return staticImport_; } /** * <code>repeated string static_import = 3;</code> */ public int getStaticImportCount() { return staticImport_.size(); } /** * <code>repeated string static_import = 3;</code> */ public java.lang.String getStaticImport(int index) { return staticImport_.get(index); } /** * <code>repeated string static_import = 3;</code> */ public com.google.protobuf.ByteString getStaticImportBytes(int index) { return staticImport_.getByteString(index); } // repeated string identifier = 4; public static final int IDENTIFIER_FIELD_NUMBER = 4; private com.google.protobuf.LazyStringList identifier_; /** * <code>repeated string identifier = 4;</code> */ public java.util.List<java.lang.String> getIdentifierList() { return identifier_; } /** * <code>repeated string identifier = 4;</code> */ public int getIdentifierCount() { return identifier_.size(); } /** * <code>repeated string identifier = 4;</code> */ public java.lang.String getIdentifier(int index) { return identifier_.get(index); } /** * <code>repeated string identifier = 4;</code> */ public com.google.protobuf.ByteString getIdentifierBytes(int index) { return identifier_.getByteString(index); } private void initFields() { className_ = ""; importStatement_ = com.google.protobuf.LazyStringArrayList.EMPTY; staticImport_ = com.google.protobuf.LazyStringArrayList.EMPTY; identifier_ = com.google.protobuf.LazyStringArrayList.EMPTY; } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized != -1) return isInitialized == 1; if (!hasClassName()) { memoizedIsInitialized = 0; return false; } memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getSerializedSize(); if (((bitField0_ & 0x00000001) == 0x00000001)) { output.writeBytes(1, getClassNameBytes()); } for (int i = 0; i < importStatement_.size(); i++) { output.writeBytes(2, importStatement_.getByteString(i)); } for (int i = 0; i < staticImport_.size(); i++) { output.writeBytes(3, staticImport_.getByteString(i)); } for (int i = 0; i < identifier_.size(); i++) { output.writeBytes(4, identifier_.getByteString(i)); } } private int memoizedSerializedSize = -1; public int getSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; if (((bitField0_ & 0x00000001) == 0x00000001)) { size += com.google.protobuf.CodedOutputStream .computeBytesSize(1, getClassNameBytes()); } { int dataSize = 0; for (int i = 0; i < importStatement_.size(); i++) { dataSize += com.google.protobuf.CodedOutputStream .computeBytesSizeNoTag(importStatement_.getByteString(i)); } size += dataSize; size += 1 * getImportStatementList().size(); } { int dataSize = 0; for (int i = 0; i < staticImport_.size(); i++) { dataSize += com.google.protobuf.CodedOutputStream .computeBytesSizeNoTag(staticImport_.getByteString(i)); } size += dataSize; size += 1 * getStaticImportList().size(); } { int dataSize = 0; for (int i = 0; i < identifier_.size(); i++) { dataSize += com.google.protobuf.CodedOutputStream .computeBytesSizeNoTag(identifier_.getByteString(i)); } size += dataSize; size += 1 * getIdentifierList().size(); } memoizedSerializedSize = size; return size; } private static final long serialVersionUID = 0L; @java.lang.Override protected java.lang.Object writeReplace() throws java.io.ObjectStreamException { return super.writeReplace(); } public static org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.ClassData parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.ClassData parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.ClassData parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.ClassData parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.ClassData parseFrom(java.io.InputStream input) throws java.io.IOException { return PARSER.parseFrom(input); } public static org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.ClassData parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } public static org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.ClassData parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return PARSER.parseDelimitedFrom(input); } public static org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.ClassData parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseDelimitedFrom(input, extensionRegistry); } public static org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.ClassData parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return PARSER.parseFrom(input); } public static org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.ClassData parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } public static Builder newBuilder() { return Builder.create(); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder(org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.ClassData prototype) { return newBuilder().mergeFrom(prototype); } public Builder toBuilder() { return newBuilder(this); } /** * Protobuf type {@code org.jetbrains.javac.Message.Response.ClassData} */ public static final class Builder extends com.google.protobuf.GeneratedMessageLite.Builder< org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.ClassData, Builder> implements org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.ClassDataOrBuilder { // Construct using org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.ClassData.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { } private static Builder create() { return new Builder(); } public Builder clear() { super.clear(); className_ = ""; bitField0_ = (bitField0_ & ~0x00000001); importStatement_ = com.google.protobuf.LazyStringArrayList.EMPTY; bitField0_ = (bitField0_ & ~0x00000002); staticImport_ = com.google.protobuf.LazyStringArrayList.EMPTY; bitField0_ = (bitField0_ & ~0x00000004); identifier_ = com.google.protobuf.LazyStringArrayList.EMPTY; bitField0_ = (bitField0_ & ~0x00000008); return this; } public Builder clone() { return create().mergeFrom(buildPartial()); } public org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.ClassData getDefaultInstanceForType() { return org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.ClassData.getDefaultInstance(); } public org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.ClassData build() { org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.ClassData result = buildPartial(); if (!result.isInitialized()) { throw Builder.newUninitializedMessageException(result); } return result; } public org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.ClassData buildPartial() { org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.ClassData result = new org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.ClassData(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) == 0x00000001)) { to_bitField0_ |= 0x00000001; } result.className_ = className_; if (((bitField0_ & 0x00000002) == 0x00000002)) { importStatement_ = new com.google.protobuf.UnmodifiableLazyStringList( importStatement_); bitField0_ = (bitField0_ & ~0x00000002); } result.importStatement_ = importStatement_; if (((bitField0_ & 0x00000004) == 0x00000004)) { staticImport_ = new com.google.protobuf.UnmodifiableLazyStringList( staticImport_); bitField0_ = (bitField0_ & ~0x00000004); } result.staticImport_ = staticImport_; if (((bitField0_ & 0x00000008) == 0x00000008)) { identifier_ = new com.google.protobuf.UnmodifiableLazyStringList( identifier_); bitField0_ = (bitField0_ & ~0x00000008); } result.identifier_ = identifier_; result.bitField0_ = to_bitField0_; return result; } public Builder mergeFrom(org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.ClassData other) { if (other == org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.ClassData.getDefaultInstance()) return this; if (other.hasClassName()) { bitField0_ |= 0x00000001; className_ = other.className_; } if (!other.importStatement_.isEmpty()) { if (importStatement_.isEmpty()) { importStatement_ = other.importStatement_; bitField0_ = (bitField0_ & ~0x00000002); } else { ensureImportStatementIsMutable(); importStatement_.addAll(other.importStatement_); } } if (!other.staticImport_.isEmpty()) { if (staticImport_.isEmpty()) { staticImport_ = other.staticImport_; bitField0_ = (bitField0_ & ~0x00000004); } else { ensureStaticImportIsMutable(); staticImport_.addAll(other.staticImport_); } } if (!other.identifier_.isEmpty()) { if (identifier_.isEmpty()) { identifier_ = other.identifier_; bitField0_ = (bitField0_ & ~0x00000008); } else { ensureIdentifierIsMutable(); identifier_.addAll(other.identifier_); } } return this; } public final boolean isInitialized() { if (!hasClassName()) { return false; } return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.ClassData parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.ClassData) e.getUnfinishedMessage(); throw e; } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; // required string class_name = 1; private java.lang.Object className_ = ""; /** * <code>required string class_name = 1;</code> */ public boolean hasClassName() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * <code>required string class_name = 1;</code> */ public java.lang.String getClassName() { java.lang.Object ref = className_; if (!(ref instanceof java.lang.String)) { java.lang.String s = ((com.google.protobuf.ByteString) ref) .toStringUtf8(); className_ = s; return s; } else { return (java.lang.String) ref; } } /** * <code>required string class_name = 1;</code> */ public com.google.protobuf.ByteString getClassNameBytes() { java.lang.Object ref = className_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); className_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <code>required string class_name = 1;</code> */ public Builder setClassName( java.lang.String value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000001; className_ = value; return this; } /** * <code>required string class_name = 1;</code> */ public Builder clearClassName() { bitField0_ = (bitField0_ & ~0x00000001); className_ = getDefaultInstance().getClassName(); return this; } /** * <code>required string class_name = 1;</code> */ public Builder setClassNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000001; className_ = value; return this; } // repeated string import_statement = 2; private com.google.protobuf.LazyStringList importStatement_ = com.google.protobuf.LazyStringArrayList.EMPTY; private void ensureImportStatementIsMutable() { if (!((bitField0_ & 0x00000002) == 0x00000002)) { importStatement_ = new com.google.protobuf.LazyStringArrayList(importStatement_); bitField0_ |= 0x00000002; } } /** * <code>repeated string import_statement = 2;</code> */ public java.util.List<java.lang.String> getImportStatementList() { return java.util.Collections.unmodifiableList(importStatement_); } /** * <code>repeated string import_statement = 2;</code> */ public int getImportStatementCount() { return importStatement_.size(); } /** * <code>repeated string import_statement = 2;</code> */ public java.lang.String getImportStatement(int index) { return importStatement_.get(index); } /** * <code>repeated string import_statement = 2;</code> */ public com.google.protobuf.ByteString getImportStatementBytes(int index) { return importStatement_.getByteString(index); } /** * <code>repeated string import_statement = 2;</code> */ public Builder setImportStatement( int index, java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureImportStatementIsMutable(); importStatement_.set(index, value); return this; } /** * <code>repeated string import_statement = 2;</code> */ public Builder addImportStatement( java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureImportStatementIsMutable(); importStatement_.add(value); return this; } /** * <code>repeated string import_statement = 2;</code> */ public Builder addAllImportStatement( java.lang.Iterable<java.lang.String> values) { ensureImportStatementIsMutable(); super.addAll(values, importStatement_); return this; } /** * <code>repeated string import_statement = 2;</code> */ public Builder clearImportStatement() { importStatement_ = com.google.protobuf.LazyStringArrayList.EMPTY; bitField0_ = (bitField0_ & ~0x00000002); return this; } /** * <code>repeated string import_statement = 2;</code> */ public Builder addImportStatementBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } ensureImportStatementIsMutable(); importStatement_.add(value); return this; } // repeated string static_import = 3; private com.google.protobuf.LazyStringList staticImport_ = com.google.protobuf.LazyStringArrayList.EMPTY; private void ensureStaticImportIsMutable() { if (!((bitField0_ & 0x00000004) == 0x00000004)) { staticImport_ = new com.google.protobuf.LazyStringArrayList(staticImport_); bitField0_ |= 0x00000004; } } /** * <code>repeated string static_import = 3;</code> */ public java.util.List<java.lang.String> getStaticImportList() { return java.util.Collections.unmodifiableList(staticImport_); } /** * <code>repeated string static_import = 3;</code> */ public int getStaticImportCount() { return staticImport_.size(); } /** * <code>repeated string static_import = 3;</code> */ public java.lang.String getStaticImport(int index) { return staticImport_.get(index); } /** * <code>repeated string static_import = 3;</code> */ public com.google.protobuf.ByteString getStaticImportBytes(int index) { return staticImport_.getByteString(index); } /** * <code>repeated string static_import = 3;</code> */ public Builder setStaticImport( int index, java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureStaticImportIsMutable(); staticImport_.set(index, value); return this; } /** * <code>repeated string static_import = 3;</code> */ public Builder addStaticImport( java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureStaticImportIsMutable(); staticImport_.add(value); return this; } /** * <code>repeated string static_import = 3;</code> */ public Builder addAllStaticImport( java.lang.Iterable<java.lang.String> values) { ensureStaticImportIsMutable(); super.addAll(values, staticImport_); return this; } /** * <code>repeated string static_import = 3;</code> */ public Builder clearStaticImport() { staticImport_ = com.google.protobuf.LazyStringArrayList.EMPTY; bitField0_ = (bitField0_ & ~0x00000004); return this; } /** * <code>repeated string static_import = 3;</code> */ public Builder addStaticImportBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } ensureStaticImportIsMutable(); staticImport_.add(value); return this; } // repeated string identifier = 4; private com.google.protobuf.LazyStringList identifier_ = com.google.protobuf.LazyStringArrayList.EMPTY; private void ensureIdentifierIsMutable() { if (!((bitField0_ & 0x00000008) == 0x00000008)) { identifier_ = new com.google.protobuf.LazyStringArrayList(identifier_); bitField0_ |= 0x00000008; } } /** * <code>repeated string identifier = 4;</code> */ public java.util.List<java.lang.String> getIdentifierList() { return java.util.Collections.unmodifiableList(identifier_); } /** * <code>repeated string identifier = 4;</code> */ public int getIdentifierCount() { return identifier_.size(); } /** * <code>repeated string identifier = 4;</code> */ public java.lang.String getIdentifier(int index) { return identifier_.get(index); } /** * <code>repeated string identifier = 4;</code> */ public com.google.protobuf.ByteString getIdentifierBytes(int index) { return identifier_.getByteString(index); } /** * <code>repeated string identifier = 4;</code> */ public Builder setIdentifier( int index, java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureIdentifierIsMutable(); identifier_.set(index, value); return this; } /** * <code>repeated string identifier = 4;</code> */ public Builder addIdentifier( java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureIdentifierIsMutable(); identifier_.add(value); return this; } /** * <code>repeated string identifier = 4;</code> */ public Builder addAllIdentifier( java.lang.Iterable<java.lang.String> values) { ensureIdentifierIsMutable(); super.addAll(values, identifier_); return this; } /** * <code>repeated string identifier = 4;</code> */ public Builder clearIdentifier() { identifier_ = com.google.protobuf.LazyStringArrayList.EMPTY; bitField0_ = (bitField0_ & ~0x00000008); return this; } /** * <code>repeated string identifier = 4;</code> */ public Builder addIdentifierBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } ensureIdentifierIsMutable(); identifier_.add(value); return this; } // @@protoc_insertion_point(builder_scope:org.jetbrains.javac.Message.Response.ClassData) } static { defaultInstance = new ClassData(true); defaultInstance.initFields(); } // @@protoc_insertion_point(class_scope:org.jetbrains.javac.Message.Response.ClassData) } private int bitField0_; // required .org.jetbrains.javac.Message.Response.Type response_type = 1; public static final int RESPONSE_TYPE_FIELD_NUMBER = 1; private org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.Type responseType_; /** * <code>required .org.jetbrains.javac.Message.Response.Type response_type = 1;</code> */ public boolean hasResponseType() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * <code>required .org.jetbrains.javac.Message.Response.Type response_type = 1;</code> */ public org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.Type getResponseType() { return responseType_; } // optional .org.jetbrains.javac.Message.Response.CompileMessage compile_message = 2; public static final int COMPILE_MESSAGE_FIELD_NUMBER = 2; private org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.CompileMessage compileMessage_; /** * <code>optional .org.jetbrains.javac.Message.Response.CompileMessage compile_message = 2;</code> */ public boolean hasCompileMessage() { return ((bitField0_ & 0x00000002) == 0x00000002); } /** * <code>optional .org.jetbrains.javac.Message.Response.CompileMessage compile_message = 2;</code> */ public org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.CompileMessage getCompileMessage() { return compileMessage_; } // optional .org.jetbrains.javac.Message.Response.OutputObject output_object = 3; public static final int OUTPUT_OBJECT_FIELD_NUMBER = 3; private org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.OutputObject outputObject_; /** * <code>optional .org.jetbrains.javac.Message.Response.OutputObject output_object = 3;</code> */ public boolean hasOutputObject() { return ((bitField0_ & 0x00000004) == 0x00000004); } /** * <code>optional .org.jetbrains.javac.Message.Response.OutputObject output_object = 3;</code> */ public org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.OutputObject getOutputObject() { return outputObject_; } // optional .org.jetbrains.javac.Message.Response.ClassData class_data = 4; public static final int CLASS_DATA_FIELD_NUMBER = 4; private org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.ClassData classData_; /** * <code>optional .org.jetbrains.javac.Message.Response.ClassData class_data = 4;</code> */ public boolean hasClassData() { return ((bitField0_ & 0x00000008) == 0x00000008); } /** * <code>optional .org.jetbrains.javac.Message.Response.ClassData class_data = 4;</code> */ public org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.ClassData getClassData() { return classData_; } // optional bool completion_status = 5; public static final int COMPLETION_STATUS_FIELD_NUMBER = 5; private boolean completionStatus_; /** * <code>optional bool completion_status = 5;</code> */ public boolean hasCompletionStatus() { return ((bitField0_ & 0x00000010) == 0x00000010); } /** * <code>optional bool completion_status = 5;</code> */ public boolean getCompletionStatus() { return completionStatus_; } private void initFields() { responseType_ = org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.Type.BUILD_MESSAGE; compileMessage_ = org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.CompileMessage.getDefaultInstance(); outputObject_ = org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.OutputObject.getDefaultInstance(); classData_ = org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.ClassData.getDefaultInstance(); completionStatus_ = false; } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized != -1) return isInitialized == 1; if (!hasResponseType()) { memoizedIsInitialized = 0; return false; } if (hasCompileMessage()) { if (!getCompileMessage().isInitialized()) { memoizedIsInitialized = 0; return false; } } if (hasOutputObject()) { if (!getOutputObject().isInitialized()) { memoizedIsInitialized = 0; return false; } } if (hasClassData()) { if (!getClassData().isInitialized()) { memoizedIsInitialized = 0; return false; } } memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getSerializedSize(); if (((bitField0_ & 0x00000001) == 0x00000001)) { output.writeEnum(1, responseType_.getNumber()); } if (((bitField0_ & 0x00000002) == 0x00000002)) { output.writeMessage(2, compileMessage_); } if (((bitField0_ & 0x00000004) == 0x00000004)) { output.writeMessage(3, outputObject_); } if (((bitField0_ & 0x00000008) == 0x00000008)) { output.writeMessage(4, classData_); } if (((bitField0_ & 0x00000010) == 0x00000010)) { output.writeBool(5, completionStatus_); } } private int memoizedSerializedSize = -1; public int getSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; if (((bitField0_ & 0x00000001) == 0x00000001)) { size += com.google.protobuf.CodedOutputStream .computeEnumSize(1, responseType_.getNumber()); } if (((bitField0_ & 0x00000002) == 0x00000002)) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(2, compileMessage_); } if (((bitField0_ & 0x00000004) == 0x00000004)) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(3, outputObject_); } if (((bitField0_ & 0x00000008) == 0x00000008)) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(4, classData_); } if (((bitField0_ & 0x00000010) == 0x00000010)) { size += com.google.protobuf.CodedOutputStream .computeBoolSize(5, completionStatus_); } memoizedSerializedSize = size; return size; } private static final long serialVersionUID = 0L; @java.lang.Override protected java.lang.Object writeReplace() throws java.io.ObjectStreamException { return super.writeReplace(); } public static org.jetbrains.jps.javac.JavacRemoteProto.Message.Response parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static org.jetbrains.jps.javac.JavacRemoteProto.Message.Response parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static org.jetbrains.jps.javac.JavacRemoteProto.Message.Response parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static org.jetbrains.jps.javac.JavacRemoteProto.Message.Response parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static org.jetbrains.jps.javac.JavacRemoteProto.Message.Response parseFrom(java.io.InputStream input) throws java.io.IOException { return PARSER.parseFrom(input); } public static org.jetbrains.jps.javac.JavacRemoteProto.Message.Response parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } public static org.jetbrains.jps.javac.JavacRemoteProto.Message.Response parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return PARSER.parseDelimitedFrom(input); } public static org.jetbrains.jps.javac.JavacRemoteProto.Message.Response parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseDelimitedFrom(input, extensionRegistry); } public static org.jetbrains.jps.javac.JavacRemoteProto.Message.Response parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return PARSER.parseFrom(input); } public static org.jetbrains.jps.javac.JavacRemoteProto.Message.Response parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } public static Builder newBuilder() { return Builder.create(); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder(org.jetbrains.jps.javac.JavacRemoteProto.Message.Response prototype) { return newBuilder().mergeFrom(prototype); } public Builder toBuilder() { return newBuilder(this); } /** * Protobuf type {@code org.jetbrains.javac.Message.Response} */ public static final class Builder extends com.google.protobuf.GeneratedMessageLite.Builder< org.jetbrains.jps.javac.JavacRemoteProto.Message.Response, Builder> implements org.jetbrains.jps.javac.JavacRemoteProto.Message.ResponseOrBuilder { // Construct using org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { } private static Builder create() { return new Builder(); } public Builder clear() { super.clear(); responseType_ = org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.Type.BUILD_MESSAGE; bitField0_ = (bitField0_ & ~0x00000001); compileMessage_ = org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.CompileMessage.getDefaultInstance(); bitField0_ = (bitField0_ & ~0x00000002); outputObject_ = org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.OutputObject.getDefaultInstance(); bitField0_ = (bitField0_ & ~0x00000004); classData_ = org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.ClassData.getDefaultInstance(); bitField0_ = (bitField0_ & ~0x00000008); completionStatus_ = false; bitField0_ = (bitField0_ & ~0x00000010); return this; } public Builder clone() { return create().mergeFrom(buildPartial()); } public org.jetbrains.jps.javac.JavacRemoteProto.Message.Response getDefaultInstanceForType() { return org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.getDefaultInstance(); } public org.jetbrains.jps.javac.JavacRemoteProto.Message.Response build() { org.jetbrains.jps.javac.JavacRemoteProto.Message.Response result = buildPartial(); if (!result.isInitialized()) { throw Builder.newUninitializedMessageException(result); } return result; } public org.jetbrains.jps.javac.JavacRemoteProto.Message.Response buildPartial() { org.jetbrains.jps.javac.JavacRemoteProto.Message.Response result = new org.jetbrains.jps.javac.JavacRemoteProto.Message.Response(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) == 0x00000001)) { to_bitField0_ |= 0x00000001; } result.responseType_ = responseType_; if (((from_bitField0_ & 0x00000002) == 0x00000002)) { to_bitField0_ |= 0x00000002; } result.compileMessage_ = compileMessage_; if (((from_bitField0_ & 0x00000004) == 0x00000004)) { to_bitField0_ |= 0x00000004; } result.outputObject_ = outputObject_; if (((from_bitField0_ & 0x00000008) == 0x00000008)) { to_bitField0_ |= 0x00000008; } result.classData_ = classData_; if (((from_bitField0_ & 0x00000010) == 0x00000010)) { to_bitField0_ |= 0x00000010; } result.completionStatus_ = completionStatus_; result.bitField0_ = to_bitField0_; return result; } public Builder mergeFrom(org.jetbrains.jps.javac.JavacRemoteProto.Message.Response other) { if (other == org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.getDefaultInstance()) return this; if (other.hasResponseType()) { setResponseType(other.getResponseType()); } if (other.hasCompileMessage()) { mergeCompileMessage(other.getCompileMessage()); } if (other.hasOutputObject()) { mergeOutputObject(other.getOutputObject()); } if (other.hasClassData()) { mergeClassData(other.getClassData()); } if (other.hasCompletionStatus()) { setCompletionStatus(other.getCompletionStatus()); } return this; } public final boolean isInitialized() { if (!hasResponseType()) { return false; } if (hasCompileMessage()) { if (!getCompileMessage().isInitialized()) { return false; } } if (hasOutputObject()) { if (!getOutputObject().isInitialized()) { return false; } } if (hasClassData()) { if (!getClassData().isInitialized()) { return false; } } return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { org.jetbrains.jps.javac.JavacRemoteProto.Message.Response parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (org.jetbrains.jps.javac.JavacRemoteProto.Message.Response) e.getUnfinishedMessage(); throw e; } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; // required .org.jetbrains.javac.Message.Response.Type response_type = 1; private org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.Type responseType_ = org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.Type.BUILD_MESSAGE; /** * <code>required .org.jetbrains.javac.Message.Response.Type response_type = 1;</code> */ public boolean hasResponseType() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * <code>required .org.jetbrains.javac.Message.Response.Type response_type = 1;</code> */ public org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.Type getResponseType() { return responseType_; } /** * <code>required .org.jetbrains.javac.Message.Response.Type response_type = 1;</code> */ public Builder setResponseType(org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.Type value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000001; responseType_ = value; return this; } /** * <code>required .org.jetbrains.javac.Message.Response.Type response_type = 1;</code> */ public Builder clearResponseType() { bitField0_ = (bitField0_ & ~0x00000001); responseType_ = org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.Type.BUILD_MESSAGE; return this; } // optional .org.jetbrains.javac.Message.Response.CompileMessage compile_message = 2; private org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.CompileMessage compileMessage_ = org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.CompileMessage.getDefaultInstance(); /** * <code>optional .org.jetbrains.javac.Message.Response.CompileMessage compile_message = 2;</code> */ public boolean hasCompileMessage() { return ((bitField0_ & 0x00000002) == 0x00000002); } /** * <code>optional .org.jetbrains.javac.Message.Response.CompileMessage compile_message = 2;</code> */ public org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.CompileMessage getCompileMessage() { return compileMessage_; } /** * <code>optional .org.jetbrains.javac.Message.Response.CompileMessage compile_message = 2;</code> */ public Builder setCompileMessage(org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.CompileMessage value) { if (value == null) { throw new NullPointerException(); } compileMessage_ = value; bitField0_ |= 0x00000002; return this; } /** * <code>optional .org.jetbrains.javac.Message.Response.CompileMessage compile_message = 2;</code> */ public Builder setCompileMessage( org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.CompileMessage.Builder builderForValue) { compileMessage_ = builderForValue.build(); bitField0_ |= 0x00000002; return this; } /** * <code>optional .org.jetbrains.javac.Message.Response.CompileMessage compile_message = 2;</code> */ public Builder mergeCompileMessage(org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.CompileMessage value) { if (((bitField0_ & 0x00000002) == 0x00000002) && compileMessage_ != org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.CompileMessage.getDefaultInstance()) { compileMessage_ = org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.CompileMessage.newBuilder(compileMessage_).mergeFrom(value).buildPartial(); } else { compileMessage_ = value; } bitField0_ |= 0x00000002; return this; } /** * <code>optional .org.jetbrains.javac.Message.Response.CompileMessage compile_message = 2;</code> */ public Builder clearCompileMessage() { compileMessage_ = org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.CompileMessage.getDefaultInstance(); bitField0_ = (bitField0_ & ~0x00000002); return this; } // optional .org.jetbrains.javac.Message.Response.OutputObject output_object = 3; private org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.OutputObject outputObject_ = org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.OutputObject.getDefaultInstance(); /** * <code>optional .org.jetbrains.javac.Message.Response.OutputObject output_object = 3;</code> */ public boolean hasOutputObject() { return ((bitField0_ & 0x00000004) == 0x00000004); } /** * <code>optional .org.jetbrains.javac.Message.Response.OutputObject output_object = 3;</code> */ public org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.OutputObject getOutputObject() { return outputObject_; } /** * <code>optional .org.jetbrains.javac.Message.Response.OutputObject output_object = 3;</code> */ public Builder setOutputObject(org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.OutputObject value) { if (value == null) { throw new NullPointerException(); } outputObject_ = value; bitField0_ |= 0x00000004; return this; } /** * <code>optional .org.jetbrains.javac.Message.Response.OutputObject output_object = 3;</code> */ public Builder setOutputObject( org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.OutputObject.Builder builderForValue) { outputObject_ = builderForValue.build(); bitField0_ |= 0x00000004; return this; } /** * <code>optional .org.jetbrains.javac.Message.Response.OutputObject output_object = 3;</code> */ public Builder mergeOutputObject(org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.OutputObject value) { if (((bitField0_ & 0x00000004) == 0x00000004) && outputObject_ != org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.OutputObject.getDefaultInstance()) { outputObject_ = org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.OutputObject.newBuilder(outputObject_).mergeFrom(value).buildPartial(); } else { outputObject_ = value; } bitField0_ |= 0x00000004; return this; } /** * <code>optional .org.jetbrains.javac.Message.Response.OutputObject output_object = 3;</code> */ public Builder clearOutputObject() { outputObject_ = org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.OutputObject.getDefaultInstance(); bitField0_ = (bitField0_ & ~0x00000004); return this; } // optional .org.jetbrains.javac.Message.Response.ClassData class_data = 4; private org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.ClassData classData_ = org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.ClassData.getDefaultInstance(); /** * <code>optional .org.jetbrains.javac.Message.Response.ClassData class_data = 4;</code> */ public boolean hasClassData() { return ((bitField0_ & 0x00000008) == 0x00000008); } /** * <code>optional .org.jetbrains.javac.Message.Response.ClassData class_data = 4;</code> */ public org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.ClassData getClassData() { return classData_; } /** * <code>optional .org.jetbrains.javac.Message.Response.ClassData class_data = 4;</code> */ public Builder setClassData(org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.ClassData value) { if (value == null) { throw new NullPointerException(); } classData_ = value; bitField0_ |= 0x00000008; return this; } /** * <code>optional .org.jetbrains.javac.Message.Response.ClassData class_data = 4;</code> */ public Builder setClassData( org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.ClassData.Builder builderForValue) { classData_ = builderForValue.build(); bitField0_ |= 0x00000008; return this; } /** * <code>optional .org.jetbrains.javac.Message.Response.ClassData class_data = 4;</code> */ public Builder mergeClassData(org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.ClassData value) { if (((bitField0_ & 0x00000008) == 0x00000008) && classData_ != org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.ClassData.getDefaultInstance()) { classData_ = org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.ClassData.newBuilder(classData_).mergeFrom(value).buildPartial(); } else { classData_ = value; } bitField0_ |= 0x00000008; return this; } /** * <code>optional .org.jetbrains.javac.Message.Response.ClassData class_data = 4;</code> */ public Builder clearClassData() { classData_ = org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.ClassData.getDefaultInstance(); bitField0_ = (bitField0_ & ~0x00000008); return this; } // optional bool completion_status = 5; private boolean completionStatus_ ; /** * <code>optional bool completion_status = 5;</code> */ public boolean hasCompletionStatus() { return ((bitField0_ & 0x00000010) == 0x00000010); } /** * <code>optional bool completion_status = 5;</code> */ public boolean getCompletionStatus() { return completionStatus_; } /** * <code>optional bool completion_status = 5;</code> */ public Builder setCompletionStatus(boolean value) { bitField0_ |= 0x00000010; completionStatus_ = value; return this; } /** * <code>optional bool completion_status = 5;</code> */ public Builder clearCompletionStatus() { bitField0_ = (bitField0_ & ~0x00000010); completionStatus_ = false; return this; } // @@protoc_insertion_point(builder_scope:org.jetbrains.javac.Message.Response) } static { defaultInstance = new Response(true); defaultInstance.initFields(); } // @@protoc_insertion_point(class_scope:org.jetbrains.javac.Message.Response) } private int bitField0_; // required .org.jetbrains.javac.Message.UUID session_id = 1; public static final int SESSION_ID_FIELD_NUMBER = 1; private org.jetbrains.jps.javac.JavacRemoteProto.Message.UUID sessionId_; /** * <code>required .org.jetbrains.javac.Message.UUID session_id = 1;</code> */ public boolean hasSessionId() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * <code>required .org.jetbrains.javac.Message.UUID session_id = 1;</code> */ public org.jetbrains.jps.javac.JavacRemoteProto.Message.UUID getSessionId() { return sessionId_; } // required .org.jetbrains.javac.Message.Type message_type = 2; public static final int MESSAGE_TYPE_FIELD_NUMBER = 2; private org.jetbrains.jps.javac.JavacRemoteProto.Message.Type messageType_; /** * <code>required .org.jetbrains.javac.Message.Type message_type = 2;</code> */ public boolean hasMessageType() { return ((bitField0_ & 0x00000002) == 0x00000002); } /** * <code>required .org.jetbrains.javac.Message.Type message_type = 2;</code> */ public org.jetbrains.jps.javac.JavacRemoteProto.Message.Type getMessageType() { return messageType_; } // optional .org.jetbrains.javac.Message.Request request = 3; public static final int REQUEST_FIELD_NUMBER = 3; private org.jetbrains.jps.javac.JavacRemoteProto.Message.Request request_; /** * <code>optional .org.jetbrains.javac.Message.Request request = 3;</code> */ public boolean hasRequest() { return ((bitField0_ & 0x00000004) == 0x00000004); } /** * <code>optional .org.jetbrains.javac.Message.Request request = 3;</code> */ public org.jetbrains.jps.javac.JavacRemoteProto.Message.Request getRequest() { return request_; } // optional .org.jetbrains.javac.Message.Response response = 4; public static final int RESPONSE_FIELD_NUMBER = 4; private org.jetbrains.jps.javac.JavacRemoteProto.Message.Response response_; /** * <code>optional .org.jetbrains.javac.Message.Response response = 4;</code> */ public boolean hasResponse() { return ((bitField0_ & 0x00000008) == 0x00000008); } /** * <code>optional .org.jetbrains.javac.Message.Response response = 4;</code> */ public org.jetbrains.jps.javac.JavacRemoteProto.Message.Response getResponse() { return response_; } // optional .org.jetbrains.javac.Message.Failure failure = 5; public static final int FAILURE_FIELD_NUMBER = 5; private org.jetbrains.jps.javac.JavacRemoteProto.Message.Failure failure_; /** * <code>optional .org.jetbrains.javac.Message.Failure failure = 5;</code> */ public boolean hasFailure() { return ((bitField0_ & 0x00000010) == 0x00000010); } /** * <code>optional .org.jetbrains.javac.Message.Failure failure = 5;</code> */ public org.jetbrains.jps.javac.JavacRemoteProto.Message.Failure getFailure() { return failure_; } private void initFields() { sessionId_ = org.jetbrains.jps.javac.JavacRemoteProto.Message.UUID.getDefaultInstance(); messageType_ = org.jetbrains.jps.javac.JavacRemoteProto.Message.Type.REQUEST; request_ = org.jetbrains.jps.javac.JavacRemoteProto.Message.Request.getDefaultInstance(); response_ = org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.getDefaultInstance(); failure_ = org.jetbrains.jps.javac.JavacRemoteProto.Message.Failure.getDefaultInstance(); } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized != -1) return isInitialized == 1; if (!hasSessionId()) { memoizedIsInitialized = 0; return false; } if (!hasMessageType()) { memoizedIsInitialized = 0; return false; } if (!getSessionId().isInitialized()) { memoizedIsInitialized = 0; return false; } if (hasRequest()) { if (!getRequest().isInitialized()) { memoizedIsInitialized = 0; return false; } } if (hasResponse()) { if (!getResponse().isInitialized()) { memoizedIsInitialized = 0; return false; } } memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getSerializedSize(); if (((bitField0_ & 0x00000001) == 0x00000001)) { output.writeMessage(1, sessionId_); } if (((bitField0_ & 0x00000002) == 0x00000002)) { output.writeEnum(2, messageType_.getNumber()); } if (((bitField0_ & 0x00000004) == 0x00000004)) { output.writeMessage(3, request_); } if (((bitField0_ & 0x00000008) == 0x00000008)) { output.writeMessage(4, response_); } if (((bitField0_ & 0x00000010) == 0x00000010)) { output.writeMessage(5, failure_); } } private int memoizedSerializedSize = -1; public int getSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; if (((bitField0_ & 0x00000001) == 0x00000001)) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(1, sessionId_); } if (((bitField0_ & 0x00000002) == 0x00000002)) { size += com.google.protobuf.CodedOutputStream .computeEnumSize(2, messageType_.getNumber()); } if (((bitField0_ & 0x00000004) == 0x00000004)) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(3, request_); } if (((bitField0_ & 0x00000008) == 0x00000008)) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(4, response_); } if (((bitField0_ & 0x00000010) == 0x00000010)) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(5, failure_); } memoizedSerializedSize = size; return size; } private static final long serialVersionUID = 0L; @java.lang.Override protected java.lang.Object writeReplace() throws java.io.ObjectStreamException { return super.writeReplace(); } public static org.jetbrains.jps.javac.JavacRemoteProto.Message parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static org.jetbrains.jps.javac.JavacRemoteProto.Message parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static org.jetbrains.jps.javac.JavacRemoteProto.Message parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static org.jetbrains.jps.javac.JavacRemoteProto.Message parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static org.jetbrains.jps.javac.JavacRemoteProto.Message parseFrom(java.io.InputStream input) throws java.io.IOException { return PARSER.parseFrom(input); } public static org.jetbrains.jps.javac.JavacRemoteProto.Message parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } public static org.jetbrains.jps.javac.JavacRemoteProto.Message parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return PARSER.parseDelimitedFrom(input); } public static org.jetbrains.jps.javac.JavacRemoteProto.Message parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseDelimitedFrom(input, extensionRegistry); } public static org.jetbrains.jps.javac.JavacRemoteProto.Message parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return PARSER.parseFrom(input); } public static org.jetbrains.jps.javac.JavacRemoteProto.Message parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } public static Builder newBuilder() { return Builder.create(); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder(org.jetbrains.jps.javac.JavacRemoteProto.Message prototype) { return newBuilder().mergeFrom(prototype); } public Builder toBuilder() { return newBuilder(this); } /** * Protobuf type {@code org.jetbrains.javac.Message} */ public static final class Builder extends com.google.protobuf.GeneratedMessageLite.Builder< org.jetbrains.jps.javac.JavacRemoteProto.Message, Builder> implements org.jetbrains.jps.javac.JavacRemoteProto.MessageOrBuilder { // Construct using org.jetbrains.jps.javac.JavacRemoteProto.Message.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { } private static Builder create() { return new Builder(); } public Builder clear() { super.clear(); sessionId_ = org.jetbrains.jps.javac.JavacRemoteProto.Message.UUID.getDefaultInstance(); bitField0_ = (bitField0_ & ~0x00000001); messageType_ = org.jetbrains.jps.javac.JavacRemoteProto.Message.Type.REQUEST; bitField0_ = (bitField0_ & ~0x00000002); request_ = org.jetbrains.jps.javac.JavacRemoteProto.Message.Request.getDefaultInstance(); bitField0_ = (bitField0_ & ~0x00000004); response_ = org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.getDefaultInstance(); bitField0_ = (bitField0_ & ~0x00000008); failure_ = org.jetbrains.jps.javac.JavacRemoteProto.Message.Failure.getDefaultInstance(); bitField0_ = (bitField0_ & ~0x00000010); return this; } public Builder clone() { return create().mergeFrom(buildPartial()); } public org.jetbrains.jps.javac.JavacRemoteProto.Message getDefaultInstanceForType() { return org.jetbrains.jps.javac.JavacRemoteProto.Message.getDefaultInstance(); } public org.jetbrains.jps.javac.JavacRemoteProto.Message build() { org.jetbrains.jps.javac.JavacRemoteProto.Message result = buildPartial(); if (!result.isInitialized()) { throw Builder.newUninitializedMessageException(result); } return result; } public org.jetbrains.jps.javac.JavacRemoteProto.Message buildPartial() { org.jetbrains.jps.javac.JavacRemoteProto.Message result = new org.jetbrains.jps.javac.JavacRemoteProto.Message(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) == 0x00000001)) { to_bitField0_ |= 0x00000001; } result.sessionId_ = sessionId_; if (((from_bitField0_ & 0x00000002) == 0x00000002)) { to_bitField0_ |= 0x00000002; } result.messageType_ = messageType_; if (((from_bitField0_ & 0x00000004) == 0x00000004)) { to_bitField0_ |= 0x00000004; } result.request_ = request_; if (((from_bitField0_ & 0x00000008) == 0x00000008)) { to_bitField0_ |= 0x00000008; } result.response_ = response_; if (((from_bitField0_ & 0x00000010) == 0x00000010)) { to_bitField0_ |= 0x00000010; } result.failure_ = failure_; result.bitField0_ = to_bitField0_; return result; } public Builder mergeFrom(org.jetbrains.jps.javac.JavacRemoteProto.Message other) { if (other == org.jetbrains.jps.javac.JavacRemoteProto.Message.getDefaultInstance()) return this; if (other.hasSessionId()) { mergeSessionId(other.getSessionId()); } if (other.hasMessageType()) { setMessageType(other.getMessageType()); } if (other.hasRequest()) { mergeRequest(other.getRequest()); } if (other.hasResponse()) { mergeResponse(other.getResponse()); } if (other.hasFailure()) { mergeFailure(other.getFailure()); } return this; } public final boolean isInitialized() { if (!hasSessionId()) { return false; } if (!hasMessageType()) { return false; } if (!getSessionId().isInitialized()) { return false; } if (hasRequest()) { if (!getRequest().isInitialized()) { return false; } } if (hasResponse()) { if (!getResponse().isInitialized()) { return false; } } return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { org.jetbrains.jps.javac.JavacRemoteProto.Message parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (org.jetbrains.jps.javac.JavacRemoteProto.Message) e.getUnfinishedMessage(); throw e; } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; // required .org.jetbrains.javac.Message.UUID session_id = 1; private org.jetbrains.jps.javac.JavacRemoteProto.Message.UUID sessionId_ = org.jetbrains.jps.javac.JavacRemoteProto.Message.UUID.getDefaultInstance(); /** * <code>required .org.jetbrains.javac.Message.UUID session_id = 1;</code> */ public boolean hasSessionId() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * <code>required .org.jetbrains.javac.Message.UUID session_id = 1;</code> */ public org.jetbrains.jps.javac.JavacRemoteProto.Message.UUID getSessionId() { return sessionId_; } /** * <code>required .org.jetbrains.javac.Message.UUID session_id = 1;</code> */ public Builder setSessionId(org.jetbrains.jps.javac.JavacRemoteProto.Message.UUID value) { if (value == null) { throw new NullPointerException(); } sessionId_ = value; bitField0_ |= 0x00000001; return this; } /** * <code>required .org.jetbrains.javac.Message.UUID session_id = 1;</code> */ public Builder setSessionId( org.jetbrains.jps.javac.JavacRemoteProto.Message.UUID.Builder builderForValue) { sessionId_ = builderForValue.build(); bitField0_ |= 0x00000001; return this; } /** * <code>required .org.jetbrains.javac.Message.UUID session_id = 1;</code> */ public Builder mergeSessionId(org.jetbrains.jps.javac.JavacRemoteProto.Message.UUID value) { if (((bitField0_ & 0x00000001) == 0x00000001) && sessionId_ != org.jetbrains.jps.javac.JavacRemoteProto.Message.UUID.getDefaultInstance()) { sessionId_ = org.jetbrains.jps.javac.JavacRemoteProto.Message.UUID.newBuilder(sessionId_).mergeFrom(value).buildPartial(); } else { sessionId_ = value; } bitField0_ |= 0x00000001; return this; } /** * <code>required .org.jetbrains.javac.Message.UUID session_id = 1;</code> */ public Builder clearSessionId() { sessionId_ = org.jetbrains.jps.javac.JavacRemoteProto.Message.UUID.getDefaultInstance(); bitField0_ = (bitField0_ & ~0x00000001); return this; } // required .org.jetbrains.javac.Message.Type message_type = 2; private org.jetbrains.jps.javac.JavacRemoteProto.Message.Type messageType_ = org.jetbrains.jps.javac.JavacRemoteProto.Message.Type.REQUEST; /** * <code>required .org.jetbrains.javac.Message.Type message_type = 2;</code> */ public boolean hasMessageType() { return ((bitField0_ & 0x00000002) == 0x00000002); } /** * <code>required .org.jetbrains.javac.Message.Type message_type = 2;</code> */ public org.jetbrains.jps.javac.JavacRemoteProto.Message.Type getMessageType() { return messageType_; } /** * <code>required .org.jetbrains.javac.Message.Type message_type = 2;</code> */ public Builder setMessageType(org.jetbrains.jps.javac.JavacRemoteProto.Message.Type value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000002; messageType_ = value; return this; } /** * <code>required .org.jetbrains.javac.Message.Type message_type = 2;</code> */ public Builder clearMessageType() { bitField0_ = (bitField0_ & ~0x00000002); messageType_ = org.jetbrains.jps.javac.JavacRemoteProto.Message.Type.REQUEST; return this; } // optional .org.jetbrains.javac.Message.Request request = 3; private org.jetbrains.jps.javac.JavacRemoteProto.Message.Request request_ = org.jetbrains.jps.javac.JavacRemoteProto.Message.Request.getDefaultInstance(); /** * <code>optional .org.jetbrains.javac.Message.Request request = 3;</code> */ public boolean hasRequest() { return ((bitField0_ & 0x00000004) == 0x00000004); } /** * <code>optional .org.jetbrains.javac.Message.Request request = 3;</code> */ public org.jetbrains.jps.javac.JavacRemoteProto.Message.Request getRequest() { return request_; } /** * <code>optional .org.jetbrains.javac.Message.Request request = 3;</code> */ public Builder setRequest(org.jetbrains.jps.javac.JavacRemoteProto.Message.Request value) { if (value == null) { throw new NullPointerException(); } request_ = value; bitField0_ |= 0x00000004; return this; } /** * <code>optional .org.jetbrains.javac.Message.Request request = 3;</code> */ public Builder setRequest( org.jetbrains.jps.javac.JavacRemoteProto.Message.Request.Builder builderForValue) { request_ = builderForValue.build(); bitField0_ |= 0x00000004; return this; } /** * <code>optional .org.jetbrains.javac.Message.Request request = 3;</code> */ public Builder mergeRequest(org.jetbrains.jps.javac.JavacRemoteProto.Message.Request value) { if (((bitField0_ & 0x00000004) == 0x00000004) && request_ != org.jetbrains.jps.javac.JavacRemoteProto.Message.Request.getDefaultInstance()) { request_ = org.jetbrains.jps.javac.JavacRemoteProto.Message.Request.newBuilder(request_).mergeFrom(value).buildPartial(); } else { request_ = value; } bitField0_ |= 0x00000004; return this; } /** * <code>optional .org.jetbrains.javac.Message.Request request = 3;</code> */ public Builder clearRequest() { request_ = org.jetbrains.jps.javac.JavacRemoteProto.Message.Request.getDefaultInstance(); bitField0_ = (bitField0_ & ~0x00000004); return this; } // optional .org.jetbrains.javac.Message.Response response = 4; private org.jetbrains.jps.javac.JavacRemoteProto.Message.Response response_ = org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.getDefaultInstance(); /** * <code>optional .org.jetbrains.javac.Message.Response response = 4;</code> */ public boolean hasResponse() { return ((bitField0_ & 0x00000008) == 0x00000008); } /** * <code>optional .org.jetbrains.javac.Message.Response response = 4;</code> */ public org.jetbrains.jps.javac.JavacRemoteProto.Message.Response getResponse() { return response_; } /** * <code>optional .org.jetbrains.javac.Message.Response response = 4;</code> */ public Builder setResponse(org.jetbrains.jps.javac.JavacRemoteProto.Message.Response value) { if (value == null) { throw new NullPointerException(); } response_ = value; bitField0_ |= 0x00000008; return this; } /** * <code>optional .org.jetbrains.javac.Message.Response response = 4;</code> */ public Builder setResponse( org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.Builder builderForValue) { response_ = builderForValue.build(); bitField0_ |= 0x00000008; return this; } /** * <code>optional .org.jetbrains.javac.Message.Response response = 4;</code> */ public Builder mergeResponse(org.jetbrains.jps.javac.JavacRemoteProto.Message.Response value) { if (((bitField0_ & 0x00000008) == 0x00000008) && response_ != org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.getDefaultInstance()) { response_ = org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.newBuilder(response_).mergeFrom(value).buildPartial(); } else { response_ = value; } bitField0_ |= 0x00000008; return this; } /** * <code>optional .org.jetbrains.javac.Message.Response response = 4;</code> */ public Builder clearResponse() { response_ = org.jetbrains.jps.javac.JavacRemoteProto.Message.Response.getDefaultInstance(); bitField0_ = (bitField0_ & ~0x00000008); return this; } // optional .org.jetbrains.javac.Message.Failure failure = 5; private org.jetbrains.jps.javac.JavacRemoteProto.Message.Failure failure_ = org.jetbrains.jps.javac.JavacRemoteProto.Message.Failure.getDefaultInstance(); /** * <code>optional .org.jetbrains.javac.Message.Failure failure = 5;</code> */ public boolean hasFailure() { return ((bitField0_ & 0x00000010) == 0x00000010); } /** * <code>optional .org.jetbrains.javac.Message.Failure failure = 5;</code> */ public org.jetbrains.jps.javac.JavacRemoteProto.Message.Failure getFailure() { return failure_; } /** * <code>optional .org.jetbrains.javac.Message.Failure failure = 5;</code> */ public Builder setFailure(org.jetbrains.jps.javac.JavacRemoteProto.Message.Failure value) { if (value == null) { throw new NullPointerException(); } failure_ = value; bitField0_ |= 0x00000010; return this; } /** * <code>optional .org.jetbrains.javac.Message.Failure failure = 5;</code> */ public Builder setFailure( org.jetbrains.jps.javac.JavacRemoteProto.Message.Failure.Builder builderForValue) { failure_ = builderForValue.build(); bitField0_ |= 0x00000010; return this; } /** * <code>optional .org.jetbrains.javac.Message.Failure failure = 5;</code> */ public Builder mergeFailure(org.jetbrains.jps.javac.JavacRemoteProto.Message.Failure value) { if (((bitField0_ & 0x00000010) == 0x00000010) && failure_ != org.jetbrains.jps.javac.JavacRemoteProto.Message.Failure.getDefaultInstance()) { failure_ = org.jetbrains.jps.javac.JavacRemoteProto.Message.Failure.newBuilder(failure_).mergeFrom(value).buildPartial(); } else { failure_ = value; } bitField0_ |= 0x00000010; return this; } /** * <code>optional .org.jetbrains.javac.Message.Failure failure = 5;</code> */ public Builder clearFailure() { failure_ = org.jetbrains.jps.javac.JavacRemoteProto.Message.Failure.getDefaultInstance(); bitField0_ = (bitField0_ & ~0x00000010); return this; } // @@protoc_insertion_point(builder_scope:org.jetbrains.javac.Message) } static { defaultInstance = new Message(true); defaultInstance.initFields(); } // @@protoc_insertion_point(class_scope:org.jetbrains.javac.Message) } static { } // @@protoc_insertion_point(outer_class_scope) }
apache-2.0
google/mr4c
java/test/java/com/google/mr4c/mbtiles/MBTilesTestUtil.java
2160
/** * Copyright 2014 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.mr4c.mbtiles; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.junit.*; import static org.junit.Assert.*; public abstract class MBTilesTestUtil { public static Map<String,String> generateTestMetadata(int count) { Map<String,String> meta = new HashMap<String,String>(); for ( int i=1; i<=count; i++ ) { meta.put("prop"+i, "val"+i); } return meta; } public static List<Tile> generateTestTiles(int count) { List<Tile> tiles = new ArrayList<Tile>(); for ( int i=1; i<=count; i++ ) { tiles.add(buildTile(i)); } return tiles; } private static Tile buildTile(int index) { int zoom = index; int x = index * zoom; int y = index * x; return buildTile(zoom, x, y); } private static Tile buildTile(int zoom, int x, int y) { TileKey key = new TileKey(zoom, x, y); byte[] data = new byte[] { (byte) zoom, (byte) x, (byte) y }; return new Tile(key, data); } public static void checkTiles(MBTilesFile mbtiles, List<Tile> expectedTiles) throws Exception { Set<TileKey> keys = new HashSet<TileKey>(); for ( Tile tile : expectedTiles ) { keys.add(tile.getKey()); assertEquals(tile, mbtiles.findTile(tile.getKey())); } assertEquals(keys, mbtiles.getAllTileKeys()); } public static void cleanup(Iterable<MBTilesFile> files ) throws IOException { for ( MBTilesFile file : files ) { file.close(); } } }
apache-2.0
renatoathaydes/checker-framework
checker/src/org/checkerframework/checker/nullness/compatqual/KeyForDecl.java
500
package org.checkerframework.checker.nullness.compatqual; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /** * Java 7 compatibility annotation without dependency on Java 8 classes. * * @see org.checkerframework.checker.nullness.qual.KeyFor * @checker_framework.manual #nullness-checker Nullness Checker */ @Documented @Retention(RetentionPolicy.RUNTIME) public @interface KeyForDecl { public String[] value(); }
gpl-2.0
helloiloveit/VkxPhoneProject
submodules/externals/antlr3/tool/src/test/java/org/antlr/test/TestRewriteAST.java
47005
/* * [The "BSD license"] * Copyright (c) 2010 Terence Parr * 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. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 org.antlr.test; import org.antlr.Tool; import org.antlr.codegen.CodeGenerator; import org.antlr.tool.ErrorManager; import org.antlr.tool.Grammar; import org.antlr.tool.GrammarSemanticsMessage; import org.junit.Ignore; import org.junit.Test; public class TestRewriteAST extends BaseTest { protected boolean debug = false; @Test public void testDelete() throws Exception { String grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : ID INT -> ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; String found = execParser("T.g", grammar, "TParser", "TLexer", "a", "abc 34", debug); assertEquals("", found); } @Test public void testSingleToken() throws Exception { String grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : ID -> ID;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; String found = execParser("T.g", grammar, "TParser", "TLexer", "a", "abc", debug); assertEquals("abc\n", found); } @Test public void testSingleTokenToNewNode() throws Exception { String grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : ID -> ID[\"x\"];\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; String found = execParser("T.g", grammar, "TParser", "TLexer", "a", "abc", debug); assertEquals("x\n", found); } @Test public void testSingleTokenToNewNodeRoot() throws Exception { String grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : ID -> ^(ID[\"x\"] INT);\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; String found = execParser("T.g", grammar, "TParser", "TLexer", "a", "abc", debug); assertEquals("(x INT)\n", found); } @Test public void testSingleTokenToNewNode2() throws Exception { // Allow creation of new nodes w/o args. String grammar = "grammar TT;\n" + "options {output=AST;}\n" + "a : ID -> ID[ ];\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; String found = execParser("TT.g", grammar, "TTParser", "TTLexer", "a", "abc", debug); assertEquals("ID\n", found); } @Test public void testSingleCharLiteral() throws Exception { String grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : 'c' -> 'c';\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; String found = execParser("T.g", grammar, "TParser", "TLexer", "a", "c", debug); assertEquals("c\n", found); } @Test public void testSingleStringLiteral() throws Exception { String grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : 'ick' -> 'ick';\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; String found = execParser("T.g", grammar, "TParser", "TLexer", "a", "ick", debug); assertEquals("ick\n", found); } @Test public void testSingleRule() throws Exception { String grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : b -> b;\n" + "b : ID ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; String found = execParser("T.g", grammar, "TParser", "TLexer", "a", "abc", debug); assertEquals("abc\n", found); } @Test public void testReorderTokens() throws Exception { String grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : ID INT -> INT ID;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; String found = execParser("T.g", grammar, "TParser", "TLexer", "a", "abc 34", debug); assertEquals("34 abc\n", found); } @Test public void testReorderTokenAndRule() throws Exception { String grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : b INT -> INT b;\n" + "b : ID ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; String found = execParser("T.g", grammar, "TParser", "TLexer", "a", "abc 34", debug); assertEquals("34 abc\n", found); } @Test public void testTokenTree() throws Exception { String grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : ID INT -> ^(INT ID);\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; String found = execParser("T.g", grammar, "TParser", "TLexer", "a", "abc 34", debug); assertEquals("(34 abc)\n", found); } @Test public void testTokenTreeAfterOtherStuff() throws Exception { String grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : 'void' ID INT -> 'void' ^(INT ID);\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; String found = execParser("T.g", grammar, "TParser", "TLexer", "a", "void abc 34", debug); assertEquals("void (34 abc)\n", found); } @Test public void testNestedTokenTreeWithOuterLoop() throws Exception { // verify that ID and INT both iterate over outer index variable String grammar = "grammar T;\n" + "options {output=AST;}\n" + "tokens {DUH;}\n" + "a : ID INT ID INT -> ^( DUH ID ^( DUH INT) )+ ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; String found = execParser("T.g", grammar, "TParser", "TLexer", "a", "a 1 b 2", debug); assertEquals("(DUH a (DUH 1)) (DUH b (DUH 2))\n", found); } @Test public void testOptionalSingleToken() throws Exception { String grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : ID -> ID? ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; String found = execParser("T.g", grammar, "TParser", "TLexer", "a", "abc", debug); assertEquals("abc\n", found); } @Test public void testClosureSingleToken() throws Exception { String grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : ID ID -> ID* ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; String found = execParser("T.g", grammar, "TParser", "TLexer", "a", "a b", debug); assertEquals("a b\n", found); } @Test public void testPositiveClosureSingleToken() throws Exception { String grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : ID ID -> ID+ ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; String found = execParser("T.g", grammar, "TParser", "TLexer", "a", "a b", debug); assertEquals("a b\n", found); } @Test public void testOptionalSingleRule() throws Exception { String grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : b -> b?;\n" + "b : ID ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; String found = execParser("T.g", grammar, "TParser", "TLexer", "a", "abc", debug); assertEquals("abc\n", found); } @Test public void testClosureSingleRule() throws Exception { String grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : b b -> b*;\n" + "b : ID ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; String found = execParser("T.g", grammar, "TParser", "TLexer", "a", "a b", debug); assertEquals("a b\n", found); } @Test public void testClosureOfLabel() throws Exception { String grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : x+=b x+=b -> $x*;\n" + "b : ID ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; String found = execParser("T.g", grammar, "TParser", "TLexer", "a", "a b", debug); assertEquals("a b\n", found); } @Test public void testOptionalLabelNoListLabel() throws Exception { String grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : (x=ID)? -> $x?;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; String found = execParser("T.g", grammar, "TParser", "TLexer", "a", "a", debug); assertEquals("a\n", found); } @Test public void testPositiveClosureSingleRule() throws Exception { String grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : b b -> b+;\n" + "b : ID ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; String found = execParser("T.g", grammar, "TParser", "TLexer", "a", "a b", debug); assertEquals("a b\n", found); } @Test public void testSinglePredicateT() throws Exception { String grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : ID -> {true}? ID -> ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; String found = execParser("T.g", grammar, "TParser", "TLexer", "a", "abc", debug); assertEquals("abc\n", found); } @Test public void testSinglePredicateF() throws Exception { String grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : ID -> {false}? ID -> ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; String found = execParser("T.g", grammar, "TParser", "TLexer", "a", "abc", debug); assertEquals("", found); } @Test public void testMultiplePredicate() throws Exception { String grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : ID INT -> {false}? ID\n" + " -> {true}? INT\n" + " -> \n" + " ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; String found = execParser("T.g", grammar, "TParser", "TLexer", "a", "a 2", debug); assertEquals("2\n", found); } @Test public void testMultiplePredicateTrees() throws Exception { String grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : ID INT -> {false}? ^(ID INT)\n" + " -> {true}? ^(INT ID)\n" + " -> ID\n" + " ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; String found = execParser("T.g", grammar, "TParser", "TLexer", "a", "a 2", debug); assertEquals("(2 a)\n", found); } @Test public void testSimpleTree() throws Exception { String grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : op INT -> ^(op INT);\n" + "op : '+'|'-' ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; String found = execParser("T.g", grammar, "TParser", "TLexer", "a", "-34", debug); assertEquals("(- 34)\n", found); } @Test public void testSimpleTree2() throws Exception { String grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : op INT -> ^(INT op);\n" + "op : '+'|'-' ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; String found = execParser("T.g", grammar, "TParser", "TLexer", "a", "+ 34", debug); assertEquals("(34 +)\n", found); } @Test public void testNestedTrees() throws Exception { String grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : 'var' (ID ':' type ';')+ -> ^('var' ^(':' ID type)+) ;\n" + "type : 'int' | 'float' ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; String found = execParser("T.g", grammar, "TParser", "TLexer", "a", "var a:int; b:float;", debug); assertEquals("(var (: a int) (: b float))\n", found); } @Test public void testImaginaryTokenCopy() throws Exception { String grammar = "grammar T;\n" + "options {output=AST;}\n" + "tokens {VAR;}\n" + "a : ID (',' ID)*-> ^(VAR ID)+ ;\n" + "type : 'int' | 'float' ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; String found = execParser("T.g", grammar, "TParser", "TLexer", "a", "a,b,c", debug); assertEquals("(VAR a) (VAR b) (VAR c)\n", found); } @Test public void testTokenUnreferencedOnLeftButDefined() throws Exception { String grammar = "grammar T;\n" + "options {output=AST;}\n" + "tokens {VAR;}\n" + "a : b -> ID ;\n" + "b : ID ;\n"+ "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; String found = execParser("T.g", grammar, "TParser", "TLexer", "a", "a", debug); assertEquals("ID\n", found); } @Test public void testImaginaryTokenCopySetText() throws Exception { String grammar = "grammar T;\n" + "options {output=AST;}\n" + "tokens {VAR;}\n" + "a : ID (',' ID)*-> ^(VAR[\"var\"] ID)+ ;\n" + "type : 'int' | 'float' ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; String found = execParser("T.g", grammar, "TParser", "TLexer", "a", "a,b,c", debug); assertEquals("(var a) (var b) (var c)\n", found); } @Test public void testImaginaryTokenNoCopyFromToken() throws Exception { String grammar = "grammar T;\n" + "options {output=AST;}\n" + "tokens {BLOCK;}\n" + "a : lc='{' ID+ '}' -> ^(BLOCK[$lc] ID+) ;\n" + "type : 'int' | 'float' ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; String found = execParser("T.g", grammar, "TParser", "TLexer", "a", "{a b c}", debug); assertEquals("({ a b c)\n", found); } @Test public void testImaginaryTokenNoCopyFromTokenSetText() throws Exception { String grammar = "grammar T;\n" + "options {output=AST;}\n" + "tokens {BLOCK;}\n" + "a : lc='{' ID+ '}' -> ^(BLOCK[$lc,\"block\"] ID+) ;\n" + "type : 'int' | 'float' ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; String found = execParser("T.g", grammar, "TParser", "TLexer", "a", "{a b c}", debug); assertEquals("(block a b c)\n", found); } @Test public void testMixedRewriteAndAutoAST() throws Exception { String grammar = "grammar T;\n" + "options {output=AST;}\n" + "tokens {BLOCK;}\n" + "a : b b^ ;\n" + // 2nd b matches only an INT; can make it root "b : ID INT -> INT ID\n" + " | INT\n" + " ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; String found = execParser("T.g", grammar, "TParser", "TLexer", "a", "a 1 2", debug); assertEquals("(2 1 a)\n", found); } @Test public void testSubruleWithRewrite() throws Exception { String grammar = "grammar T;\n" + "options {output=AST;}\n" + "tokens {BLOCK;}\n" + "a : b b ;\n" + "b : (ID INT -> INT ID | INT INT -> INT+ )\n" + " ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; String found = execParser("T.g", grammar, "TParser", "TLexer", "a", "a 1 2 3", debug); assertEquals("1 a 2 3\n", found); } @Test public void testSubruleWithRewrite2() throws Exception { String grammar = "grammar T;\n" + "options {output=AST;}\n" + "tokens {TYPE;}\n" + "a : b b ;\n" + "b : 'int'\n" + " ( ID -> ^(TYPE 'int' ID)\n" + " | ID '=' INT -> ^(TYPE 'int' ID INT)\n" + " )\n" + " ';'\n" + " ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; String found = execParser("T.g", grammar, "TParser", "TLexer", "a", "int a; int b=3;", debug); assertEquals("(TYPE int a) (TYPE int b 3)\n", found); } @Test public void testNestedRewriteShutsOffAutoAST() throws Exception { String grammar = "grammar T;\n" + "options {output=AST;}\n" + "tokens {BLOCK;}\n" + "a : b b ;\n" + "b : ID ( ID (last=ID -> $last)+ ) ';'\n" + // get last ID " | INT\n" + // should still get auto AST construction " ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; String found = execParser("T.g", grammar, "TParser", "TLexer", "a", "a b c d; 42", debug); assertEquals("d 42\n", found); } @Test public void testRewriteActions() throws Exception { String grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : atom -> ^({adaptor.create(INT,\"9\")} atom) ;\n" + "atom : INT ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; String found = execParser("T.g", grammar, "TParser", "TLexer", "a", "3", debug); assertEquals("(9 3)\n", found); } @Test public void testRewriteActions2() throws Exception { String grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : atom -> {adaptor.create(INT,\"9\")} atom ;\n" + "atom : INT ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; String found = execParser("T.g", grammar, "TParser", "TLexer", "a", "3", debug); assertEquals("9 3\n", found); } @Test public void testRefToOldValue() throws Exception { String grammar = "grammar T;\n" + "options {output=AST;}\n" + "tokens {BLOCK;}\n" + "a : (atom -> atom) (op='+' r=atom -> ^($op $a $r) )* ;\n" + "atom : INT ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; String found = execParser("T.g", grammar, "TParser", "TLexer", "a", "3+4+5", debug); assertEquals("(+ (+ 3 4) 5)\n", found); } @Test public void testCopySemanticsForRules() throws Exception { String grammar = "grammar T;\n" + "options {output=AST;}\n" + "tokens {BLOCK;}\n" + "a : atom -> ^(atom atom) ;\n" + // NOT CYCLE! (dup atom) "atom : INT ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; String found = execParser("T.g", grammar, "TParser", "TLexer", "a", "3", debug); assertEquals("(3 3)\n", found); } @Test public void testCopySemanticsForRules2() throws Exception { // copy type as a root for each invocation of (...)+ in rewrite String grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : type ID (',' ID)* ';' -> ^(type ID)+ ;\n" + "type : 'int' ;\n" + "ID : 'a'..'z'+ ;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; String found = execParser("T.g", grammar, "TParser", "TLexer", "a", "int a,b,c;", debug); assertEquals("(int a) (int b) (int c)\n", found); } @Test public void testCopySemanticsForRules3() throws Exception { // copy type *and* modifier even though it's optional // for each invocation of (...)+ in rewrite String grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : modifier? type ID (',' ID)* ';' -> ^(type modifier? ID)+ ;\n" + "type : 'int' ;\n" + "modifier : 'public' ;\n" + "ID : 'a'..'z'+ ;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; String found = execParser("T.g", grammar, "TParser", "TLexer", "a", "public int a,b,c;", debug); assertEquals("(int public a) (int public b) (int public c)\n", found); } @Test public void testCopySemanticsForRules3Double() throws Exception { // copy type *and* modifier even though it's optional // for each invocation of (...)+ in rewrite String grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : modifier? type ID (',' ID)* ';' -> ^(type modifier? ID)+ ^(type modifier? ID)+ ;\n" + "type : 'int' ;\n" + "modifier : 'public' ;\n" + "ID : 'a'..'z'+ ;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; String found = execParser("T.g", grammar, "TParser", "TLexer", "a", "public int a,b,c;", debug); assertEquals("(int public a) (int public b) (int public c) (int public a) (int public b) (int public c)\n", found); } @Test public void testCopySemanticsForRules4() throws Exception { // copy type *and* modifier even though it's optional // for each invocation of (...)+ in rewrite String grammar = "grammar T;\n" + "options {output=AST;}\n" + "tokens {MOD;}\n" + "a : modifier? type ID (',' ID)* ';' -> ^(type ^(MOD modifier)? ID)+ ;\n" + "type : 'int' ;\n" + "modifier : 'public' ;\n" + "ID : 'a'..'z'+ ;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; String found = execParser("T.g", grammar, "TParser", "TLexer", "a", "public int a,b,c;", debug); assertEquals("(int (MOD public) a) (int (MOD public) b) (int (MOD public) c)\n", found); } @Test public void testCopySemanticsLists() throws Exception { String grammar = "grammar T;\n" + "options {output=AST;}\n" + "tokens {MOD;}\n" + "a : ID (',' ID)* ';' -> ID+ ID+ ;\n"+ "ID : 'a'..'z'+ ;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; String found = execParser("T.g", grammar, "TParser", "TLexer", "a", "a,b,c;", debug); assertEquals("a b c a b c\n", found); } @Test public void testCopyRuleLabel() throws Exception { String grammar = "grammar T;\n" + "options {output=AST;}\n" + "tokens {BLOCK;}\n" + "a : x=b -> $x $x;\n"+ "b : ID ;\n"+ "ID : 'a'..'z'+ ;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; String found = execParser("T.g", grammar, "TParser", "TLexer", "a", "a", debug); assertEquals("a a\n", found); } @Test public void testCopyRuleLabel2() throws Exception { String grammar = "grammar T;\n" + "options {output=AST;}\n" + "tokens {BLOCK;}\n" + "a : x=b -> ^($x $x);\n"+ "b : ID ;\n"+ "ID : 'a'..'z'+ ;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; String found = execParser("T.g", grammar, "TParser", "TLexer", "a", "a", debug); assertEquals("(a a)\n", found); } @Test public void testQueueingOfTokens() throws Exception { String grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : 'int' ID (',' ID)* ';' -> ^('int' ID+) ;\n" + "op : '+'|'-' ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; String found = execParser("T.g", grammar, "TParser", "TLexer", "a", "int a,b,c;", debug); assertEquals("(int a b c)\n", found); } @Test public void testCopyOfTokens() throws Exception { String grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : 'int' ID ';' -> 'int' ID 'int' ID ;\n" + "op : '+'|'-' ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; String found = execParser("T.g", grammar, "TParser", "TLexer", "a", "int a;", debug); assertEquals("int a int a\n", found); } @Test public void testTokenCopyInLoop() throws Exception { String grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : 'int' ID (',' ID)* ';' -> ^('int' ID)+ ;\n" + "op : '+'|'-' ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; String found = execParser("T.g", grammar, "TParser", "TLexer", "a", "int a,b,c;", debug); assertEquals("(int a) (int b) (int c)\n", found); } @Test public void testTokenCopyInLoopAgainstTwoOthers() throws Exception { // must smear 'int' copies across as root of multiple trees String grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : 'int' ID ':' INT (',' ID ':' INT)* ';' -> ^('int' ID INT)+ ;\n" + "op : '+'|'-' ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; String found = execParser("T.g", grammar, "TParser", "TLexer", "a", "int a:1,b:2,c:3;", debug); assertEquals("(int a 1) (int b 2) (int c 3)\n", found); } @Test public void testListRefdOneAtATime() throws Exception { String grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : ID+ -> ID ID ID ;\n" + // works if 3 input IDs "op : '+'|'-' ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; String found = execParser("T.g", grammar, "TParser", "TLexer", "a", "a b c", debug); assertEquals("a b c\n", found); } @Test public void testSplitListWithLabels() throws Exception { String grammar = "grammar T;\n" + "options {output=AST;}\n" + "tokens {VAR;}\n"+ "a : first=ID others+=ID* -> $first VAR $others+ ;\n" + "op : '+'|'-' ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; String found = execParser("T.g", grammar, "TParser", "TLexer", "a", "a b c", debug); assertEquals("a VAR b c\n", found); } @Test public void testComplicatedMelange() throws Exception { String grammar = "grammar T;\n" + "options {output=AST;}\n" + "tokens {BLOCK;}\n" + "a : A A b=B B b=B c+=C C c+=C D {String s=$D.text;} -> A+ B+ C+ D ;\n" + "type : 'int' | 'float' ;\n" + "A : 'a' ;\n" + "B : 'b' ;\n" + "C : 'c' ;\n" + "D : 'd' ;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; String found = execParser("T.g", grammar, "TParser", "TLexer", "a", "a a b b b c c c d", debug); assertEquals("a a b b b c c c d\n", found); } @Test public void testRuleLabel() throws Exception { String grammar = "grammar T;\n" + "options {output=AST;}\n" + "tokens {BLOCK;}\n" + "a : x=b -> $x;\n"+ "b : ID ;\n"+ "ID : 'a'..'z'+ ;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; String found = execParser("T.g", grammar, "TParser", "TLexer", "a", "a", debug); assertEquals("a\n", found); } @Test public void testAmbiguousRule() throws Exception { String grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : ID a -> a | INT ;\n"+ "ID : 'a'..'z'+ ;\n" + "INT: '0'..'9'+ ;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; String found = execParser("T.g", grammar, "TParser", "TLexer", "a", "abc 34", debug); assertEquals("34\n", found); } @Test public void testWeirdRuleRef() throws Exception { ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); String grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : ID a -> $a | INT ;\n"+ "ID : 'a'..'z'+ ;\n" + "INT: '0'..'9'+ ;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; Grammar g = new Grammar(grammar); Tool antlr = newTool(); antlr.setOutputDirectory(null); // write to /dev/null CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); // $a is ambig; is it previous root or ref to a ref in alt? assertEquals("unexpected errors: "+equeue, 1, equeue.errors.size()); } @Test public void testRuleListLabel() throws Exception { String grammar = "grammar T;\n" + "options {output=AST;}\n" + "tokens {BLOCK;}\n" + "a : x+=b x+=b -> $x+;\n"+ "b : ID ;\n"+ "ID : 'a'..'z'+ ;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; String found = execParser("T.g", grammar, "TParser", "TLexer", "a", "a b", debug); assertEquals("a b\n", found); } @Test public void testRuleListLabel2() throws Exception { String grammar = "grammar T;\n" + "options {output=AST;}\n" + "tokens {BLOCK;}\n" + "a : x+=b x+=b -> $x $x*;\n"+ "b : ID ;\n"+ "ID : 'a'..'z'+ ;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; String found = execParser("T.g", grammar, "TParser", "TLexer", "a", "a b", debug); assertEquals("a b\n", found); } @Test public void testOptional() throws Exception { String grammar = "grammar T;\n" + "options {output=AST;}\n" + "tokens {BLOCK;}\n" + "a : x=b (y=b)? -> $x $y?;\n"+ "b : ID ;\n"+ "ID : 'a'..'z'+ ;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; String found = execParser("T.g", grammar, "TParser", "TLexer", "a", "a", debug); assertEquals("a\n", found); } @Test public void testOptional2() throws Exception { String grammar = "grammar T;\n" + "options {output=AST;}\n" + "tokens {BLOCK;}\n" + "a : x=ID (y=b)? -> $x $y?;\n"+ "b : ID ;\n"+ "ID : 'a'..'z'+ ;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; String found = execParser("T.g", grammar, "TParser", "TLexer", "a", "a b", debug); assertEquals("a b\n", found); } @Test public void testOptional3() throws Exception { String grammar = "grammar T;\n" + "options {output=AST;}\n" + "tokens {BLOCK;}\n" + "a : x=ID (y=b)? -> ($x $y)?;\n"+ "b : ID ;\n"+ "ID : 'a'..'z'+ ;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; String found = execParser("T.g", grammar, "TParser", "TLexer", "a", "a b", debug); assertEquals("a b\n", found); } @Test public void testOptional4() throws Exception { String grammar = "grammar T;\n" + "options {output=AST;}\n" + "tokens {BLOCK;}\n" + "a : x+=ID (y=b)? -> ($x $y)?;\n"+ "b : ID ;\n"+ "ID : 'a'..'z'+ ;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; String found = execParser("T.g", grammar, "TParser", "TLexer", "a", "a b", debug); assertEquals("a b\n", found); } @Test public void testOptional5() throws Exception { String grammar = "grammar T;\n" + "options {output=AST;}\n" + "tokens {BLOCK;}\n" + "a : ID -> ID? ;\n"+ // match an ID to optional ID "b : ID ;\n"+ "ID : 'a'..'z'+ ;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; String found = execParser("T.g", grammar, "TParser", "TLexer", "a", "a", debug); assertEquals("a\n", found); } @Test public void testArbitraryExprType() throws Exception { String grammar = "grammar T;\n" + "options {output=AST;}\n" + "tokens {BLOCK;}\n" + "a : x+=b x+=b -> {new CommonTree()};\n"+ "b : ID ;\n"+ "ID : 'a'..'z'+ ;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; String found = execParser("T.g", grammar, "TParser", "TLexer", "a", "a b", debug); assertEquals("", found); } @Test public void testSet() throws Exception { String grammar = "grammar T;\n" + "options { output = AST; } \n" + "a: (INT|ID)+ -> INT+ ID+ ;\n" + "INT: '0'..'9'+;\n" + "ID : 'a'..'z'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; String found = execParser("T.g", grammar, "TParser", "TLexer", "a", "2 a 34 de", debug); assertEquals("2 34 a de\n", found); } @Test public void testSet2() throws Exception { String grammar = "grammar T;\n" + "options { output = AST; } \n" + "a: (INT|ID) -> INT? ID? ;\n" + "INT: '0'..'9'+;\n" + "ID : 'a'..'z'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; String found = execParser("T.g", grammar, "TParser", "TLexer", "a", "2", debug); assertEquals("2\n", found); } @Ignore // TODO: FAILS. The should probably generate a warning from antlr // See http://www.antlr.org:8888/browse/ANTLR-162 // public void testSetWithLabel() throws Exception { String grammar = "grammar T;\n" + "options { output = AST; } \n" + "a : x=(INT|ID) -> $x ;\n" + "INT: '0'..'9'+;\n" + "ID : 'a'..'z'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; String found = execParser("T.g", grammar, "TParser", "TLexer", "a", "2", debug); assertEquals("2\n", found); } @Test public void testRewriteAction() throws Exception { String grammar = "grammar T; \n" + "options { output = AST; }\n" + "tokens { FLOAT; }\n" + "r\n" + " : INT -> {new CommonTree(new CommonToken(FLOAT,$INT.text+\".0\"))} \n" + " ; \n" + "INT : '0'..'9'+; \n" + "WS: (' ' | '\\n' | '\\t')+ {$channel = HIDDEN;}; \n"; String found = execParser("T.g", grammar, "TParser", "TLexer", "r", "25", debug); assertEquals("25.0\n", found); } @Test public void testOptionalSubruleWithoutRealElements() throws Exception { // copy type *and* modifier even though it's optional // for each invocation of (...)+ in rewrite String grammar = "grammar T;\n" + "options {output=AST;} \n" + "tokens {PARMS;} \n" + "\n" + "modulo \n" + " : 'modulo' ID ('(' parms+ ')')? -> ^('modulo' ID ^(PARMS parms+)?) \n" + " ; \n" + "parms : '#'|ID; \n" + "ID : ('a'..'z' | 'A'..'Z')+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; String found = execParser("T.g", grammar, "TParser", "TLexer", "modulo", "modulo abc (x y #)", debug); assertEquals("(modulo abc (PARMS x y #))\n", found); } // C A R D I N A L I T Y I S S U E S @Test public void testCardinality() throws Exception { String grammar = "grammar T;\n" + "options {output=AST;}\n" + "tokens {BLOCK;}\n" + "a : ID ID INT INT INT -> (ID INT)+;\n"+ "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+; \n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; execParser("T.g", grammar, "TParser", "TLexer", "a", "a b 3 4 5", debug); String expecting = "org.antlr.runtime.tree.RewriteCardinalityException: token ID"; String found = getFirstLineOfException(); assertEquals(expecting, found); } @Test public void testCardinality2() throws Exception { String grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : ID+ -> ID ID ID ;\n" + // only 2 input IDs "op : '+'|'-' ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; execParser("T.g", grammar, "TParser", "TLexer", "a", "a b", debug); String expecting = "org.antlr.runtime.tree.RewriteCardinalityException: token ID"; String found = getFirstLineOfException(); assertEquals(expecting, found); } @Test public void testCardinality3() throws Exception { String grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : ID? INT -> ID INT ;\n" + "op : '+'|'-' ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; execParser("T.g", grammar, "TParser", "TLexer", "a", "3", debug); String expecting = "org.antlr.runtime.tree.RewriteEmptyStreamException: token ID"; String found = getFirstLineOfException(); assertEquals(expecting, found); } @Test public void testLoopCardinality() throws Exception { String grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : ID? INT -> ID+ INT ;\n" + "op : '+'|'-' ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; execParser("T.g", grammar, "TParser", "TLexer", "a", "3", debug); String expecting = "org.antlr.runtime.tree.RewriteEarlyExitException"; String found = getFirstLineOfException(); assertEquals(expecting, found); } @Test public void testWildcard() throws Exception { String grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : ID c=. -> $c;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; String found = execParser("T.g", grammar, "TParser", "TLexer", "a", "abc 34", debug); assertEquals("34\n", found); } // E R R O R S @Test public void testUnknownRule() throws Exception { ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); String grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : INT -> ugh ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; Grammar g = new Grammar(grammar); Tool antlr = newTool(); antlr.setOutputDirectory(null); // write to /dev/null CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); int expectedMsgID = ErrorManager.MSG_UNDEFINED_RULE_REF; Object expectedArg = "ugh"; Object expectedArg2 = null; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage(expectedMsgID, g, null, expectedArg, expectedArg2); checkError(equeue, expectedMessage); } @Test public void testKnownRuleButNotInLHS() throws Exception { ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); String grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : INT -> b ;\n" + "b : 'b' ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; Grammar g = new Grammar(grammar); Tool antlr = newTool(); antlr.setOutputDirectory(null); // write to /dev/null CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); int expectedMsgID = ErrorManager.MSG_REWRITE_ELEMENT_NOT_PRESENT_ON_LHS; Object expectedArg = "b"; Object expectedArg2 = null; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage(expectedMsgID, g, null, expectedArg, expectedArg2); checkError(equeue, expectedMessage); } @Test public void testUnknownToken() throws Exception { ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); String grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : INT -> ICK ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; Grammar g = new Grammar(grammar); Tool antlr = newTool(); antlr.setOutputDirectory(null); // write to /dev/null CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); int expectedMsgID = ErrorManager.MSG_UNDEFINED_TOKEN_REF_IN_REWRITE; Object expectedArg = "ICK"; Object expectedArg2 = null; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage(expectedMsgID, g, null, expectedArg, expectedArg2); checkError(equeue, expectedMessage); } @Test public void testUnknownLabel() throws Exception { ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); String grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : INT -> $foo ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; Grammar g = new Grammar(grammar); Tool antlr = newTool(); antlr.setOutputDirectory(null); // write to /dev/null CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); int expectedMsgID = ErrorManager.MSG_UNDEFINED_LABEL_REF_IN_REWRITE; Object expectedArg = "foo"; Object expectedArg2 = null; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage(expectedMsgID, g, null, expectedArg, expectedArg2); checkError(equeue, expectedMessage); } @Test public void testUnknownCharLiteralToken() throws Exception { ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); String grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : INT -> 'a' ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; Grammar g = new Grammar(grammar); Tool antlr = newTool(); antlr.setOutputDirectory(null); // write to /dev/null CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); int expectedMsgID = ErrorManager.MSG_UNDEFINED_TOKEN_REF_IN_REWRITE; Object expectedArg = "'a'"; Object expectedArg2 = null; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage(expectedMsgID, g, null, expectedArg, expectedArg2); checkError(equeue, expectedMessage); } @Test public void testUnknownStringLiteralToken() throws Exception { ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); String grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : INT -> 'foo' ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; Grammar g = new Grammar(grammar); Tool antlr = newTool(); antlr.setOutputDirectory(null); // write to /dev/null CodeGenerator generator = new CodeGenerator(antlr, g, "Java"); g.setCodeGenerator(generator); generator.genRecognizer(); int expectedMsgID = ErrorManager.MSG_UNDEFINED_TOKEN_REF_IN_REWRITE; Object expectedArg = "'foo'"; Object expectedArg2 = null; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage(expectedMsgID, g, null, expectedArg, expectedArg2); checkError(equeue, expectedMessage); } @Test public void testExtraTokenInSimpleDecl() throws Exception { String grammar = "grammar foo;\n" + "options {output=AST;}\n" + "tokens {EXPR;}\n" + "decl : type ID '=' INT ';' -> ^(EXPR type ID INT) ;\n" + "type : 'int' | 'float' ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; String found = execParser("foo.g", grammar, "fooParser", "fooLexer", "decl", "int 34 x=1;", debug); assertEquals("line 1:4 extraneous input '34' expecting ID\n", this.stderrDuringParse); assertEquals("(EXPR int x 1)\n", found); // tree gets correct x and 1 tokens } @Test public void testMissingIDInSimpleDecl() throws Exception { String grammar = "grammar foo;\n" + "options {output=AST;}\n" + "tokens {EXPR;}\n" + "decl : type ID '=' INT ';' -> ^(EXPR type ID INT) ;\n" + "type : 'int' | 'float' ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; String found = execParser("foo.g", grammar, "fooParser", "fooLexer", "decl", "int =1;", debug); assertEquals("line 1:4 missing ID at '='\n", this.stderrDuringParse); assertEquals("(EXPR int <missing ID> 1)\n", found); // tree gets invented ID token } @Test public void testMissingSetInSimpleDecl() throws Exception { String grammar = "grammar foo;\n" + "options {output=AST;}\n" + "tokens {EXPR;}\n" + "decl : type ID '=' INT ';' -> ^(EXPR type ID INT) ;\n" + "type : 'int' | 'float' ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; String found = execParser("foo.g", grammar, "fooParser", "fooLexer", "decl", "x=1;", debug); assertEquals("line 1:0 mismatched input 'x' expecting set null\n", this.stderrDuringParse); assertEquals("(EXPR <error: x> x 1)\n", found); // tree gets invented ID token } @Test public void testMissingTokenGivesErrorNode() throws Exception { String grammar = "grammar foo;\n" + "options {output=AST;}\n" + "a : ID INT -> ID INT ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; String found = execParser("foo.g", grammar, "fooParser", "fooLexer", "a", "abc", debug); assertEquals("line 1:3 missing INT at '<EOF>'\n", this.stderrDuringParse); // doesn't do in-line recovery for sets (yet?) assertEquals("abc <missing INT>\n", found); } @Test public void testExtraTokenGivesErrorNode() throws Exception { String grammar = "grammar foo;\n" + "options {output=AST;}\n" + "a : b c -> b c;\n" + "b : ID -> ID ;\n" + "c : INT -> INT ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; String found = execParser("foo.g", grammar, "fooParser", "fooLexer", "a", "abc ick 34", debug); assertEquals("line 1:4 extraneous input 'ick' expecting INT\n", this.stderrDuringParse); assertEquals("abc 34\n", found); } @Test public void testMissingFirstTokenGivesErrorNode() throws Exception { String grammar = "grammar foo;\n" + "options {output=AST;}\n" + "a : ID INT -> ID INT ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; String found = execParser("foo.g", grammar, "fooParser", "fooLexer", "a", "34", debug); assertEquals("line 1:0 missing ID at '34'\n", this.stderrDuringParse); assertEquals("<missing ID> 34\n", found); } @Test public void testMissingFirstTokenGivesErrorNode2() throws Exception { String grammar = "grammar foo;\n" + "options {output=AST;}\n" + "a : b c -> b c;\n" + "b : ID -> ID ;\n" + "c : INT -> INT ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; String found = execParser("foo.g", grammar, "fooParser", "fooLexer", "a", "34", debug); // finds an error at the first token, 34, and re-syncs. // re-synchronizing does not consume a token because 34 follows // ref to rule b (start of c). It then matches 34 in c. assertEquals("line 1:0 missing ID at '34'\n", this.stderrDuringParse); assertEquals("<missing ID> 34\n", found); } @Test public void testNoViableAltGivesErrorNode() throws Exception { String grammar = "grammar foo;\n" + "options {output=AST;}\n" + "a : b -> b | c -> c;\n" + "b : ID -> ID ;\n" + "c : INT -> INT ;\n" + "ID : 'a'..'z'+ ;\n" + "S : '*' ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; String found = execParser("foo.g", grammar, "fooParser", "fooLexer", "a", "*", debug); // finds an error at the first token, 34, and re-syncs. // re-synchronizing does not consume a token because 34 follows // ref to rule b (start of c). It then matches 34 in c. assertEquals("line 1:0 no viable alternative at input '*'\n", this.stderrDuringParse); assertEquals("<unexpected: [@0,0:0='*',<6>,1:0], resync=*>\n", found); } }
gpl-2.0
wraiden/spacewalk
java/code/src/com/redhat/rhn/frontend/action/groups/SSMGroupManageAction.java
3899
/** * Copyright (c) 2015 Red Hat, Inc. * * This software is licensed to you under the GNU General Public License, * version 2 (GPLv2). There is NO WARRANTY for this software, express or * implied, including the implied warranties of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2 * along with this software; if not, see * http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt. * * Red Hat trademarks are not licensed under GPLv2. No permission is * granted to use or replicate Red Hat trademarks that are incorporated * in this software or its documentation. */ package com.redhat.rhn.frontend.action.groups; import com.redhat.rhn.domain.rhnset.RhnSet; import com.redhat.rhn.domain.user.User; import com.redhat.rhn.frontend.dto.SystemGroupOverview; import com.redhat.rhn.frontend.struts.RequestContext; import com.redhat.rhn.frontend.struts.RhnAction; import com.redhat.rhn.frontend.struts.RhnHelper; import com.redhat.rhn.frontend.taglibs.list.ListTagHelper; import com.redhat.rhn.manager.rhnset.RhnSetDecl; import com.redhat.rhn.manager.rhnset.RhnSetManager; import com.redhat.rhn.manager.system.SystemManager; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.DynaActionForm; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * SSMGroupManageAction * @version $Rev$ */ public class SSMGroupManageAction extends RhnAction { public static final Long ADD = 1L; public static final Long REMOVE = 0L; /** * {@inheritDoc} */ @Override public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { RequestContext rctx = new RequestContext(request); User user = rctx.getCurrentUser(); DynaActionForm daForm = (DynaActionForm)form; request.setAttribute(ListTagHelper.PARENT_URL, request.getRequestURI()); List<SystemGroupOverview> groups = SystemManager.groupList(user, null); // If submitted, save the user's choices for the confirm page if (isSubmitted(daForm)) { processList(user, request); return mapping.findForward("confirm"); } request.setAttribute(RequestContext.PAGE_LIST, groups); return mapping.findForward(RhnHelper.DEFAULT_FORWARD); } private int processList(User user, HttpServletRequest request) { List<Long> addList = new ArrayList<Long>(); List<Long> removeList = new ArrayList<Long>(); Enumeration<String> names = request.getParameterNames(); while (names.hasMoreElements()) { String aName = names.nextElement(); String aValue = request.getParameter(aName); Long aId = null; try { aId = Long.parseLong(aName); } catch (NumberFormatException e) { // not a param we care about; skip continue; } if ("add".equals(aValue)) { addList.add(aId); } else if ("remove".equals(aValue)) { removeList.add(aId); } } if (addList.size() + removeList.size() > 0) { RhnSet cset = RhnSetDecl.SSM_GROUP_LIST.get(user); cset.clear(); for (Long id : addList) { cset.addElement(id, ADD); } for (Long id : removeList) { cset.addElement(id, REMOVE); } RhnSetManager.store(cset); } return addList.size() + removeList.size(); } }
gpl-2.0
FauxFaux/jdk9-langtools
test/jdk/javadoc/doclet/testTitleInHref/TestTitleInHref.java
2431
/* * Copyright (c) 2002, 2016, 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 4714257 * @summary Test to make sure that the title attribute shows up in links. * @author jamieh * @library ../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool * @build JavadocTester * @run main TestTitleInHref */ public class TestTitleInHref extends JavadocTester { public static void main(String... args) throws Exception { TestTitleInHref tester = new TestTitleInHref(); tester.runTests(); } @Test void test() { String uri = "http://java.sun.com/j2se/1.4/docs/api"; javadoc("-d", "out", "-sourcepath", testSrc, "-linkoffline", uri, testSrc, "pkg"); checkExit(Exit.OK); checkOutput("pkg/Links.html", true, //Test to make sure that the title shows up in a class link. "<a href=\"../pkg/Class.html\" title=\"class in pkg\">", //Test to make sure that the title shows up in an interface link. "<a href=\"../pkg/Interface.html\" title=\"interface in pkg\">", //Test to make sure that the title shows up in cross link shows up "<a href=\"" + uri + "/java/io/File.html?is-external=true\" " + "title=\"class or interface in java.io\">" + "<code>This is a cross link to class File</code></a>"); } }
gpl-2.0
abbeyj/sonarqube
server/sonar-server/src/test/java/org/sonar/server/computation/formula/counter/DoubleVariationValueTest.java
3045
/* * SonarQube, open source software quality management tool. * Copyright (C) 2008-2014 SonarSource * mailto:contact AT sonarsource DOT com * * SonarQube is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * SonarQube is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.computation.formula.counter; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class DoubleVariationValueTest { @Test public void newly_created_DoubleVariationValue_is_unset_and_has_value_0() { verifyUnsetVariationValue(new DoubleVariationValue()); } @Test public void increment_double_sets_DoubleVariationValue_and_increments_value() { verifySetVariationValue(new DoubleVariationValue().increment(10.6), 10.6); } @Test public void increment_DoubleVariationValue_has_no_effect_if_arg_is_null() { verifyUnsetVariationValue(new DoubleVariationValue().increment(null)); } @Test public void increment_DoubleVariationValue_has_no_effect_if_arg_is_unset() { verifyUnsetVariationValue(new DoubleVariationValue().increment(new DoubleVariationValue())); } @Test public void increment_DoubleVariationValue_increments_by_the_value_of_the_arg() { DoubleVariationValue source = new DoubleVariationValue().increment(10); DoubleVariationValue target = new DoubleVariationValue().increment(source); verifySetVariationValue(target, 10); } @Test public void multiple_calls_to_increment_DoubleVariationValue_increments_by_the_value_of_the_arg() { DoubleVariationValue target = new DoubleVariationValue() .increment(new DoubleVariationValue().increment(35)) .increment(new DoubleVariationValue().increment(10)); verifySetVariationValue(target, 45); } @Test public void multiples_calls_to_increment_double_increment_the_value() { DoubleVariationValue variationValue = new DoubleVariationValue() .increment(10.6) .increment(95.4); verifySetVariationValue(variationValue, 106); } private static void verifyUnsetVariationValue(DoubleVariationValue variationValue) { assertThat(variationValue.isSet()).isFalse(); assertThat(variationValue.getValue()).isEqualTo(0); } private static void verifySetVariationValue(DoubleVariationValue variationValue, double expected) { assertThat(variationValue.isSet()).isTrue(); assertThat(variationValue.getValue()).isEqualTo(expected); } }
lgpl-3.0
andre-nunes/fenixedu-academic
src/main/java/org/fenixedu/academic/domain/phd/thesis/activities/RequestJuryReviews.java
8104
/** * Copyright © 2002 Instituto Superior Técnico * * This file is part of FenixEdu Academic. * * FenixEdu Academic is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * FenixEdu Academic 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 FenixEdu Academic. If not, see <http://www.gnu.org/licenses/>. */ /** * */ package org.fenixedu.academic.domain.phd.thesis.activities; import org.fenixedu.academic.domain.caseHandling.PreConditionNotValidException; import org.fenixedu.academic.domain.caseHandling.Process; import org.fenixedu.academic.domain.phd.PhdIndividualProgramProcess; import org.fenixedu.academic.domain.phd.PhdParticipant; import org.fenixedu.academic.domain.phd.access.PhdProcessAccessType; import org.fenixedu.academic.domain.phd.alert.AlertService; import org.fenixedu.academic.domain.phd.alert.AlertService.AlertMessage; import org.fenixedu.academic.domain.phd.alert.PhdReporterReviewAlert; import org.fenixedu.academic.domain.phd.thesis.PhdThesisProcess; import org.fenixedu.academic.domain.phd.thesis.PhdThesisProcessBean; import org.fenixedu.academic.domain.phd.thesis.PhdThesisProcessStateType; import org.fenixedu.academic.domain.phd.thesis.ThesisJuryElement; import org.fenixedu.academic.domain.phd.thesis.meeting.PhdMeetingSchedulingProcess; import org.fenixedu.bennu.core.domain.User; import org.joda.time.Days; import org.joda.time.LocalDate; public class RequestJuryReviews extends PhdThesisActivity { @Override protected void activityPreConditions(PhdThesisProcess process, User userView) { if (!process.isJuryValidated()) { throw new PreConditionNotValidException(); } if (process.hasState(PhdThesisProcessStateType.WAITING_FOR_JURY_REPORTER_FEEDBACK)) { throw new PreConditionNotValidException(); } if (!process.isAllowedToManageProcess(userView)) { throw new PreConditionNotValidException(); } } @Override protected PhdThesisProcess executeActivity(PhdThesisProcess process, User userView, Object object) { final PhdThesisProcessBean bean = (PhdThesisProcessBean) object; if (bean.isToNotify()) { notifyJuryElements(process); sendAlertToJuryElement(process.getIndividualProgramProcess(), process.getPresidentJuryElement(), "message.phd.request.jury.reviews.external.access.jury.president.body"); } if (process.getActiveState() != PhdThesisProcessStateType.WAITING_FOR_JURY_REPORTER_FEEDBACK) { process.createState(PhdThesisProcessStateType.WAITING_FOR_JURY_REPORTER_FEEDBACK, userView.getPerson(), ""); } bean.setThesisProcess(process); if (process.getMeetingProcess() == null) { Process.createNewProcess(userView, PhdMeetingSchedulingProcess.class, bean); } return process; } private void notifyJuryElements(PhdThesisProcess process) { for (final ThesisJuryElement juryElement : process.getThesisJuryElementsSet()) { if (juryElement.isDocumentValidated()) { continue; } if (!juryElement.isInternal()) { createExternalAccess(juryElement); } if (juryElement.getReporter().booleanValue()) { sendInitialAlertToReporter(process.getIndividualProgramProcess(), juryElement); } else { sendAlertToJuryElement(process.getIndividualProgramProcess(), juryElement, "message.phd.request.jury.reviews.external.access.jury.body"); } } for (final ThesisJuryElement juryElement : process.getThesisJuryElementsSet()) { final PhdParticipant participant = juryElement.getParticipant(); if (!juryElement.getReporter().booleanValue()) { continue; } new PhdReporterReviewAlert(process.getIndividualProgramProcess(), participant); } } private void sendInitialAlertToReporter(PhdIndividualProgramProcess process, ThesisJuryElement thesisJuryElement) { PhdParticipant participant = thesisJuryElement.getParticipant(); if (!participant.isInternal()) { participant.ensureExternalAccess(); } final AlertMessage subject = AlertMessage .create(AlertMessage.get("message.phd.request.jury.reviews.external.access.subject", process .getPhdProgram().getName())).isKey(false).withPrefix(false); final AlertMessage body = AlertMessage .create(AlertMessage.get("message.phd.request.jury.reviews.external.access.jury.body", process .getPerson().getName(), process.getProcessNumber()) + "\n\n" + AlertMessage.get("message.phd.request.jury.reviews.reporter.body", getDaysLeftForReview(process.getThesisProcess())) + "\n\n" + getAccessInformation(process, participant, "message.phd.request.jury.reviews.coordinator.access", "message.phd.request.jury.reviews.teacher.access")).isKey(false).withPrefix(false); AlertService.alertParticipants(process, subject, body, participant); } private void sendAlertToJuryElement(PhdIndividualProgramProcess process, ThesisJuryElement thesisJuryElement, String bodyMessage) { PhdParticipant participant = thesisJuryElement.getParticipant(); if (!participant.isInternal()) { createExternalAccess(thesisJuryElement); participant.ensureExternalAccess(); } final AlertMessage subject = AlertMessage .create(AlertMessage.get("message.phd.request.jury.reviews.external.access.subject", process .getPhdProgram().getName())).isKey(false).withPrefix(false); final AlertMessage body = AlertMessage .create(AlertMessage.get(bodyMessage, process.getPerson().getName(), process.getProcessNumber()) + "\n\n" + getAccessInformation(process, participant, "message.phd.request.jury.reviews.coordinator.access", "message.phd.request.jury.reviews.teacher.access") + "\n\n" + AlertMessage.get("message.phd.request.jury.external.access.reviews.body", getDaysLeftForReview(process.getThesisProcess()))).isKey(false).withPrefix(false); AlertService.alertParticipants(process, subject, body, participant); } private void createExternalAccess(final ThesisJuryElement juryElement) { final PhdParticipant participant = juryElement.getParticipant(); participant.addAccessType(PhdProcessAccessType.JURY_DOCUMENTS_DOWNLOAD); if (juryElement.getReporter().booleanValue()) { participant.addAccessType(PhdProcessAccessType.JURY_REPORTER_FEEDBACK_UPLOAD); } } private int getDaysLeftForReview(PhdThesisProcess process) { return Days.daysBetween(process.getWhenJuryValidated().plusDays(PhdReporterReviewAlert.getReporterReviewDeadlineDays()), new LocalDate()).getDays(); } }
lgpl-3.0
apache/drill
exec/vector/src/main/java/org/apache/drill/exec/vector/accessor/writer/SimpleListShim.java
5780
/* * 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.drill.exec.vector.accessor.writer; import org.apache.drill.common.types.TypeProtos.MinorType; import org.apache.drill.exec.record.metadata.ColumnMetadata; import org.apache.drill.exec.vector.accessor.ColumnWriterIndex; import org.apache.drill.exec.vector.accessor.ObjectWriter; import org.apache.drill.exec.vector.accessor.impl.HierarchicalFormatter; import org.apache.drill.exec.vector.accessor.writer.UnionWriterImpl.UnionShim; import org.apache.drill.shaded.guava.com.google.common.base.Preconditions; /** * Shim for a list that holds a single type, but may eventually become a * list of variants. (A list that is declared to hold a single type * is implemented using the {@link ListWriterImpl} class that * directly holds that single type.) This shim is needed when we want * to present a uniform variant interface for a list that holds zero * one (this case) or many types. */ public class SimpleListShim implements UnionShim { private UnionWriterImpl writer; private AbstractObjectWriter colWriter; public SimpleListShim() { } public SimpleListShim(AbstractObjectWriter writer) { this.colWriter = writer; } @Override public void bindWriter(UnionWriterImpl writer) { this.writer = writer; } @Override public void bindIndex(ColumnWriterIndex index) { events().bindIndex(index); } @Override public void bindListener(ColumnWriterListener listener) { colWriter.events().bindListener(listener); } @Override public boolean hasType(MinorType type) { return type == colWriter.schema().type(); } @Override public void setType(MinorType type) { if (! hasType(type)) { // Not this type. Ask the listener to promote this writer // to a union, then ask the writer to set the type on // the resulting new shim. addMember(type); writer.setType(type); } } @Override public ObjectWriter member(MinorType type) { if (hasType(type)) { return colWriter; } return addMember(type); } public AbstractObjectWriter memberWriter() { return colWriter; } @Override public AbstractObjectWriter addMember(ColumnMetadata colSchema) { return doAddMember((AbstractObjectWriter) writer.listener().addMember(colSchema)); } @Override public AbstractObjectWriter addMember(MinorType type) { return doAddMember((AbstractObjectWriter) writer.listener().addType(type)); } /** * This is a bit of magic. The listener will create the writer (and vector) for * the requested type. It will also replace the shim in the writer with something * that handles a union, so that, when the listener returns, * this shim is no longer bound to the writer. Our dying act is to ask the * new shim to add the new writer as a member. The listener must have moved our * existing reader to the new union shim; but we must add the new writer. * * @param colWriter the column writer returned from the listener * @return the same column writer */ private AbstractObjectWriter doAddMember(AbstractObjectWriter colWriter) { // Something went terribly wrong if the check below fails. Preconditions.checkState(writer.shim() != this); writer.shim().addMember(colWriter); return colWriter; } @Override public void addMember(AbstractObjectWriter colWriter) { // Should only be called when promoting from a no-type shim to this // single type shim. Otherwise, something is wrong with the type // promotion logic. Preconditions.checkState(this.colWriter == null); this.colWriter = colWriter; writer.addMember(colWriter); } @Override public void setNull() { colWriter.setNull(); } private WriterEvents events() { return colWriter.events(); } @Override public void startWrite() { // startWrite called before the column is added. if (colWriter != null) { colWriter.events().startWrite(); } } @Override public void startRow() { // startRow called before the column is added. if (colWriter != null) { colWriter.events().startRow(); } } @Override public void endArrayValue() { events().endArrayValue(); } @Override public void restartRow() { events().restartRow(); } @Override public void saveRow() { events().saveRow(); } @Override public void endWrite() { events().endWrite(); } @Override public void preRollover() { events().preRollover(); } @Override public void postRollover() { events().postRollover(); } @Override public int lastWriteIndex() { return events().lastWriteIndex(); } @Override public int rowStartIndex() { return events().rowStartIndex(); } @Override public int writeIndex() { return events().writeIndex(); } @Override public void dump(HierarchicalFormatter format) { format.startObject(this).attribute("colWriter"); colWriter.dump(format); format.endObject(); } }
apache-2.0
gitblit/gitblit
src/main/java/com/gitblit/wicket/pages/ProjectsPage.java
4357
/* * Copyright 2012 gitblit.com. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.gitblit.wicket.pages; import java.util.Collections; import java.util.List; import org.apache.wicket.PageParameters; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.repeater.Item; import org.apache.wicket.markup.repeater.data.DataView; import org.apache.wicket.markup.repeater.data.ListDataProvider; import com.gitblit.Keys; import com.gitblit.models.Menu.ParameterMenuItem; import com.gitblit.models.NavLink.DropDownPageMenuNavLink; import com.gitblit.models.NavLink; import com.gitblit.models.ProjectModel; import com.gitblit.wicket.GitBlitWebSession; import com.gitblit.wicket.WicketUtils; import com.gitblit.wicket.panels.LinkPanel; public class ProjectsPage extends RootPage { public ProjectsPage() { super(); setup(null); } public ProjectsPage(PageParameters params) { super(params); setup(params); } @Override protected boolean reusePageParameters() { return true; } @Override protected Class<? extends BasePage> getRootNavPageClass() { return RepositoriesPage.class; } @Override protected List<ProjectModel> getProjectModels() { return app().projects().getProjectModels(getRepositoryModels(), false); } private void setup(PageParameters params) { setupPage("", ""); // check to see if we should display a login message boolean authenticateView = app().settings().getBoolean(Keys.web.authenticateViewPages, true); if (authenticateView && !GitBlitWebSession.get().isLoggedIn()) { add(new Label("projectsPanel")); return; } List<ProjectModel> projects = getProjects(params); Collections.sort(projects); ListDataProvider<ProjectModel> dp = new ListDataProvider<ProjectModel>(projects); DataView<ProjectModel> dataView = new DataView<ProjectModel>("project", dp) { private static final long serialVersionUID = 1L; int counter; @Override protected void onBeforeRender() { super.onBeforeRender(); counter = 0; } @Override public void populateItem(final Item<ProjectModel> item) { final ProjectModel entry = item.getModelObject(); PageParameters pp = WicketUtils.newProjectParameter(entry.name); item.add(new LinkPanel("projectTitle", "list", entry.getDisplayName(), ProjectPage.class, pp)); item.add(new LinkPanel("projectDescription", "list", entry.description, ProjectPage.class, pp)); item.add(new Label("repositoryCount", entry.repositories.size() + " " + (entry.repositories.size() == 1 ? getString("gb.repository") : getString("gb.repositories")))); String lastChange; if (entry.lastChange.getTime() == 0) { lastChange = "--"; } else { lastChange = getTimeUtils().timeAgo(entry.lastChange); } Label lastChangeLabel = new Label("projectLastChange", lastChange); item.add(lastChangeLabel); WicketUtils.setCssClass(lastChangeLabel, getTimeUtils() .timeAgoCss(entry.lastChange)); WicketUtils.setAlternatingBackground(item, counter); counter++; } }; add(dataView); } @Override protected void addDropDownMenus(List<NavLink> navLinks) { PageParameters params = getPageParameters(); DropDownPageMenuNavLink menu = new DropDownPageMenuNavLink("gb.filters", ProjectsPage.class); // preserve time filter option on repository choices menu.menuItems.addAll(getRepositoryFilterItems(params)); // preserve repository filter option on time choices menu.menuItems.addAll(getTimeFilterItems(params)); if (menu.menuItems.size() > 0) { // Reset Filter menu.menuItems.add(new ParameterMenuItem(getString("gb.reset"))); } navLinks.add(menu); } }
apache-2.0
yshakhau/pentaho-kettle
plugins/kettle-xml-plugin/test-src/org/pentaho/di/job/entries/xsdvalidator/JobEntryXSDValidatorTest.java
1760
/*! ****************************************************************************** * * Pentaho Data Integration * * Copyright (C) 2002-2015 by Pentaho : http://www.pentaho.com * ******************************************************************************* * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ******************************************************************************/ package org.pentaho.di.job.entries.xsdvalidator; import static java.util.Arrays.asList; import java.util.List; import java.util.Map; import org.pentaho.di.job.entry.loadSave.JobEntryLoadSaveTestSupport; public class JobEntryXSDValidatorTest extends JobEntryLoadSaveTestSupport<JobEntryXSDValidator> { @Override protected Class<JobEntryXSDValidator> getJobEntryClass() { return JobEntryXSDValidator.class; } @Override protected List<String> listCommonAttributes() { return asList( "xmlfilename", "xsdfilename" ); } @Override protected Map<String, String> createGettersMap() { return toMap( "xmlfilename", "getxmlFilename", "xsdfilename", "getxsdFilename" ); } @Override protected Map<String, String> createSettersMap() { return toMap( "xmlfilename", "setxmlFilename", "xsdfilename", "setxsdFilename" ); } }
apache-2.0
jinhyukchang/gobblin
gobblin-metastore/src/main/java/org/apache/gobblin/metastore/database/DatabaseJobHistoryStoreV100.java
40040
/* * 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.gobblin.metastore.database; import java.io.IOException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Timestamp; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.AbstractMap; import java.util.Arrays; import java.util.Calendar; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TimeZone; import javax.sql.DataSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Optional; import com.google.common.base.Preconditions; import com.google.common.base.Strings; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.linkedin.data.template.StringMap; import org.apache.gobblin.metastore.DatabaseJobHistoryStore; import org.apache.gobblin.metastore.JobHistoryStore; import org.apache.gobblin.rest.JobExecutionInfo; import org.apache.gobblin.rest.JobExecutionQuery; import org.apache.gobblin.rest.JobStateEnum; import org.apache.gobblin.rest.LauncherTypeEnum; import org.apache.gobblin.rest.Metric; import org.apache.gobblin.rest.MetricArray; import org.apache.gobblin.rest.MetricTypeEnum; import org.apache.gobblin.rest.QueryListType; import org.apache.gobblin.rest.Table; import org.apache.gobblin.rest.TableTypeEnum; import org.apache.gobblin.rest.TaskExecutionInfo; import org.apache.gobblin.rest.TaskExecutionInfoArray; import org.apache.gobblin.rest.TaskStateEnum; import org.apache.gobblin.rest.TimeRange; /** * An implementation of {@link JobHistoryStore} backed by MySQL. * * <p> * The DDLs for the MySQL job history store can be found under metastore/src/main/resources. * </p> * * @author Yinan Li */ @SupportedDatabaseVersion(isDefault = true, version = "1.0.0") public class DatabaseJobHistoryStoreV100 implements VersionedDatabaseJobHistoryStore { private static final Logger LOGGER = LoggerFactory.getLogger(DatabaseJobHistoryStore.class); private static final String JOB_EXECUTION_INSERT_STATEMENT_TEMPLATE = "INSERT INTO gobblin_job_executions (job_name,job_id,start_time,end_time,duration,state," + "launched_tasks,completed_tasks,launcher_type,tracking_url) VALUES(?,?,?,?,?,?,?,?,?,?)"; private static final String TASK_EXECUTION_INSERT_STATEMENT_TEMPLATE = "INSERT INTO gobblin_task_executions (task_id,job_id,start_time,end_time,duration," + "state,failure_exception,low_watermark,high_watermark,table_namespace,table_name,table_type) " + "VALUES(?,?,?,?,?,?,?,?,?,?,?,?)"; private static final String JOB_METRIC_INSERT_STATEMENT_TEMPLATE = "INSERT INTO gobblin_job_metrics (job_id,metric_group,metric_name," + "metric_type,metric_value) VALUES(?,?,?,?,?)"; private static final String TASK_METRIC_INSERT_STATEMENT_TEMPLATE = "INSERT INTO gobblin_task_metrics (task_id,metric_group,metric_name," + "metric_type,metric_value) VALUES(?,?,?,?,?)"; private static final String JOB_PROPERTY_INSERT_STATEMENT_TEMPLATE = "INSERT INTO gobblin_job_properties (job_id,property_key,property_value) VALUES(?,?,?)"; private static final String TASK_PROPERTY_INSERT_STATEMENT_TEMPLATE = "INSERT INTO gobblin_task_properties (task_id,property_key,property_value) VALUES(?,?,?)"; private static final String JOB_EXECUTION_UPDATE_STATEMENT_TEMPLATE = "UPDATE gobblin_job_executions SET start_time=?,end_time=?,duration=?," + "state=?,launched_tasks=?,completed_tasks=?,launcher_type=?,tracking_url=? WHERE job_id=?"; private static final String TASK_EXECUTION_UPDATE_STATEMENT_TEMPLATE = "UPDATE gobblin_task_executions SET start_time=?,end_time=?,duration=?,state=?,failure_exception=?," + "low_watermark=?,high_watermark=?,table_namespace=?,table_name=?,table_type=? WHERE task_id=?"; private static final String JOB_METRIC_UPDATE_STATEMENT_TEMPLATE = "UPDATE gobblin_job_metrics SET metric_value=? WHERE job_id=? AND " + "metric_group=? AND metric_name=? AND metric_type=?"; private static final String TASK_METRIC_UPDATE_STATEMENT_TEMPLATE = "UPDATE gobblin_task_metrics SET metric_value=? WHERE task_id=? AND " + "metric_group=? AND metric_name=? AND metric_type=?"; private static final String JOB_PROPERTY_UPDATE_STATEMENT_TEMPLATE = "UPDATE gobblin_job_properties SET property_value=? WHERE job_id=? AND property_key=?"; private static final String TASK_PROPERTY_UPDATE_STATEMENT_TEMPLATE = "UPDATE gobblin_task_properties SET property_value=? WHERE task_id=? AND property_key=?"; private static final String LIST_DISTINCT_JOB_EXECUTION_QUERY_TEMPLATE = "SELECT j.job_id FROM gobblin_job_executions j, " + "(SELECT MAX(last_modified_ts) AS most_recent_ts, job_name " + "FROM gobblin_job_executions GROUP BY job_name) max_results " + "WHERE j.job_name = max_results.job_name AND j.last_modified_ts = max_results.most_recent_ts"; private static final String LIST_RECENT_JOB_EXECUTION_QUERY_TEMPLATE = "SELECT job_id FROM gobblin_job_executions"; private static final String JOB_NAME_QUERY_BY_TABLE_STATEMENT_TEMPLATE = "SELECT j.job_name FROM gobblin_job_executions j, gobblin_task_executions t " + "WHERE j.job_id=t.job_id AND %s GROUP BY j.job_name"; private static final String JOB_ID_QUERY_BY_JOB_NAME_STATEMENT_TEMPLATE = "SELECT job_id FROM gobblin_job_executions WHERE job_name=?"; private static final String JOB_EXECUTION_QUERY_BY_JOB_ID_STATEMENT_TEMPLATE = "SELECT * FROM gobblin_job_executions WHERE job_id=?"; private static final String TASK_EXECUTION_EXIST_QUERY_STATEMENT_TEMPLATE = "SELECT * FROM gobblin_task_executions WHERE task_id=?"; private static final String TASK_EXECUTION_QUERY_STATEMENT_TEMPLATE = "SELECT * FROM gobblin_task_executions WHERE job_id=?"; private static final String JOB_METRIC_EXIST_QUERY_STATEMENT_TEMPLATE = "SELECT * FROM gobblin_job_metrics " + "WHERE job_id=? AND metric_group=? AND metric_name=? AND metric_type=?"; private static final String TASK_METRIC_EXIST_QUERY_STATEMENT_TEMPLATE = "SELECT * FROM gobblin_task_metrics " + "WHERE task_id=? AND metric_group=? AND metric_name=? AND metric_type=?"; private static final String JOB_METRIC_QUERY_STATEMENT_TEMPLATE = "SELECT metric_group,metric_name,metric_type,metric_value FROM gobblin_job_metrics WHERE job_id=?"; private static final String TASK_METRIC_QUERY_STATEMENT_TEMPLATE = "SELECT metric_group,metric_name,metric_type,metric_value FROM gobblin_task_metrics WHERE task_id=?"; private static final String JOB_PROPERTY_EXIST_QUERY_STATEMENT_TEMPLATE = "SELECT * FROM gobblin_job_properties WHERE job_id=? AND property_key=?"; private static final String TASK_PROPERTY_EXIST_QUERY_STATEMENT_TEMPLATE = "SELECT * FROM gobblin_task_properties WHERE task_id=? AND property_key=?"; private static final String JOB_PROPERTY_QUERY_STATEMENT_TEMPLATE = "SELECT property_key, property_value FROM gobblin_job_properties WHERE job_id=?"; private static final String TASK_PROPERTY_QUERY_STATEMENT_TEMPLATE = "SELECT property_key, property_value FROM gobblin_task_properties WHERE task_id=?"; private static final Timestamp DEFAULT_TIMESTAMP = new Timestamp(1000L); private DataSource dataSource; @Override public void init(DataSource dataSource) { this.dataSource = dataSource; } @Override public synchronized void put(JobExecutionInfo jobExecutionInfo) throws IOException { Optional<Connection> connectionOptional = Optional.absent(); try { connectionOptional = Optional.of(getConnection()); Connection connection = connectionOptional.get(); connection.setAutoCommit(false); // Insert or update job execution information if (existsJobExecutionInfo(connection, jobExecutionInfo)) { updateJobExecutionInfo(connection, jobExecutionInfo); } else { insertJobExecutionInfo(connection, jobExecutionInfo); } // Insert or update job metrics if (jobExecutionInfo.hasMetrics()) { for (Metric metric : jobExecutionInfo.getMetrics()) { boolean insert = !existsMetric(connection, JOB_METRIC_EXIST_QUERY_STATEMENT_TEMPLATE, jobExecutionInfo.getJobId(), metric); updateMetric(connection, insert ? JOB_METRIC_INSERT_STATEMENT_TEMPLATE : JOB_METRIC_UPDATE_STATEMENT_TEMPLATE, jobExecutionInfo.getJobId(), metric, insert); } } // Insert or update job properties if (jobExecutionInfo.hasJobProperties()) { for (Map.Entry<String, String> entry : jobExecutionInfo.getJobProperties().entrySet()) { boolean insert = !existsProperty(connection, JOB_PROPERTY_EXIST_QUERY_STATEMENT_TEMPLATE, jobExecutionInfo.getJobId(), entry.getKey()); updateProperty(connection, insert ? JOB_PROPERTY_INSERT_STATEMENT_TEMPLATE : JOB_PROPERTY_UPDATE_STATEMENT_TEMPLATE, jobExecutionInfo.getJobId(), entry.getKey(), entry.getValue(), insert); } } // Insert or update task execution information if (jobExecutionInfo.hasTaskExecutions()) { for (TaskExecutionInfo info : jobExecutionInfo.getTaskExecutions()) { // Insert or update task execution information if (existsTaskExecutionInfo(connection, info)) { updateTaskExecutionInfo(connection, info); } else { insertTaskExecutionInfo(connection, info); } // Insert or update task metrics if (info.hasMetrics()) { for (Metric metric : info.getMetrics()) { boolean insert = !existsMetric(connection, TASK_METRIC_EXIST_QUERY_STATEMENT_TEMPLATE, info.getTaskId(), metric); updateMetric(connection, insert ? TASK_METRIC_INSERT_STATEMENT_TEMPLATE : TASK_METRIC_UPDATE_STATEMENT_TEMPLATE, info.getTaskId(), metric, insert); } } // Insert or update task properties if (info.hasTaskProperties()) { for (Map.Entry<String, String> entry : info.getTaskProperties().entrySet()) { boolean insert = !existsProperty(connection, TASK_PROPERTY_EXIST_QUERY_STATEMENT_TEMPLATE, info.getTaskId(), entry.getKey()); updateProperty(connection, insert ? TASK_PROPERTY_INSERT_STATEMENT_TEMPLATE : TASK_PROPERTY_UPDATE_STATEMENT_TEMPLATE, info.getTaskId(), entry.getKey(), entry.getValue(), insert); } } } } connection.commit(); } catch (SQLException se) { LOGGER.error("Failed to put a new job execution information record", se); if (connectionOptional.isPresent()) { try { connectionOptional.get().rollback(); } catch (SQLException se1) { LOGGER.error("Failed to rollback", se1); } } throw new IOException(se); } finally { if (connectionOptional.isPresent()) { try { connectionOptional.get().close(); } catch (SQLException se) { LOGGER.error("Failed to close connection", se); } } } } @Override public synchronized List<JobExecutionInfo> get(JobExecutionQuery query) throws IOException { Preconditions.checkArgument(query.hasId() && query.hasIdType()); Optional<Connection> connectionOptional = Optional.absent(); try { connectionOptional = Optional.of(getConnection()); Connection connection = connectionOptional.get(); switch (query.getIdType()) { case JOB_ID: List<JobExecutionInfo> jobExecutionInfos = Lists.newArrayList(); JobExecutionInfo jobExecutionInfo = processQueryById(connection, query.getId().getString(), query, Filter.MISSING); if (jobExecutionInfo != null) { jobExecutionInfos.add(jobExecutionInfo); } return jobExecutionInfos; case JOB_NAME: return processQueryByJobName(connection, query.getId().getString(), query, Filter.MISSING); case TABLE: return processQueryByTable(connection, query); case LIST_TYPE: return processListQuery(connection, query); default: throw new IOException("Unsupported query ID type: " + query.getIdType().name()); } } catch (SQLException se) { LOGGER.error("Failed to execute query: " + query, se); throw new IOException(se); } finally { if (connectionOptional.isPresent()) { try { connectionOptional.get().close(); } catch (SQLException se) { LOGGER.error("Failed to close connection", se); } } } } @Override public void close() throws IOException { // Nothing to do } private Connection getConnection() throws SQLException { return this.dataSource.getConnection(); } private static boolean existsJobExecutionInfo(Connection connection, JobExecutionInfo info) throws SQLException { Preconditions.checkArgument(info.hasJobId()); try (PreparedStatement queryStatement = connection .prepareStatement(JOB_EXECUTION_QUERY_BY_JOB_ID_STATEMENT_TEMPLATE)) { queryStatement.setString(1, info.getJobId()); try (ResultSet resultSet = queryStatement.executeQuery()) { return resultSet.next(); } } } private static void insertJobExecutionInfo(Connection connection, JobExecutionInfo info) throws SQLException { Preconditions.checkArgument(info.hasJobName()); Preconditions.checkArgument(info.hasJobId()); try (PreparedStatement insertStatement = connection.prepareStatement(JOB_EXECUTION_INSERT_STATEMENT_TEMPLATE)) { int index = 0; insertStatement.setString(++index, info.getJobName()); insertStatement.setString(++index, info.getJobId()); insertStatement .setTimestamp(++index, info.hasStartTime() ? new Timestamp(info.getStartTime()) : DEFAULT_TIMESTAMP, getCalendarUTCInstance()); insertStatement.setTimestamp(++index, info.hasEndTime() ? new Timestamp(info.getEndTime()) : DEFAULT_TIMESTAMP, getCalendarUTCInstance()); insertStatement.setLong(++index, info.hasDuration() ? info.getDuration() : -1); insertStatement.setString(++index, info.hasState() ? info.getState().name() : null); insertStatement.setInt(++index, info.hasLaunchedTasks() ? info.getLaunchedTasks() : -1); insertStatement.setInt(++index, info.hasCompletedTasks() ? info.getCompletedTasks() : -1); insertStatement.setString(++index, info.hasLauncherType() ? info.getLauncherType().name() : null); insertStatement.setString(++index, info.hasTrackingUrl() ? info.getTrackingUrl() : null); insertStatement.executeUpdate(); } } private static void updateJobExecutionInfo(Connection connection, JobExecutionInfo info) throws SQLException { Preconditions.checkArgument(info.hasJobId()); try (PreparedStatement updateStatement = connection.prepareStatement(JOB_EXECUTION_UPDATE_STATEMENT_TEMPLATE)) { int index = 0; updateStatement .setTimestamp(++index, info.hasStartTime() ? new Timestamp(info.getStartTime()) : DEFAULT_TIMESTAMP, getCalendarUTCInstance()); updateStatement.setTimestamp(++index, info.hasEndTime() ? new Timestamp(info.getEndTime()) : DEFAULT_TIMESTAMP, getCalendarUTCInstance()); updateStatement.setLong(++index, info.hasDuration() ? info.getDuration() : -1); updateStatement.setString(++index, info.hasState() ? info.getState().name() : null); updateStatement.setInt(++index, info.hasLaunchedTasks() ? info.getLaunchedTasks() : -1); updateStatement.setInt(++index, info.hasCompletedTasks() ? info.getCompletedTasks() : -1); updateStatement.setString(++index, info.hasLauncherType() ? info.getLauncherType().name() : null); updateStatement.setString(++index, info.hasTrackingUrl() ? info.getTrackingUrl() : null); updateStatement.setString(++index, info.getJobId()); updateStatement.executeUpdate(); } } private static boolean existsTaskExecutionInfo(Connection connection, TaskExecutionInfo info) throws SQLException { Preconditions.checkArgument(info.hasTaskId()); try (PreparedStatement queryStatement = connection.prepareStatement(TASK_EXECUTION_EXIST_QUERY_STATEMENT_TEMPLATE)) { queryStatement.setString(1, info.getTaskId()); try (ResultSet resultSet = queryStatement.executeQuery()) { return resultSet.next(); } } } private static void insertTaskExecutionInfo(Connection connection, TaskExecutionInfo info) throws SQLException { Preconditions.checkArgument(info.hasTaskId()); Preconditions.checkArgument(info.hasJobId()); try (PreparedStatement insertStatement = connection.prepareStatement(TASK_EXECUTION_INSERT_STATEMENT_TEMPLATE)) { int index = 0; insertStatement.setString(++index, info.getTaskId()); insertStatement.setString(++index, info.getJobId()); insertStatement .setTimestamp(++index, info.hasStartTime() ? new Timestamp(info.getStartTime()) : DEFAULT_TIMESTAMP, getCalendarUTCInstance()); insertStatement.setTimestamp(++index, info.hasEndTime() ? new Timestamp(info.getEndTime()) : DEFAULT_TIMESTAMP, getCalendarUTCInstance()); insertStatement.setLong(++index, info.hasDuration() ? info.getDuration() : -1); insertStatement.setString(++index, info.hasState() ? info.getState().name() : null); insertStatement.setString(++index, info.hasFailureException() ? info.getFailureException() : null); insertStatement.setLong(++index, info.hasLowWatermark() ? info.getLowWatermark() : -1); insertStatement.setLong(++index, info.hasHighWatermark() ? info.getHighWatermark() : -1); insertStatement.setString(++index, info.hasTable() && info.getTable().hasNamespace() ? info.getTable().getNamespace() : null); insertStatement .setString(++index, info.hasTable() && info.getTable().hasName() ? info.getTable().getName() : null); insertStatement .setString(++index, info.hasTable() && info.getTable().hasType() ? info.getTable().getType().name() : null); insertStatement.executeUpdate(); } } private static void updateTaskExecutionInfo(Connection connection, TaskExecutionInfo info) throws SQLException { Preconditions.checkArgument(info.hasTaskId()); try (PreparedStatement updateStatement = connection.prepareStatement(TASK_EXECUTION_UPDATE_STATEMENT_TEMPLATE)) { int index = 0; updateStatement .setTimestamp(++index, info.hasStartTime() ? new Timestamp(info.getStartTime()) : DEFAULT_TIMESTAMP, getCalendarUTCInstance()); updateStatement.setTimestamp(++index, info.hasEndTime() ? new Timestamp(info.getEndTime()) : DEFAULT_TIMESTAMP, getCalendarUTCInstance()); updateStatement.setLong(++index, info.hasDuration() ? info.getDuration() : -1); updateStatement.setString(++index, info.hasState() ? info.getState().name() : null); updateStatement.setString(++index, info.hasFailureException() ? info.getFailureException() : null); updateStatement.setLong(++index, info.hasLowWatermark() ? info.getLowWatermark() : -1); updateStatement.setLong(++index, info.hasHighWatermark() ? info.getHighWatermark() : -1); updateStatement.setString(++index, info.hasTable() && info.getTable().hasNamespace() ? info.getTable().getNamespace() : null); updateStatement .setString(++index, info.hasTable() && info.getTable().hasName() ? info.getTable().getName() : null); updateStatement .setString(++index, info.hasTable() && info.getTable().hasType() ? info.getTable().getType().name() : null); updateStatement.setString(++index, info.getTaskId()); updateStatement.executeUpdate(); } } private static boolean existsMetric(Connection connection, String template, String id, Metric metric) throws SQLException { Preconditions.checkArgument(!Strings.isNullOrEmpty(id)); Preconditions.checkArgument(metric.hasGroup()); Preconditions.checkArgument(metric.hasName()); Preconditions.checkArgument(metric.hasType()); try (PreparedStatement queryStatement = connection.prepareStatement(template)) { int index = 0; queryStatement.setString(++index, id); queryStatement.setString(++index, metric.getGroup()); queryStatement.setString(++index, metric.getName()); queryStatement.setString(++index, metric.getType().name()); try (ResultSet resultSet = queryStatement.executeQuery()) { return resultSet.next(); } } } private static void updateMetric(Connection connection, String template, String id, Metric metric, boolean insert) throws SQLException { Preconditions.checkArgument(!Strings.isNullOrEmpty(id)); Preconditions.checkArgument(metric.hasGroup()); Preconditions.checkArgument(metric.hasName()); Preconditions.checkArgument(metric.hasType()); Preconditions.checkArgument(metric.hasValue()); try (PreparedStatement updateStatement = connection.prepareStatement(template)) { int index = 0; if (insert) { updateStatement.setString(++index, id); updateStatement.setString(++index, metric.getGroup()); updateStatement.setString(++index, metric.getName()); updateStatement.setString(++index, metric.getType().name()); updateStatement.setString(++index, metric.getValue()); } else { updateStatement.setString(++index, metric.getValue()); updateStatement.setString(++index, id); updateStatement.setString(++index, metric.getGroup()); updateStatement.setString(++index, metric.getName()); updateStatement.setString(++index, metric.getType().name()); } updateStatement.executeUpdate(); } } private static boolean existsProperty(Connection connection, String template, String id, String key) throws SQLException { Preconditions.checkArgument(!Strings.isNullOrEmpty(id)); Preconditions.checkArgument(!Strings.isNullOrEmpty(key)); try (PreparedStatement queryStatement = connection.prepareStatement(template)) { int index = 0; queryStatement.setString(++index, id); queryStatement.setString(++index, key); try (ResultSet resultSet = queryStatement.executeQuery()) { return resultSet.next(); } } } private static void updateProperty(Connection connection, String template, String id, String key, String value, boolean insert) throws SQLException { Preconditions.checkArgument(!Strings.isNullOrEmpty(id)); Preconditions.checkArgument(!Strings.isNullOrEmpty(key)); Preconditions.checkArgument(!Strings.isNullOrEmpty(value)); try (PreparedStatement updateStatement = connection.prepareStatement(template)) { int index = 0; if (insert) { updateStatement.setString(++index, id); updateStatement.setString(++index, key); updateStatement.setString(++index, value); } else { updateStatement.setString(++index, value); updateStatement.setString(++index, id); updateStatement.setString(++index, key); } updateStatement.executeUpdate(); } } private JobExecutionInfo processQueryById(Connection connection, String jobId, JobExecutionQuery query, Filter tableFilter) throws SQLException { Preconditions.checkArgument(!Strings.isNullOrEmpty(jobId)); // Query job execution information try (PreparedStatement jobExecutionQueryStatement = connection .prepareStatement(JOB_EXECUTION_QUERY_BY_JOB_ID_STATEMENT_TEMPLATE)) { jobExecutionQueryStatement.setString(1, jobId); try (ResultSet jobRs = jobExecutionQueryStatement.executeQuery()) { if (!jobRs.next()) { return null; } JobExecutionInfo jobExecutionInfo = resultSetToJobExecutionInfo(jobRs); // Query job metrics if (query.isIncludeJobMetrics()) { try (PreparedStatement jobMetricQueryStatement = connection .prepareStatement(JOB_METRIC_QUERY_STATEMENT_TEMPLATE)) { jobMetricQueryStatement.setString(1, jobRs.getString(2)); try (ResultSet jobMetricRs = jobMetricQueryStatement.executeQuery()) { MetricArray jobMetrics = new MetricArray(); while (jobMetricRs.next()) { jobMetrics.add(resultSetToMetric(jobMetricRs)); } // Add job metrics jobExecutionInfo.setMetrics(jobMetrics); } } } // Query job properties Set<String> requestedJobPropertyKeys = null; if (query.hasJobProperties()) { requestedJobPropertyKeys = new HashSet<>(Arrays.asList(query.getJobProperties().split(","))); } try (PreparedStatement jobPropertiesQueryStatement = connection .prepareStatement(JOB_PROPERTY_QUERY_STATEMENT_TEMPLATE)) { jobPropertiesQueryStatement.setString(1, jobExecutionInfo.getJobId()); try (ResultSet jobPropertiesRs = jobPropertiesQueryStatement.executeQuery()) { Map<String, String> jobProperties = Maps.newHashMap(); while (jobPropertiesRs.next()) { Map.Entry<String, String> property = resultSetToProperty(jobPropertiesRs); if (requestedJobPropertyKeys == null || requestedJobPropertyKeys.contains(property.getKey())) { jobProperties.put(property.getKey(), property.getValue()); } } // Add job properties jobExecutionInfo.setJobProperties(new StringMap(jobProperties)); } } // Query task execution information if (query.isIncludeTaskExecutions()) { TaskExecutionInfoArray taskExecutionInfos = new TaskExecutionInfoArray(); String taskExecutionQuery = TASK_EXECUTION_QUERY_STATEMENT_TEMPLATE; // Add table filter if applicable if (tableFilter.isPresent()) { taskExecutionQuery += " AND " + tableFilter; } try (PreparedStatement taskExecutionQueryStatement = connection.prepareStatement(taskExecutionQuery)) { taskExecutionQueryStatement.setString(1, jobId); if (tableFilter.isPresent()) { tableFilter.addParameters(taskExecutionQueryStatement, 2); } try (ResultSet taskRs = taskExecutionQueryStatement.executeQuery()) { while (taskRs.next()) { TaskExecutionInfo taskExecutionInfo = resultSetToTaskExecutionInfo(taskRs); // Query task metrics for each task execution record if (query.isIncludeTaskMetrics()) { try (PreparedStatement taskMetricQueryStatement = connection .prepareStatement(TASK_METRIC_QUERY_STATEMENT_TEMPLATE)) { taskMetricQueryStatement.setString(1, taskExecutionInfo.getTaskId()); try (ResultSet taskMetricRs = taskMetricQueryStatement.executeQuery()) { MetricArray taskMetrics = new MetricArray(); while (taskMetricRs.next()) { taskMetrics.add(resultSetToMetric(taskMetricRs)); } // Add task metrics taskExecutionInfo.setMetrics(taskMetrics); } } } taskExecutionInfos.add(taskExecutionInfo); // Query task properties Set<String> queryTaskPropertyKeys = null; if (query.hasTaskProperties()) { queryTaskPropertyKeys = new HashSet<>(Arrays.asList(query.getTaskProperties().split(","))); } try (PreparedStatement taskPropertiesQueryStatement = connection .prepareStatement(TASK_PROPERTY_QUERY_STATEMENT_TEMPLATE)) { taskPropertiesQueryStatement.setString(1, taskExecutionInfo.getTaskId()); try (ResultSet taskPropertiesRs = taskPropertiesQueryStatement.executeQuery()) { Map<String, String> taskProperties = Maps.newHashMap(); while (taskPropertiesRs.next()) { Map.Entry<String, String> property = resultSetToProperty(taskPropertiesRs); if (queryTaskPropertyKeys == null || queryTaskPropertyKeys.contains(property.getKey())) { taskProperties.put(property.getKey(), property.getValue()); } } // Add job properties taskExecutionInfo.setTaskProperties(new StringMap(taskProperties)); } } // Add task properties } // Add task execution information jobExecutionInfo.setTaskExecutions(taskExecutionInfos); } } } return jobExecutionInfo; } } } private List<JobExecutionInfo> processQueryByJobName(Connection connection, String jobName, JobExecutionQuery query, Filter tableFilter) throws SQLException { Preconditions.checkArgument(!Strings.isNullOrEmpty(jobName)); // Construct the query for job IDs by a given job name Filter timeRangeFilter = Filter.MISSING; String jobIdByNameQuery = JOB_ID_QUERY_BY_JOB_NAME_STATEMENT_TEMPLATE; if (query.hasTimeRange()) { // Add time range filter if applicable try { timeRangeFilter = constructTimeRangeFilter(query.getTimeRange()); if (timeRangeFilter.isPresent()) { jobIdByNameQuery += " AND " + timeRangeFilter; } } catch (ParseException pe) { LOGGER.error("Failed to parse the query time range", pe); throw new SQLException(pe); } } // Add ORDER BY jobIdByNameQuery += " ORDER BY created_ts DESC"; List<JobExecutionInfo> jobExecutionInfos = Lists.newArrayList(); // Query job IDs by the given job name try (PreparedStatement queryStatement = connection.prepareStatement(jobIdByNameQuery)) { int limit = query.getLimit(); if (limit > 0) { queryStatement.setMaxRows(limit); } queryStatement.setString(1, jobName); if (timeRangeFilter.isPresent()) { timeRangeFilter.addParameters(queryStatement, 2); } try (ResultSet rs = queryStatement.executeQuery()) { while (rs.next()) { jobExecutionInfos.add(processQueryById(connection, rs.getString(1), query, tableFilter)); } } } return jobExecutionInfos; } private List<JobExecutionInfo> processQueryByTable(Connection connection, JobExecutionQuery query) throws SQLException { Preconditions.checkArgument(query.getId().isTable()); Filter tableFilter = constructTableFilter(query.getId().getTable()); // Construct the query for job names by table definition String jobNameByTableQuery = String.format(JOB_NAME_QUERY_BY_TABLE_STATEMENT_TEMPLATE, tableFilter); List<JobExecutionInfo> jobExecutionInfos = Lists.newArrayList(); // Query job names by table definition try (PreparedStatement queryStatement = connection.prepareStatement(jobNameByTableQuery)) { if (tableFilter.isPresent()) { tableFilter.addParameters(queryStatement, 1); } try (ResultSet rs = queryStatement.executeQuery()) { while (rs.next()) { jobExecutionInfos.addAll(processQueryByJobName(connection, rs.getString(1), query, tableFilter)); } } } return jobExecutionInfos; } private List<JobExecutionInfo> processListQuery(Connection connection, JobExecutionQuery query) throws SQLException { Preconditions.checkArgument(query.getId().isQueryListType()); Filter timeRangeFilter = Filter.MISSING; QueryListType queryType = query.getId().getQueryListType(); String listJobExecutionsQuery = ""; if (queryType == QueryListType.DISTINCT) { listJobExecutionsQuery = LIST_DISTINCT_JOB_EXECUTION_QUERY_TEMPLATE; if (query.hasTimeRange()) { try { timeRangeFilter = constructTimeRangeFilter(query.getTimeRange()); if (timeRangeFilter.isPresent()) { listJobExecutionsQuery += " AND " + timeRangeFilter; } } catch (ParseException pe) { LOGGER.error("Failed to parse the query time range", pe); throw new SQLException(pe); } } } else { listJobExecutionsQuery = LIST_RECENT_JOB_EXECUTION_QUERY_TEMPLATE; } listJobExecutionsQuery += " ORDER BY last_modified_ts DESC"; try (PreparedStatement queryStatement = connection.prepareStatement(listJobExecutionsQuery)) { int limit = query.getLimit(); if (limit > 0) { queryStatement.setMaxRows(limit); } if (timeRangeFilter.isPresent()) { timeRangeFilter.addParameters(queryStatement, 1); } try (ResultSet rs = queryStatement.executeQuery()) { List<JobExecutionInfo> jobExecutionInfos = Lists.newArrayList(); while (rs.next()) { jobExecutionInfos.add(processQueryById(connection, rs.getString(1), query, Filter.MISSING)); } return jobExecutionInfos; } } } private JobExecutionInfo resultSetToJobExecutionInfo(ResultSet rs) throws SQLException { JobExecutionInfo jobExecutionInfo = new JobExecutionInfo(); jobExecutionInfo.setJobName(rs.getString("job_name")); jobExecutionInfo.setJobId(rs.getString("job_id")); try { jobExecutionInfo.setStartTime(rs.getTimestamp("start_time").getTime()); } catch (SQLException se) { jobExecutionInfo.setStartTime(0); } try { jobExecutionInfo.setEndTime(rs.getTimestamp("end_time").getTime()); } catch (SQLException se) { jobExecutionInfo.setEndTime(0); } jobExecutionInfo.setDuration(rs.getLong("duration")); String state = rs.getString("state"); if (!Strings.isNullOrEmpty(state)) { jobExecutionInfo.setState(JobStateEnum.valueOf(state)); } jobExecutionInfo.setLaunchedTasks(rs.getInt("launched_tasks")); jobExecutionInfo.setCompletedTasks(rs.getInt("completed_tasks")); String launcherType = rs.getString("launcher_type"); if (!Strings.isNullOrEmpty(launcherType)) { jobExecutionInfo.setLauncherType(LauncherTypeEnum.valueOf(launcherType)); } String trackingUrl = rs.getString("tracking_url"); if (!Strings.isNullOrEmpty(trackingUrl)) { jobExecutionInfo.setTrackingUrl(trackingUrl); } return jobExecutionInfo; } private static TaskExecutionInfo resultSetToTaskExecutionInfo(ResultSet rs) throws SQLException { TaskExecutionInfo taskExecutionInfo = new TaskExecutionInfo(); taskExecutionInfo.setTaskId(rs.getString("task_id")); taskExecutionInfo.setJobId(rs.getString("job_id")); try { taskExecutionInfo.setStartTime(rs.getTimestamp("start_time").getTime()); } catch (SQLException se) { taskExecutionInfo.setStartTime(0); } try { taskExecutionInfo.setEndTime(rs.getTimestamp("end_time").getTime()); } catch (SQLException se) { taskExecutionInfo.setEndTime(0); } taskExecutionInfo.setDuration(rs.getLong("duration")); String state = rs.getString("state"); if (!Strings.isNullOrEmpty(state)) { taskExecutionInfo.setState(TaskStateEnum.valueOf(state)); } String failureException = rs.getString("failure_exception"); if (!Strings.isNullOrEmpty(failureException)) { taskExecutionInfo.setFailureException(failureException); } taskExecutionInfo.setLowWatermark(rs.getLong("low_watermark")); taskExecutionInfo.setHighWatermark(rs.getLong("high_watermark")); Table table = new Table(); String namespace = rs.getString("table_namespace"); if (!Strings.isNullOrEmpty(namespace)) { table.setNamespace(namespace); } String name = rs.getString("table_name"); if (!Strings.isNullOrEmpty(name)) { table.setName(name); } String type = rs.getString("table_type"); if (!Strings.isNullOrEmpty(type)) { table.setType(TableTypeEnum.valueOf(type)); } taskExecutionInfo.setTable(table); return taskExecutionInfo; } private static Metric resultSetToMetric(ResultSet rs) throws SQLException { Metric metric = new Metric(); metric.setGroup(rs.getString("metric_group")); metric.setName(rs.getString("metric_name")); metric.setType(MetricTypeEnum.valueOf(rs.getString("metric_type"))); metric.setValue(rs.getString("metric_value")); return metric; } private static AbstractMap.SimpleEntry<String, String> resultSetToProperty(ResultSet rs) throws SQLException { return new AbstractMap.SimpleEntry<>(rs.getString(1), rs.getString(2)); } private Filter constructTimeRangeFilter(TimeRange timeRange) throws ParseException { List<String> values = Lists.newArrayList(); StringBuilder sb = new StringBuilder(); if (!timeRange.hasTimeFormat()) { LOGGER.warn("Skipping the time range filter as there is no time format in: " + timeRange); return Filter.MISSING; } DateFormat dateFormat = new SimpleDateFormat(timeRange.getTimeFormat()); boolean hasStartTime = timeRange.hasStartTime(); if (hasStartTime) { sb.append("start_time>?"); values.add(new Timestamp(dateFormat.parse(timeRange.getStartTime()).getTime()).toString()); } if (timeRange.hasEndTime()) { if (hasStartTime) { sb.append(" AND "); } sb.append("end_time<?"); values.add(new Timestamp(dateFormat.parse(timeRange.getEndTime()).getTime()).toString()); } if (sb.length() > 0) { return new Filter(sb.toString(), values); } return Filter.MISSING; } private Filter constructTableFilter(Table table) { List<String> values = Lists.newArrayList(); StringBuilder sb = new StringBuilder(); boolean hasNamespace = table.hasNamespace(); if (hasNamespace) { sb.append("table_namespace=?"); values.add(table.getNamespace()); } boolean hasName = table.hasName(); if (hasName) { if (hasNamespace) { sb.append(" AND "); } sb.append("table_name=?"); values.add(table.getName()); } if (table.hasType()) { if (hasName) { sb.append(" AND "); } sb.append("table_type=?"); values.add(table.getType().name()); } if (sb.length() > 0) { return new Filter(sb.toString(), values); } return Filter.MISSING; } private static Calendar getCalendarUTCInstance() { return Calendar.getInstance(TimeZone.getTimeZone("UTC")); } }
apache-2.0
goodwinnk/intellij-community
platform/vcs-api/vcs-api-core/src/com/intellij/openapi/diff/impl/patch/FilePatch.java
2630
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.openapi.diff.impl.patch; import com.intellij.openapi.util.text.StringUtil; public abstract class FilePatch { private String myBeforeName; private String myAfterName; private String myBeforeVersionId; private String myAfterVersionId; private String myBaseRevisionText; // store file mode in 6 digit format a.e. 100655, -1 means file mode was not changed in the pathc private int myNewFileMode = -1; public String getBeforeName() { return myBeforeName; } public String getAfterName() { return myAfterName; } public String getBeforeFileName() { String[] pathNameComponents = myBeforeName.split("/"); return pathNameComponents [pathNameComponents.length-1]; } public String getAfterFileName() { String[] pathNameComponents = myAfterName.split("/"); return pathNameComponents [pathNameComponents.length-1]; } public void setBeforeName(final String fileName) { myBeforeName = fileName; } public void setAfterName(final String fileName) { myAfterName = fileName; } public String getBeforeVersionId() { return myBeforeVersionId; } public void setBeforeVersionId(final String beforeVersionId) { myBeforeVersionId = beforeVersionId; } public String getAfterVersionId() { return myAfterVersionId; } public void setAfterVersionId(final String afterVersionId) { myAfterVersionId = afterVersionId; } public String getAfterNameRelative(int skipDirs) { String[] components = myAfterName.split("/"); return StringUtil.join(components, skipDirs, components.length, "/"); } public String getBaseRevisionText() { return myBaseRevisionText; } public void setBaseRevisionText(String baseRevisionText) { myBaseRevisionText = baseRevisionText; } public abstract boolean isNewFile(); public abstract boolean isDeletedFile(); public int getNewFileMode() { return myNewFileMode; } public void setNewFileMode(int newFileMode) { myNewFileMode = newFileMode; } }
apache-2.0
ysung-pivotal/incubator-geode
gemfire-core/src/main/java/com/gemstone/gemfire/internal/process/ProcessControllerParameters.java
486
package com.gemstone.gemfire.internal.process; /** * Defines the methods for providing input arguments to the <code>ProcessController</code>. * * Implementations of <code>ProcessController</code> are in this package. Classes that * implement <code>ProcessControllerArguments</code> would typically be in a different * package. * * @author Kirk Lund * @since 8.0 */ public interface ProcessControllerParameters extends FileControllerParameters, MBeanControllerParameters { }
apache-2.0
asedunov/intellij-community
java/java-impl/src/com/intellij/codeInsight/completion/JavaCompletionSession.java
3488
/* * Copyright 2000-2010 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.completion; import com.intellij.codeInsight.lookup.AutoCompletionPolicy; import com.intellij.codeInsight.lookup.LookupElement; import com.intellij.psi.PsiClass; import com.intellij.psi.PsiMethod; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.MultiMap; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Collection; import java.util.HashSet; import java.util.Map; import java.util.Set; /** * @author peter */ public class JavaCompletionSession { private final Set<String> myAddedClasses = new HashSet<>(); private Set<String> myKeywords = new HashSet<>(); private final MultiMap<CompletionResultSet, LookupElement> myBatchItems = MultiMap.create(); private final CompletionResultSet myResult; public JavaCompletionSession(CompletionResultSet result) { myResult = result; } void registerBatchItems(CompletionResultSet result, Collection<LookupElement> elements) { myBatchItems.putValues(result, elements); } void flushBatchItems() { for (Map.Entry<CompletionResultSet, Collection<LookupElement>> entry : myBatchItems.entrySet()) { entry.getKey().addAllElements(entry.getValue()); } myBatchItems.clear(); } public void addClassItem(LookupElement lookupElement) { PsiClass psiClass = extractClass(lookupElement); if (psiClass != null) { registerClass(psiClass); } myResult.addElement(AutoCompletionPolicy.NEVER_AUTOCOMPLETE.applyPolicy(lookupElement)); } @NotNull PrefixMatcher getMatcher() { return myResult.getPrefixMatcher(); } @Nullable private static PsiClass extractClass(LookupElement lookupElement) { final Object object = lookupElement.getObject(); if (object instanceof PsiClass) { return (PsiClass)object; } if (object instanceof PsiMethod && ((PsiMethod)object).isConstructor()) { return ((PsiMethod)object).getContainingClass(); } return null; } public void registerClass(@NotNull PsiClass psiClass) { ContainerUtil.addIfNotNull(myAddedClasses, getClassName(psiClass)); } @Nullable private static String getClassName(@NotNull PsiClass psiClass) { String name = psiClass.getQualifiedName(); return name == null ? psiClass.getName() : name; } public boolean alreadyProcessed(@NotNull LookupElement element) { final PsiClass psiClass = extractClass(element); return psiClass != null && alreadyProcessed(psiClass); } public boolean alreadyProcessed(@NotNull PsiClass object) { final String name = getClassName(object); return name == null || myAddedClasses.contains(name); } public boolean isKeywordAlreadyProcessed(@NotNull String keyword) { return myKeywords.contains(keyword); } void registerKeyword(@NotNull String keyword) { myKeywords.add(keyword); } }
apache-2.0
Flipkart/elasticsearch
src/main/java/org/elasticsearch/action/indexedscripts/put/TransportPutIndexedScriptAction.java
2605
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch 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.elasticsearch.action.indexedscripts.put; import org.elasticsearch.action.ActionListener; import org.elasticsearch.action.index.IndexResponse; import org.elasticsearch.action.support.ActionFilters; import org.elasticsearch.action.support.DelegatingActionListener; import org.elasticsearch.action.support.HandledTransportAction; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.script.ScriptService; import org.elasticsearch.threadpool.ThreadPool; import org.elasticsearch.transport.TransportService; /** * Performs the put indexed script operation. */ public class TransportPutIndexedScriptAction extends HandledTransportAction<PutIndexedScriptRequest, PutIndexedScriptResponse> { private final ScriptService scriptService; @Inject public TransportPutIndexedScriptAction(Settings settings, ThreadPool threadPool, ScriptService scriptService, TransportService transportService, ActionFilters actionFilters) { super(settings, PutIndexedScriptAction.NAME, threadPool, transportService, actionFilters, PutIndexedScriptRequest.class); this.scriptService = scriptService; } @Override protected void doExecute(final PutIndexedScriptRequest request, final ActionListener<PutIndexedScriptResponse> listener) { scriptService.putScriptToIndex(request, new DelegatingActionListener<IndexResponse,PutIndexedScriptResponse>(listener) { @Override public PutIndexedScriptResponse getDelegatedFromInstigator(IndexResponse indexResponse){ return new PutIndexedScriptResponse(indexResponse.getType(),indexResponse.getId(),indexResponse.getVersion(),indexResponse.isCreated()); } }); } }
apache-2.0
openweave/openweave-core
third_party/android/platform-libcore/android-platform-libcore/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/DoubleTest.java
91828
/* 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.harmony.luni.tests.java.lang; import dalvik.annotation.KnownFailure; import dalvik.annotation.TestLevel; import dalvik.annotation.TestTargetNew; import dalvik.annotation.TestTargetClass; import junit.framework.TestCase; import java.util.Locale; @TestTargetClass(Double.class) public class DoubleTest extends TestCase { private static final long rawBitsFor3_4en324ToN1[] = { 0x1L, 0x7L, 0x45L, 0x2b0L, 0x1ae2L, 0x10cd1L, 0xa8028L, 0x69018dL, 0x41a0f7eL, 0x29049aedL, 0x19a2e0d44L, 0x1005cc84acL, 0xa039fd2ebdL, 0x64243e3d361L, 0x3e96a6e641c6L, 0x271e284fe91b8L, 0x1872d931f1b131L, 0x4e8f8f7e6e1d7dL, 0x8319b9af04d26eL, 0xb7e0281ac6070aL, 0xedd832217788ccL, 0x122a71f54eab580L, 0x15750e72a2562e0L, 0x18d2520f4aebb98L, 0x1c2373498ed353fL, 0x1f6c501bf28828eL, 0x22c76422ef2a332L, 0x261c9e95d57a5ffL, 0x2963c63b4ad8f7fL, 0x2cbcb7ca1d8f35fL, 0x3015f2de527981bL, 0x335b6f95e717e22L, 0x36b24b7b60dddabL, 0x3a0f6f2d1c8aa8bL, 0x3d534af863ad52dL, 0x40a81db67c98a79L, 0x440912920ddf68bL, 0x474b5736915742eL, 0x4a9e2d0435ad13aL, 0x4e02dc22a18c2c4L, 0x5143932b49ef375L, 0x549477f61c6b052L, 0x57f995f3a385c67L, 0x5b3bfdb846339c0L, 0x5e8afd2657c0830L, 0x61edbc6fedb0a3dL, 0x653495c5f48e666L, 0x6881bb3771b1fffL, 0x6be22a054e1e7ffL, 0x6f2d5a4350d30ffL, 0x7278b0d42507d3fL, 0x75d6dd092e49c8fL, 0x79264a25bcee1daL, 0x7c6fdcaf2c29a50L, 0x7fcbd3daf7340e4L, 0x831f6468da8088eL, 0x86673d831120ab2L, 0x89c10ce3d568d5fL, 0x8d18a80e656185bL, 0x905ed211feb9e72L, 0x93b686967e6860eL, 0x9712141e0f013c9L, 0x9a56992592c18bbL, 0x9dac3f6ef771eeaL, 0xa10ba7a55aa7352L, 0xa44e918eb151027L, 0xa7a235f25da5430L, 0xab0561b77a8749eL, 0xae46ba2559291c6L, 0xb19868aeaf73637L, 0xb4fe82da5b503c5L, 0xb83f11c8791225bL, 0xbb8ed63a9756af2L, 0xbef28bc93d2c5afL, 0xc237975dc63bb8dL, 0xc5857d3537caa70L, 0xc8e6dc8285bd50cL, 0xcc3049d19396528L, 0xcf7c5c45f87be72L, 0xd2db7357769ae0eL, 0xd6292816aa20cc9L, 0xd973721c54a8ffbL, 0xdcd04ea369d33faL, 0xe0223126222407cL, 0xe36abd6faaad09bL, 0xe6c56ccb95584c2L, 0xea1b63ff3d572f9L, 0xed623cff0cacfb8L, 0xf0bacc3ecfd83a5L, 0xf414bfa741e7247L, 0xf759ef911260ed9L, 0xfab06b7556f9290L, 0xfe0e4329565bb9aL, 0x10151d3f3abf2a80L, 0x104a648f096ef520L, 0x10807ed965e55934L, 0x10b49e8fbf5eaf81L, 0x10e9c633af365b61L, 0x11201be04d81f91dL, 0x115422d860e27764L, 0x11892b8e791b153dL, 0x11bf76721761da8cL, 0x11f3aa074e9d2898L, 0x12289489224472beL, 0x125eb9ab6ad58f6dL, 0x1293340b22c579a4L, 0x12c8010deb76d80dL, 0x12fe015166548e11L, 0x1332c0d2dff4d8caL, 0x1367710797f20efdL, 0x139d4d497dee92bcL, 0x13d2504deeb51bb6L, 0x1406e4616a6262a3L, 0x143c9d79c4fafb4cL, 0x1471e26c1b1cdd0fL, 0x14a65b0721e41453L, 0x14dbf1c8ea5d1968L, 0x1511771d927a2fe1L, 0x1545d4e4f718bbd9L, 0x157b4a1e34deead0L, 0x15b10e52e10b52c2L, 0x15e551e7994e2772L, 0x161aa6617fa1b14fL, 0x1650a7fcefc50ed1L, 0x1684d1fc2bb65286L, 0x16ba067b36a3e727L, 0x16f0440d02267078L, 0x1724551042b00c96L, 0x17596a54535c0fbcL, 0x178fc4e9683313abL, 0x17c3db11e11fec4bL, 0x17f8d1d65967e75eL, 0x182f064befc1e135L, 0x186363ef75d92cc1L, 0x18983ceb534f77f1L, 0x18ce4c26282355eeL, 0x1902ef97d91615b5L, 0x1937ab7dcf5b9b22L, 0x196d965d433281eaL, 0x19a27dfa49ff9132L, 0x19d71d78dc7f757fL, 0x1a0ce4d7139f52dfL, 0x1a420f066c4393cbL, 0x1a7692c8075478beL, 0x1aac377a092996edL, 0x1ae1a2ac45b9fe54L, 0x1b160b5757287de9L, 0x1b4b8e2d2cf29d64L, 0x1b8138dc3c17a25eL, 0x1bb587134b1d8af6L, 0x1beae8d81de4edb4L, 0x1c20d18712af1490L, 0x1c5505e8d75ad9b4L, 0x1c8a47630d319021L, 0x1cc06c9de83efa15L, 0x1cf487c5624eb89aL, 0x1d29a9b6bae266c1L, 0x1d600a1234cd8038L, 0x1d940c96c200e046L, 0x1dc90fbc72811858L, 0x1dff53ab8f215e6eL, 0x1e33944b3974db05L, 0x1e68795e07d211c6L, 0x1e9e97b589c69637L, 0x1ed31ed1761c1de3L, 0x1f07e685d3a3255bL, 0x1f3de027488beeb2L, 0x1f72ac188d57752fL, 0x1fa7571eb0ad527bL, 0x1fdd2ce65cd8a71aL, 0x20123c0ffa076870L, 0x2046cb13f889428cL, 0x207c7dd8f6ab932fL, 0x20b1cea79a2b3bfeL, 0x20e6425180b60afdL, 0x211bd2e5e0e38dbcL, 0x215163cfac8e3896L, 0x2185bcc397b1c6bbL, 0x21bb2bf47d9e386aL, 0x21f0fb78ce82e342L, 0x22253a5702239c13L, 0x225a88ecc2ac8317L, 0x22909593f9abd1efL, 0x22c4baf8f816c66aL, 0x22f9e9b7361c7805L, 0x2330321281d1cb03L, 0x23643e9722463dc4L, 0x23994e3cead7cd35L, 0x23cfa1cc258dc082L, 0x2403c51f97789851L, 0x2438b6677d56be65L, 0x246ee4015cac6dffL, 0x24a34e80d9ebc4bfL, 0x24d822211066b5efL, 0x250e2aa95480636bL, 0x2542daa9d4d03e23L, 0x257791544a044dabL, 0x25ad75a95c856116L, 0x25e26989d9d35caeL, 0x261703ec504833d9L, 0x264cc4e7645a40d0L, 0x2681fb109eb86882L, 0x26b679d4c66682a2L, 0x26ec1849f800234bL, 0x27218f2e3b00160fL, 0x2755f2f9c9c01b93L, 0x278b6fb83c302277L, 0x27c125d3259e158bL, 0x27f56f47ef059aedL, 0x282acb19eac701a8L, 0x2860bef032bc6109L, 0x2894eeac3f6b794cL, 0x28ca2a574f46579eL, 0x29005a76918bf6c3L, 0x2934711435eef474L, 0x29698d59436ab191L, 0x299ff0af94455df5L, 0x29d3f66dbcab5ab9L, 0x2a08f4092bd63167L, 0x2a3f310b76cbbdc1L, 0x2a737ea72a3f5699L, 0x2aa85e50f4cf2c3fL, 0x2ade75e53202f74fL, 0x2b1309af3f41da91L, 0x2b47cc1b0f125135L, 0x2b7dbf21d2d6e583L, 0x2bb2977523c64f72L, 0x2be73d526cb7e34eL, 0x2c1d0ca707e5dc22L, 0x2c5227e864efa995L, 0x2c86b1e27e2b93faL, 0x2cbc5e5b1db678f9L, 0x2cf1baf8f2920b9cL, 0x2d2629b72f368e83L, 0x2d5bb424fb043223L, 0x2d9150971ce29f56L, 0x2dc5a4bce41b472bL, 0x2dfb0dec1d2218f6L, 0x2e30e8b392354f9aL, 0x2e6522e076c2a380L, 0x2e9a6b9894734c61L, 0x2ed0833f5cc80fbcL, 0x2f04a40f33fa13abL, 0x2f39cd1300f89896L, 0x2f70202be09b5f5eL, 0x2fa42836d8c23735L, 0x2fd932448ef2c503L, 0x300f7ed5b2af7643L, 0x3043af458fada9eaL, 0x30789b16f3991465L, 0x30aec1dcb07f597eL, 0x30e33929ee4f97efL, 0x3118077469e37deaL, 0x314e0951845c5d65L, 0x3182c5d2f2b9ba5fL, 0x31b77747af6828f7L, 0x31ed55199b423335L, 0x3222553001096001L, 0x3256ea7c014bb801L, 0x328ca51b019ea601L, 0x32c1e730e10327c1L, 0x32f660fd1943f1b1L, 0x332bf93c5f94ee1dL, 0x33617bc5bbbd14d2L, 0x3395dab72aac5a07L, 0x33cb5164f5577089L, 0x340112df1956a655L, 0x34355796dfac4febL, 0x346aad7c979763e5L, 0x34a0ac6ddebe9e6fL, 0x34d4d789566e460bL, 0x350a0d6bac09d78eL, 0x354048634b8626b9L, 0x35745a7c1e67b067L, 0x35a9711b26019c81L, 0x35dfcd61ef8203a1L, 0x3613e05d35b14245L, 0x3648d874831d92d6L, 0x367f0e91a3e4f78bL, 0x36b3691b066f1ab7L, 0x36e84361c80ae165L, 0x371e543a3a0d99beL, 0x3752f4a464488017L, 0x3787b1cd7d5aa01cL, 0x37bd9e40dcb14823L, 0x37f282e889eecd16L, 0x382723a2ac6a805cL, 0x385cec8b57852073L, 0x389213d716b33448L, 0x38c698ccdc60015aL, 0x38fc3f00137801b0L, 0x3931a7600c2b010eL, 0x396611380f35c151L, 0x399b9586130331a6L, 0x39d13d73cbe1ff08L, 0x3a058cd0beda7ec9L, 0x3a3af004ee911e7cL, 0x3a70d603151ab30dL, 0x3aa50b83da615fd1L, 0x3ada4e64d0f9b7c5L, 0x3b1070ff029c12dbL, 0x3b448d3ec3431792L, 0x3b79b08e7413dd76L, 0x3bb00e59088c6a6aL, 0x3be411ef4aaf8504L, 0x3c19166b1d5b6646L, 0x3c4f5c05e4b23fd7L, 0x3c839983aeef67e6L, 0x3cb87fe49aab41e0L, 0x3cee9fddc1561258L, 0x3d2323ea98d5cb77L, 0x3d57ece53f0b3e55L, 0x3d8de81e8ece0deaL, 0x3dc2b1131940c8b2L, 0x3df75d57df90fadfL, 0x3e2d34add7753996L, 0x3e6240eca6a943feL, 0x3e96d127d05394fdL, 0x3ecc8571c4687a3dL, 0x3f01d3671ac14c66L, 0x3f364840e1719f80L, 0x3f6bda5119ce075fL, 0x3fa16872b020c49cL, 0x3fd5c28f5c28f5c3L, 0x400B333333333333L }; private static final long rawBitsFor1_2e0To309[] = { 0x3ff3333333333333L, 0x4028000000000000L, 0x405e000000000000L, 0x4092c00000000000L, 0x40c7700000000000L, 0x40fd4c0000000000L, 0x41324f8000000000L, 0x4166e36000000000L, 0x419c9c3800000000L, 0x41d1e1a300000000L, 0x42065a0bc0000000L, 0x423bf08eb0000000L, 0x427176592e000000L, 0x42a5d3ef79800000L, 0x42db48eb57e00000L, 0x43110d9316ec0000L, 0x434550f7dca70000L, 0x437aa535d3d0c000L, 0x43b0a741a4627800L, 0x43e4d1120d7b1600L, 0x441a055690d9db80L, 0x445043561a882930L, 0x4484542ba12a337cL, 0x44b969368974c05bL, 0x44efc3842bd1f072L, 0x4523da329b633647L, 0x4558d0bf423c03d9L, 0x458f04ef12cb04cfL, 0x45c363156bbee301L, 0x45f83bdac6ae9bc2L, 0x462e4ad1785a42b2L, 0x4662eec2eb3869afL, 0x4697aa73a606841bL, 0x46cd95108f882522L, 0x47027d2a59b51735L, 0x47371c74f0225d03L, 0x476ce3922c2af443L, 0x47a20e3b5b9ad8aaL, 0x47d691ca32818ed5L, 0x480c363cbf21f28aL, 0x4841a1e5f7753796L, 0x48760a5f7552857cL, 0x48ab8cf752a726daL, 0x48e1381a93a87849L, 0x491586213892965bL, 0x494ae7a986b73bf1L, 0x4980d0c9f4328577L, 0x49b504fc713f26d5L, 0x49ea463b8d8ef08aL, 0x4a206be538795656L, 0x4a5486de8697abecL, 0x4a89a896283d96e6L, 0x4ac0095dd9267e50L, 0x4af40bb54f701de4L, 0x4b290ea2a34c255dL, 0x4b5f524b4c1f2eb4L, 0x4b93936f0f937d31L, 0x4bc8784ad3785c7dL, 0x4bfe965d8856739cL, 0x4c331dfa75360842L, 0x4c67e57912838a52L, 0x4c9dded757246ce6L, 0x4cd2ab469676c410L, 0x4d0756183c147514L, 0x4d3d2b9e4b199259L, 0x4d723b42eeeffb78L, 0x4da6ca13aaabfa56L, 0x4ddc7c989556f8ebL, 0x4e11cddf5d565b93L, 0x4e46415734abf278L, 0x4e7bd1ad01d6ef15L, 0x4eb1630c2126556dL, 0x4ee5bbcf296feac9L, 0x4f1b2ac2f3cbe57bL, 0x4f50fab9d85f6f6dL, 0x4f8539684e774b48L, 0x4fba87c262151e1aL, 0x4ff094d97d4d32d0L, 0x5024ba0fdca07f84L, 0x5059e893d3c89f65L, 0x5090315c645d639fL, 0x50c43db37d74bc87L, 0x50f94d205cd1eba9L, 0x512fa06874066693L, 0x5163c4414884001cL, 0x5198b5519aa50023L, 0x51cee2a6014e402cL, 0x52034da7c0d0e81bL, 0x52382111b1052222L, 0x526e29561d466aabL, 0x52a2d9d5d24c02abL, 0x52d7904b46df0355L, 0x530d745e1896c42bL, 0x534268bacf5e3a9bL, 0x537702e98335c941L, 0x53acc3a3e4033b92L, 0x53e1fa466e82053bL, 0x541678d80a22868aL, 0x544c170e0cab282cL, 0x54818e68c7eaf91cL, 0x54b5f202f9e5b763L, 0x54eb6e83b85f253bL, 0x55212512533b7745L, 0x55556e56e80a5516L, 0x558ac9eca20cea5cL, 0x55c0be33e5481279L, 0x55f4edc0de9a1718L, 0x562a293116409cdeL, 0x566059beade8620bL, 0x5694702e59627a8dL, 0x56c98c39efbb1931L, 0x56ffef486ba9df7dL, 0x5733f58d434a2baeL, 0x5768f2f0941cb699L, 0x579f2facb923e440L, 0x57d37dcbf3b66ea8L, 0x58085d3ef0a40a52L, 0x583e748eaccd0ce6L, 0x587308d92c002810L, 0x58a7cb0f77003214L, 0x58ddbdd354c03e99L, 0x591296a414f82720L, 0x59473c4d1a3630e8L, 0x597d0b6060c3bd21L, 0x59b2271c3c7a5635L, 0x59e6b0e34b98ebc2L, 0x5a1c5d1c1e7f26b3L, 0x5a51ba31930f7830L, 0x5a8628bdf7d3563cL, 0x5abbb2ed75c82bcaL, 0x5af14fd4699d1b5fL, 0x5b25a3c984046236L, 0x5b5b0cbbe5057ac4L, 0x5b90e7f56f236cbaL, 0x5bc521f2caec47e9L, 0x5bfa6a6f7da759e3L, 0x5c308285ae88982eL, 0x5c64a3271a2abe39L, 0x5c99cbf0e0b56dc8L, 0x5cd01f768c71649dL, 0x5d0427542f8dbdc4L, 0x5d3931293b712d35L, 0x5d6f7d738a4d7882L, 0x5da3ae6836706b51L, 0x5dd89a02440c8626L, 0x5e0ec082d50fa7afL, 0x5e433851c529c8ceL, 0x5e78066636743b01L, 0x5eae07ffc41149c1L, 0x5ee2c4ffda8ace19L, 0x5f17763fd12d819fL, 0x5f4d53cfc578e207L, 0x5f825461db6b8d44L, 0x5fb6e97a52467095L, 0x5feca3d8e6d80cbbL, 0x6021e667904707f5L, 0x605660017458c9f2L, 0x608bf801d16efc6eL, 0x60c17b0122e55dc5L, 0x60f5d9c16b9eb536L, 0x612b5031c6866284L, 0x6161121f1c13fd92L, 0x619556a6e318fcf7L, 0x61caac509bdf3c34L, 0x6200abb2616b85a1L, 0x6234d69ef9c66709L, 0x626a0c46b83800cbL, 0x62a047ac3323007fL, 0x62d459973febc09fL, 0x63096ffd0fe6b0c6L, 0x633fcbfc53e05cf8L, 0x6373df7db46c3a1bL, 0x63a8d75d218748a2L, 0x63df0d3469e91acaL, 0x64136840c231b0beL, 0x64484250f2be1ceeL, 0x647e52e52f6da42aL, 0x64b2f3cf3da4869aL, 0x64e7b0c30d0da840L, 0x651d9cf3d0511251L, 0x655282186232ab72L, 0x6587229e7abf564fL, 0x65bceb46196f2be3L, 0x65f2130bcfe57b6eL, 0x662697cec3deda49L, 0x665c3dc274d690dbL, 0x6691a69989061a89L, 0x66c6103feb47a12bL, 0x66fb944fe6198976L, 0x67313cb1efcff5eaL, 0x67658bde6bc3f364L, 0x679aeed606b4f03dL, 0x67d0d545c4311626L, 0x68050a97353d5bb0L, 0x683a4d3d028cb29cL, 0x687070462197efa2L, 0x68a48c57a9fdeb8aL, 0x68d9af6d947d666cL, 0x69100da47cce6004L, 0x6944110d9c01f805L, 0x6979155103027606L, 0x69af5aa543c31387L, 0x69e398a74a59ec35L, 0x6a187ed11cf06742L, 0x6a4e9e85642c8112L, 0x6a8323135e9bd0abL, 0x6ab7ebd83642c4d6L, 0x6aede6ce43d3760cL, 0x6b22b040ea6429c7L, 0x6b575c5124fd3439L, 0x6b8d33656e3c8147L, 0x6bc2401f64e5d0cdL, 0x6bf6d0273e1f4500L, 0x6c2c84310da71640L, 0x6c61d29ea8886de8L, 0x6c96474652aa8962L, 0x6ccbd917e7552bbaL, 0x6d0167aef0953b54L, 0x6d35c19aacba8a29L, 0x6d6b320157e92cb4L, 0x6da0ff40d6f1bbf0L, 0x6dd53f110cae2aedL, 0x6e0a8ed54fd9b5a8L, 0x6e40994551e81189L, 0x6e74bf96a66215ebL, 0x6ea9ef7c4ffa9b66L, 0x6ee035adb1fca120L, 0x6f1443191e7bc967L, 0x6f4953df661abbc1L, 0x6f7fa8d73fa16ab2L, 0x6fb3c98687c4e2afL, 0x6fe8bbe829b61b5bL, 0x701eeae23423a232L, 0x705352cd6096455fL, 0x70882780b8bbd6b7L, 0x70be3160e6eacc64L, 0x70f2dedc9052bfbfL, 0x71279693b4676faeL, 0x715d7c38a1814b9aL, 0x71926da364f0cf40L, 0x71c7090c3e2d0310L, 0x71fccb4f4db843d4L, 0x7231ff1190932a65L, 0x72667ed5f4b7f4feL, 0x729c1e8b71e5f23dL, 0x72d19317272fb766L, 0x7305f7dcf0fba540L, 0x733b75d42d3a8e90L, 0x737129a49c44991aL, 0x73a5740dc355bf60L, 0x73dad111342b2f39L, 0x7410c2aac09afd83L, 0x7444f35570c1bce4L, 0x747a302accf22c1dL, 0x74b05e1ac0175b92L, 0x74e475a1701d3277L, 0x75199309cc247f15L, 0x754ff7cc3f2d9edaL, 0x7583fadfa77c8348L, 0x75b8f997915ba41aL, 0x75ef37fd75b28d21L, 0x762382fe698f9834L, 0x765863be03f37e41L, 0x768e7cad84f05dd2L, 0x76c30dec73163aa3L, 0x76f7d1678fdbc94cL, 0x772dc5c173d2bb9fL, 0x77629b98e863b543L, 0x7797427f227ca294L, 0x77cd131eeb1bcb39L, 0x78022bf352f15f04L, 0x7836b6f027adb6c5L, 0x786c64ac31992476L, 0x78a1beeb9effb6caL, 0x78d62ea686bfa47cL, 0x790bba50286f8d9bL, 0x794154721945b881L, 0x7975a98e9f9726a1L, 0x79ab13f2477cf049L, 0x79e0ec776cae162eL, 0x7a15279547d99bb9L, 0x7a4a717a99d002a8L, 0x7a8086eca02201a9L, 0x7ab4a8a7c82a8213L, 0x7ae9d2d1ba352298L, 0x7b2023c31461359fL, 0x7b542cb3d9798307L, 0x7b8937e0cfd7e3c8L, 0x7bbf85d903cddcbaL, 0x7bf3b3a7a260a9f4L, 0x7c28a0918af8d472L, 0x7c5ec8b5edb7098eL, 0x7c933d71b49265f9L, 0x7cc80cce21b6ff77L, 0x7cfe1001aa24bf55L, 0x7d32ca010a56f795L, 0x7d677c814cecb57aL, 0x7d9d5ba1a027e2d9L, 0x7dd259450418edc7L, 0x7e06ef96451f2939L, 0x7e3cab7bd666f388L, 0x7e71eb2d66005835L, 0x7ea665f8bf806e42L, 0x7edbff76ef6089d2L, 0x7f117faa559c5623L, 0x7f45df94eb036bacL, 0x7f7b577a25c44697L, 0x7fb116ac579aac1fL, 0x7fe55c576d815726L, 0x7ff0000000000000L }; private void doTestCompareRawBits(String originalDoubleString, long expectedRawBits, String expectedString) { double result; long rawBits; String convertedString; result = Double.parseDouble(originalDoubleString); rawBits = Double.doubleToLongBits(result); convertedString = new Double(result).toString(); assertEquals(expectedRawBits, rawBits); assertEquals(expectedString.toLowerCase(Locale.US), convertedString .toLowerCase(Locale.US)); } private void test_toString(double dd, String answer) { assertEquals(answer, Double.toString(dd)); Double d = new Double(dd); assertEquals(answer, Double.toString(d.doubleValue())); assertEquals(answer, d.toString()); } /** * @tests java.lang.Double#Double(double) */ @TestTargetNew( level = TestLevel.COMPLETE, notes = "", method = "Double", args = {double.class} ) public void test_ConstructorD() { Double d = new Double(39089.88888888888888888888888888888888); assertEquals("Created incorrect double", 39089.88888888888888888888888888888888, d .doubleValue(), 0D); } /** * @tests java.lang.Double#Double(java.lang.String) */ @TestTargetNew( level = TestLevel.COMPLETE, notes = "", method = "Double", args = {java.lang.String.class} ) public void test_ConstructorLjava_lang_String() { Double d = new Double("39089.88888888888888888888888888888888"); assertEquals("Created incorrect double", 39089.88888888888888888888888888888888, d .doubleValue(), 0D); // REGRESSION for HARMONY-489 try { d = new Double("1E+-20"); fail("new Double(\"1E+-20\") should throw exception"); } catch (NumberFormatException e) { // expected } } /** * @tests java.lang.Double#byteValue() */ @TestTargetNew( level = TestLevel.COMPLETE, notes = "", method = "byteValue", args = {} ) public void test_byteValue() { Double d = new Double(1923311.47712); assertEquals("Returned incorrect byte value", (byte) -17, d.byteValue()); d= new Double(Byte.MAX_VALUE); assertEquals("Returned incorrect byte value", Byte.MAX_VALUE, d.byteValue()); d= new Double(Byte.MIN_VALUE); assertEquals("Returned incorrect byte value", Byte.MIN_VALUE, d.byteValue()); d= new Double(Double.MAX_VALUE); assertEquals("Returned incorrect byte value", -1, d.byteValue()); } /** * @tests java.lang.Double#compareTo(java.lang.Double) * @tests java.lang.Double#compare(double, double) */ @TestTargetNew( level = TestLevel.COMPLETE, notes = "", method = "compare", args = {double.class, double.class} ) public void test_compare() { double[] values = new double[] { Double.NEGATIVE_INFINITY, -Double.MAX_VALUE, -2d, -Double.MIN_VALUE, -0d, 0d, Double.MIN_VALUE, 2d, Double.MAX_VALUE, Double.POSITIVE_INFINITY, Double.NaN }; for (int i = 0; i < values.length; i++) { double d1 = values[i]; assertTrue("compare() should be equal: " + d1, Double.compare(d1, d1) == 0); Double D1 = new Double(d1); assertTrue("compareTo() should be equal: " + d1, D1.compareTo(D1) == 0); for (int j = i + 1; j < values.length; j++) { double d2 = values[j]; assertTrue("compare() " + d1 + " should be less " + d2, Double.compare(d1, d2) == -1); assertTrue("compare() " + d2 + " should be greater " + d1, Double.compare(d2, d1) == 1); Double D2 = new Double(d2); assertTrue("compareTo() " + d1 + " should be less " + d2, D1.compareTo(D2) == -1); assertTrue("compareTo() " + d2 + " should be greater " + d1, D2.compareTo(D1) == 1); } } try { new Double(0.0D).compareTo(null); fail("No NPE"); } catch (NullPointerException e) { } } /** * @tests java.lang.Double#doubleToLongBits(double) */ @TestTargetNew( level = TestLevel.COMPLETE, notes = "", method = "doubleToLongBits", args = {double.class} ) public void test_doubleToLongBitsD() { // Test for method long java.lang.Double.doubleToLongBits(double) Double d = new Double(Double.MAX_VALUE); long lbits = Double.doubleToLongBits(d.doubleValue()); double r = Double.longBitsToDouble(lbits); assertTrue("Bit conversion failed", d.doubleValue() == r); assertEquals(0x7ff8000000000000L, Double.doubleToLongBits(Double.NaN)); assertEquals(0x7ff0000000000000L, Double.doubleToLongBits(Double.POSITIVE_INFINITY)); assertEquals(0xfff0000000000000L, Double.doubleToLongBits(Double.NEGATIVE_INFINITY)); } /** * @tests java.lang.Double#doubleToRawLongBits(double) */ @TestTargetNew( level = TestLevel.COMPLETE, notes = "", method = "doubleToRawLongBits", args = {double.class} ) public void test_doubleToRawLongBitsD() { long l = 0x7ff80000000004d2L; double d = Double.longBitsToDouble(l); assertTrue("Wrong raw bits", Double.doubleToRawLongBits(d) == l); assertEquals(0x7ff8000000000000L, Double.doubleToLongBits(Double.NaN)); assertEquals(0x7ff0000000000000L, Double.doubleToLongBits(Double.POSITIVE_INFINITY)); assertEquals(0xfff0000000000000L, Double.doubleToLongBits(Double.NEGATIVE_INFINITY)); } /** * @tests java.lang.Double#doubleValue() */ @TestTargetNew( level = TestLevel.COMPLETE, notes = "", method = "doubleValue", args = {} ) public void test_doubleValue() { assertEquals("Incorrect double value returned", 999999999999999.9999999999999, new Double(999999999999999.9999999999999).doubleValue(), 0D); assertEquals(Double.POSITIVE_INFINITY, new Double("1.7976931348623159E308").doubleValue()); assertEquals(Double.NEGATIVE_INFINITY, new Double("-1.7976931348623159E308").doubleValue()); assertEquals(Double.MAX_VALUE, new Double("1.7976931348623157E308").doubleValue()); assertEquals(Double.MIN_VALUE, new Double("4.9E-324").doubleValue()); } /** * @tests java.lang.Double#floatValue() */ @TestTargetNew( level = TestLevel.COMPLETE, notes = "", method = "floatValue", args = {} ) public void test_floatValue() { // Test for method float java.lang.Double.floatValue() assertTrue( "Incorrect float value returned ", Math.abs(new Double(999999999999999.9999999999999d). floatValue() - 999999999999999.9999999999999f) < 1); assertEquals(Float.POSITIVE_INFINITY, new Double("3.4028236E38").floatValue()); assertEquals(Float.NEGATIVE_INFINITY, new Double("-3.4028236E38").floatValue()); assertEquals(Float.MAX_VALUE, new Double("3.4028235E38").floatValue()); assertEquals(Float.MIN_VALUE, new Double("1.4E-45").floatValue()); } /** * @tests java.lang.Double#hashCode() */ @TestTargetNew( level = TestLevel.COMPLETE, notes = "", method = "hashCode", args = {} ) public void test_hashCode() { // Test for method int java.lang.Double.hashCode() for (int i = -1000; i < 1000; i++) { Double d = new Double(i); Double dd = new Double(i); assertTrue("Should not be identical ", d != dd); assertTrue("Should be equals 1 ", d.equals(dd)); assertTrue("Should be equals 2 ", dd.equals(d)); assertTrue("Should have identical values ", dd.doubleValue() == d.doubleValue()); assertTrue("Invalid hash for equal but not identical doubles ", d.hashCode() == dd .hashCode()); } assertEquals("Magic assumption hasCode (0.0) = 0 failed", 0, new Double(0.0).hashCode()); } /** * @tests java.lang.Double#intValue() */ @TestTargetNew( level = TestLevel.COMPLETE, notes = "", method = "intValue", args = {} ) public void test_intValue() { // Test for method int java.lang.Double.intValue() Double d = new Double(1923311.47712); assertEquals("Returned incorrect int value", 1923311, d.intValue()); assertEquals("Returned incorrect int value", Integer.MAX_VALUE, new Double(2147483648d).intValue()); assertEquals("Returned incorrect int value", Integer.MIN_VALUE, new Double(-2147483649d).intValue()); } /** * @tests java.lang.Double#isInfinite() */ @TestTargetNew( level = TestLevel.COMPLETE, notes = "", method = "isInfinite", args = {} ) public void test_isInfinite() { // Test for method boolean java.lang.Double.isInfinite() assertTrue("NEGATIVE_INFINITY returned false", new Double(Double.NEGATIVE_INFINITY) .isInfinite()); assertTrue("POSITIVE_INFINITY returned false", new Double(Double.POSITIVE_INFINITY) .isInfinite()); assertTrue("Non infinite number returned true", !(new Double(1000).isInfinite())); } /** * @tests java.lang.Double#isInfinite(double) */ @TestTargetNew( level = TestLevel.COMPLETE, notes = "", method = "isInfinite", args = {double.class} ) public void test_isInfiniteD() { // Test for method boolean java.lang.Double.isInfinite(double) assertTrue("Infinity check failed", Double.isInfinite(Double.NEGATIVE_INFINITY) && (Double.isInfinite(Double.POSITIVE_INFINITY)) && !(Double.isInfinite(Double.MAX_VALUE))); } /** * @tests java.lang.Double#isNaN() */ @TestTargetNew( level = TestLevel.COMPLETE, notes = "", method = "isNaN", args = {} ) public void test_isNaN() { // Test for method boolean java.lang.Double.isNaN() Double d = new Double(0.0 / 0.0); assertTrue("NAN returned false", d.isNaN()); d = new Double(0); assertTrue("Non NAN returned true", !d.isNaN()); } /** * @tests java.lang.Double#isNaN(double) */ @TestTargetNew( level = TestLevel.COMPLETE, notes = "", method = "isNaN", args = {double.class} ) public void test_isNaND() { // Test for method boolean java.lang.Double.isNaN(double) Double d = new Double(0.0 / 0.0); assertTrue("NAN check failed", Double.isNaN(d.doubleValue())); assertFalse("Doesn't return false value", Double.isNaN(new Double(Double.MAX_VALUE))); } /** * @tests java.lang.Double#longBitsToDouble(long) */ @TestTargetNew( level = TestLevel.COMPLETE, notes = "", method = "longBitsToDouble", args = {long.class} ) public void test_longBitsToDoubleJ() { // Test for method double java.lang.Double.longBitsToDouble(long) Double d = new Double(Double.MAX_VALUE); long lbits = Double.doubleToLongBits(d.doubleValue()); double r = Double.longBitsToDouble(lbits); assertTrue("Bit conversion failed", d.doubleValue() == r); } /** * @tests java.lang.Double#longValue() */ @TestTargetNew( level = TestLevel.COMPLETE, notes = "", method = "longValue", args = {} ) public void test_longValue() { // Test for method long java.lang.Double.longValue() Double d = new Double(1923311.47712); assertEquals("Returned incorrect long value", 1923311, d.longValue()); } /** * @tests java.lang.Double#parseDouble(java.lang.String) */ @TestTargetNew( level = TestLevel.PARTIAL_COMPLETE, notes = "Verifies boundary values and the loop due to the difference in the expected output string.", method = "parseDouble", args = {java.lang.String.class} ) public void test_parseDoubleLjava_lang_String() { assertEquals("Incorrect double returned, expected zero.", 0.0, Double .parseDouble("2.4703282292062327208828439643411e-324"), 0.0); assertTrue("Incorrect double returned, expected minimum double.", Double .parseDouble("2.4703282292062327208828439643412e-324") == Double.MIN_VALUE); for (int i = 324; i > 0; i--) { Double.parseDouble("3.4e-" + i); } for (int i = 0; i <= 309; i++) { Double.parseDouble("1.2e" + i); } /* * The first two cases and the last four cases have to placed outside * the loop due to the difference in the expected output string. */ doTestCompareRawBits("3.4e-324", rawBitsFor3_4en324ToN1[0], "4.9e-324"); doTestCompareRawBits("3.4e-323", rawBitsFor3_4en324ToN1[1], "3.5e-323"); for (int i = 322; i > 3; i--) { String testString, expectedString; testString = expectedString = "3.4e-" + i; doTestCompareRawBits(testString, rawBitsFor3_4en324ToN1[324 - i], expectedString); } doTestCompareRawBits("3.4e-3", rawBitsFor3_4en324ToN1[321], "0.0034"); doTestCompareRawBits("3.4e-2", rawBitsFor3_4en324ToN1[322], "0.034"); doTestCompareRawBits("3.4e-1", rawBitsFor3_4en324ToN1[323], "0.34"); doTestCompareRawBits("3.4e-0", rawBitsFor3_4en324ToN1[324], "3.4"); doTestCompareRawBits("1.2e0", rawBitsFor1_2e0To309[0], "1.2"); doTestCompareRawBits("1.2e1", rawBitsFor1_2e0To309[1], "12.0"); doTestCompareRawBits("1.2e2", rawBitsFor1_2e0To309[2], "120.0"); doTestCompareRawBits("1.2e3", rawBitsFor1_2e0To309[3], "1200.0"); doTestCompareRawBits("1.2e4", rawBitsFor1_2e0To309[4], "12000.0"); doTestCompareRawBits("1.2e5", rawBitsFor1_2e0To309[5], "120000.0"); doTestCompareRawBits("1.2e6", rawBitsFor1_2e0To309[6], "1200000.0"); for (int i = 7; i <= 308; i++) { String testString, expectedString; testString = expectedString = "1.2e" + i; doTestCompareRawBits(testString, rawBitsFor1_2e0To309[i], expectedString); } doTestCompareRawBits("1.2e309", rawBitsFor1_2e0To309[309], "Infinity"); doTestCompareRawBits( "111222333444555666777888999000111222333444555666777888999000111222333444555666777888999000111222333444555666777888999000111222333444555666777888999000111222333444555666777888999000111222333444555666777888999000111222333444555666777888999000111222333444555666777888999000111222333444555666777888999000.92233720368547758079223372036854775807", 0x7e054218c295e43fL, "1.1122233344455567E299"); doTestCompareRawBits( "-111222333444555666777888999000111222333444555666777888999000111222333444555666777888999000111222333444555666777888999000111222333444555666777888999000111222333444555666777888999000111222333444555666777888999000111222333444555666777888999000111222333444555666777888999000111222333444555666777888999000.92233720368547758079223372036854775807", 0xfe054218c295e43fL, "-1.1122233344455567E299"); doTestCompareRawBits("1.234123412431233E107", 0x562ae7a25fe706ebL, "1.234123412431233E107"); doTestCompareRawBits("1.2341234124312331E107", 0x562ae7a25fe706ecL, "1.2341234124312331E107"); doTestCompareRawBits("1.2341234124312332E107", 0x562ae7a25fe706ecL, "1.2341234124312331E107"); doTestCompareRawBits("-1.234123412431233E107", 0xd62ae7a25fe706ebL, "-1.234123412431233E107"); doTestCompareRawBits("-1.2341234124312331E107", 0xd62ae7a25fe706ecL, "-1.2341234124312331E107"); doTestCompareRawBits("-1.2341234124312332E107", 0xd62ae7a25fe706ecL, "-1.2341234124312331E107"); doTestCompareRawBits("9.999999999999999e22", 0x44b52d02c7e14af6L, "9.999999999999999e22"); /* * These particular tests verify that the extreme boundary conditions * are converted correctly. */ doTestCompareRawBits("0.0e-309", 0L, "0.0"); doTestCompareRawBits("-0.0e-309", 0x8000000000000000L, "-0.0"); doTestCompareRawBits("0.0e309", 0L, "0.0"); doTestCompareRawBits("-0.0e309", 0x8000000000000000L, "-0.0"); doTestCompareRawBits("0.1e309", 0x7fe1ccf385ebc8a0L, "1.0e308"); doTestCompareRawBits("0.2e309", 0x7ff0000000000000L, "Infinity"); doTestCompareRawBits("65e-325", 1L, "4.9e-324"); doTestCompareRawBits("1000e-326", 2L, "1.0e-323"); doTestCompareRawBits("4.0e-306", 0x86789e3750f791L, "4.0e-306"); doTestCompareRawBits("2.22507e-308", 0xffffe2e8159d0L, "2.22507e-308"); doTestCompareRawBits( "111222333444555666777888999000111228999000.92233720368547758079223372036854775807", 0x48746da623f1dd8bL, "1.1122233344455567E41"); doTestCompareRawBits( "-111222333444555666777888999000111228999000.92233720368547758079223372036854775807", 0xc8746da623f1dd8bL, "-1.1122233344455567E41"); doTestCompareRawBits( "1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890.987654321098765432109876543210987654321098765432109876543210987654321098765432109876543210987654321098765432109876543210987654321098765432109876543210987654321098765432109876543210987654321098765432109876543210987654321098765432109876543210987654321098765432109876543210987654321098765432109876543210", 0x54820fe0ba17f469L, "1.2345678901234567E99"); doTestCompareRawBits( "-1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890.987654321098765432109876543210987654321098765432109876543210987654321098765432109876543210987654321098765432109876543210987654321098765432109876543210987654321098765432109876543210987654321098765432109876543210987654321098765432109876543210987654321098765432109876543210987654321098765432109876543210", 0xd4820fe0ba17f469L, "-1.2345678901234567E99"); doTestCompareRawBits( "179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000.01", 0x7fefffffffffffffL, "1.7976931348623157E308"); doTestCompareRawBits( "-179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000.01", 0xffefffffffffffffL, "-1.7976931348623157E308"); doTestCompareRawBits( "1112223334445556667778889990001112223334445556667778889990001112223334445556667778889990001112223334445556667778889990001112223334445556667778889990001112223334445556667778889990001112223334445556667778889990001112223334445556667778889990001112223334445556667778889990001112223334445556667778889990001234567890", 0x7ff0000000000000L, "Infinity"); doTestCompareRawBits( "-1112223334445556667778889990001112223334445556667778889990001112223334445556667778889990001112223334445556667778889990001112223334445556667778889990001112223334445556667778889990001112223334445556667778889990001112223334445556667778889990001112223334445556667778889990001112223334445556667778889990001234567890", 0xfff0000000000000L, "-Infinity"); doTestCompareRawBits( "179769313486231590000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000.01", 0x7ff0000000000000L, "Infinity"); doTestCompareRawBits( "-179769313486231590000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000.01", 0xfff0000000000000L, "-Infinity"); doTestCompareRawBits( "0.00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000017976931348623157", 0x2b392a32afcc661eL, "1.7976931348623157E-100"); doTestCompareRawBits( "-0.00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000017976931348623157", 0xab392a32afcc661eL, "-1.7976931348623157E-100"); doTestCompareRawBits( "0.0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000017976931348623157", 0x1b3432f0cb68e61L, "1.7976931348623157E-300"); doTestCompareRawBits( "-0.0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000017976931348623157", 0x81b3432f0cb68e61L, "-1.7976931348623157E-300"); doTestCompareRawBits( "0.00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000017976931348623157", 0x2117b590b942L, "1.79769313486234E-310"); doTestCompareRawBits( "-0.00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000017976931348623157", 0x80002117b590b942L, "-1.79769313486234E-310"); doTestCompareRawBits( "0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000017976931348623157", 0xe37L, "1.798E-320"); doTestCompareRawBits( "-0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000017976931348623157", 0x8000000000000e37L, "-1.798E-320"); doTestCompareRawBits( "0.00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001", 0x2L, "1.0E-323"); doTestCompareRawBits( "-0.00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001", 0x8000000000000002L, "-1.0E-323"); doTestCompareRawBits( "0.0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000055595409854908458349204328908234982349050934129878452378432452458968024357823490509341298784523784324524589680243578234905093412987845237843245245896802435782349050934129878452378432452458968024357868024357823490509341298784523784324524589680243578234905093412987845237843245245896802435786802435782349050934129878452378432452458968024357823490509341298784523784324524589680243578", 0x1L, "4.9E-324"); doTestCompareRawBits( "-0.0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000055595409854908458349204328908234982349050934129878452378432452458968024357823490509341298784523784324524589680243578234905093412987845237843245245896802435782349050934129878452378432452458968024357868024357823490509341298784523784324524589680243578234905093412987845237843245245896802435786802435782349050934129878452378432452458968024357823490509341298784523784324524589680243578", 0x8000000000000001L, "-4.9E-324"); } /** * @tests java.lang.Double#parseDouble(java.lang.String) */ @TestTargetNew( level = TestLevel.PARTIAL_COMPLETE, notes = "Verifies NumberFormatException.", method = "parseDouble", args = {java.lang.String.class} ) public void test_parseDouble_LString_Illegal() { try { Double.parseDouble("0.0p0D"); fail("Should throw NumberFormatException."); } catch (NumberFormatException e) { // expected } try { Double.parseDouble("+0x.p1d"); fail("Should throw NumberFormatException."); } catch (NumberFormatException e) { // expected } try { Double.parseDouble("0Xg.gp1D"); fail("Should throw NumberFormatException."); } catch (NumberFormatException e) { // expected } try { Double.parseDouble("-0x1.1p"); fail("Should throw NumberFormatException."); } catch (NumberFormatException e) { // expected } try { Double.parseDouble("+0x 1.1 p2d"); fail("Should throw NumberFormatException."); } catch (NumberFormatException e) { // expected } try { Double.parseDouble("x1.1p2d"); fail("Should throw NumberFormatException."); } catch (NumberFormatException e) { // expected } try { Double.parseDouble(" 0x-2.1p2"); fail("Should throw NumberFormatException."); } catch (NumberFormatException e) { // expected } try { Double.parseDouble(" 0x2.1pad"); fail("Should throw NumberFormatException."); } catch (NumberFormatException e) { // expected } try { Double.parseDouble(" 0x111.222p 22d"); fail("Should throw NumberFormatException."); } catch (NumberFormatException e) { // expected } } /** * @tests java.lang.Double#parseDouble(java.lang.String) */ @TestTargetNew( level = TestLevel.PARTIAL_COMPLETE, notes = "Doesn't check exception.", method = "parseDouble", args = {java.lang.String.class} ) public void test_parseDouble_LString_FromHexString() { double actual; double expected; actual = Double.parseDouble("0x0.0p0D"); assertEquals("Returned incorrect value", 0.0d, actual, 0.0D); actual = Double.parseDouble("0xa.ap+9d"); assertEquals("Returned incorrect value", 5440.0d, actual, 0.0D); actual = Double.parseDouble("+0Xb.10ap8"); assertEquals("Returned incorrect value", 2832.625d, actual, 0.0D); actual = Double.parseDouble("-0X.a0P2D"); assertEquals("Returned incorrect value", -2.5d, actual, 0.0D); actual = Double.parseDouble("\r 0x22.1p2d \t"); assertEquals("Returned incorrect value", 136.25d, actual, 0.0D); actual = Double.parseDouble("0x1.0p-1"); assertEquals("Returned incorrect value", 0.5, actual, 0.0D); actual = Double .parseDouble("0x00000000000000000000000000000000001.0p-1"); assertEquals("Returned incorrect value", 0.5, actual, 0.0D); actual = Double.parseDouble("0x1.0p-00000000000000000000000000001"); assertEquals("Returned incorrect value", 0.5, actual, 0.0D); actual = Double.parseDouble("0x.100000000000000000000000000000000p1"); assertEquals("Returned incorrect value", 0.125, actual, 0.0D); actual = Double.parseDouble("0x0.0p999999999999999999999999999999999999999999999999999999999999999"); assertEquals("Returned incorrect value", 0.0, actual, 0.0D); actual = Double.parseDouble("0xf1.0p9999999999999999999999999999999999999999999999999999999999999999"); assertEquals("Returned incorrect value", Double.POSITIVE_INFINITY, actual, 0.0D); actual = Double.parseDouble("0xffffffffffffffffffffffffffffffffffff.ffffffffffffffffffffffffffffffffffffffffffffffp1"); expected = Double.longBitsToDouble(0x4900000000000000L); assertEquals("Returned incorrect value", expected, actual, 0.0D); actual = Double.parseDouble("0x0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001p1600"); expected = Double.longBitsToDouble(0x7f30000000000000L); assertEquals("Returned incorrect value", expected, actual, 0.0D); actual = Double.parseDouble("0x0.0p-999999999999999999999999999999999999999999999999999999"); assertEquals("Returned incorrect value", 0.0, actual, 0.0D); actual = Double.parseDouble("0xf1.0p-9999999999999999999999999999999999999999999999999999999999999999"); assertEquals("Returned incorrect value", 0.0, actual, 0.0D); actual = Double.parseDouble("0x10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000p-1600"); expected = Double.longBitsToDouble(0xf0000000000000L); assertEquals("Returned incorrect value", expected, actual, 0.0D); actual = Double.parseDouble("0x1.p9223372036854775807"); assertEquals("Returned incorrect value", Double.POSITIVE_INFINITY, actual, 0.0D); actual = Double.parseDouble("0x1.p9223372036854775808"); assertEquals("Returned incorrect value", Double.POSITIVE_INFINITY, actual, 0.0D); actual = Double.parseDouble("0x10.p9223372036854775808"); assertEquals("Returned incorrect value", Double.POSITIVE_INFINITY, actual, 0.0D); actual = Double.parseDouble("0xabcd.ffffffffp+2000"); assertEquals("Returned incorrect value", Double.POSITIVE_INFINITY, actual, 0.0D); actual = Double.parseDouble("0x1.p-9223372036854775808"); assertEquals("Returned incorrect value", 0.0, actual, 0.0D); actual = Double.parseDouble("0x1.p-9223372036854775809"); assertEquals("Returned incorrect value", 0.0, actual, 0.0D); actual = Double.parseDouble("0x.1p-9223372036854775809"); assertEquals("Returned incorrect value", 0.0, actual, 0.0D); actual = Double.parseDouble("0xabcd.ffffffffffffffp-2000"); assertEquals("Returned incorrect value", 0.0, actual, 0.0D); } @TestTargetNew( level = TestLevel.PARTIAL_COMPLETE, notes = "Regression test for hotfix in native code of double parser.", method = "parseDouble", args = {java.lang.String.class} ) public void test_parseDouble_LString_AndroidRegression() { // Android regression test long startTime = System.currentTimeMillis(); double actual = Double.parseDouble("9e551027"); assertTrue("parsing double 9e551027 took too long.", (System.currentTimeMillis() - startTime) < 1000); assertEquals("Returned incorrect value", Double.POSITIVE_INFINITY, actual, 0.0D); } /** * @tests java.lang.Double#parseDouble(java.lang.String) */ @TestTargetNew( level = TestLevel.PARTIAL_COMPLETE, notes = "Verifies positive functionality.", method = "parseDouble", args = {java.lang.String.class} ) public void test_parseDouble_LString_NormalPositiveExponent() { long[] expecteds = { 0x3f323456789abcdfL, 0x40e111012345678aL, 0x41a1110091a2b3c5L, 0x4259998091a2b3c5L, 0x4311110048d159e2L, 0x43c5554048d159e2L, 0x4479998048d159e2L, 0x452dddc048d159e2L, 0x45e111002468acf1L, 0x469333202468acf1L, 0x4751011001234568L, 0x4802112101234568L, 0x48b3213201234568L, 0x4964314301234568L, 0x4a15415401234568L, 0x4ac6516501234568L, 0x4b77617601234568L, 0x4c28718701234568L, 0x4cd9819801234568L, 0x4d9049048091a2b4L, 0x4e4101100091a2b4L, 0x4ef189188091a2b4L, 0x4fa211210091a2b4L, 0x505299298091a2b4L, 0x510321320091a2b4L, 0x51b3a93a8091a2b4L, 0x526431430091a2b4L, 0x5314b94b8091a2b4L, 0x53c841840091a2b4L, 0x5478c98c8091a2b4L, 0x552981980091a2b4L, 0x55da09a08091a2b4L, 0x568a91a90091a2b4L, 0x573b19b18091a2b4L, 0x57eba1ba0091a2b4L, 0x589c29c28091a2b4L, 0x594cb1cb0091a2b4L, 0x5a001d01c048d15aL, 0x5ab061060048d15aL, 0x5b60a50a4048d15aL, 0x5c1101100048d15aL, 0x5cc145144048d15aL, 0x5d7189188048d15aL, 0x5e21cd1cc048d15aL, 0x5ed211210048d15aL, 0x5f8255254048d15aL, 0x603419418048d15aL, 0x60e45d45c048d15aL, 0x6194a14a0048d15aL, 0x6244e54e4048d15aL, 0x62f541540048d15aL, 0x63a585584048d15aL, 0x6455c95c8048d15aL, 0x65060d60c048d15aL, 0x65b651650048d15aL, 0x666815814048d15aL, 0x671859858048d15aL, 0x67c89d89c048d15aL, 0x6878e18e0048d15aL, 0x692925924048d15aL, 0x69d981980048d15aL, 0x6a89c59c4048d15aL, 0x6b3a09a08048d15aL, 0x6bea4da4c048d15aL, 0x6c9c11c10048d15aL, 0x6d4c55c54048d15aL, 0x6dfc99c98048d15aL, 0x6eacddcdc048d15aL, 0x6f5d21d20048d15aL, 0x700d65d64048d15aL, 0x70bdc1dc0048d15aL, 0x716e05e04048d15aL, 0x721e49e48048d15aL, 0x72d00700602468adL, 0x73802902802468adL, 0x74304b04a02468adL, 0x74e06d06c02468adL, 0x75908f08e02468adL, 0x7640b10b002468adL, 0x76f0d30d202468adL, 0x77a10110002468adL, 0x78512312202468adL, 0x79020520402468adL, 0x79b22722602468adL, 0x7a624924802468adL, 0x7b126b26a02468adL, 0x7bc28d28c02468adL, 0x7c72af2ae02468adL, 0x7d22d12d002468adL, 0x7dd2f32f202468adL, 0x7e832132002468adL, 0x7f40011001012345L, 0x7ff0000000000000L, 0x7ff0000000000000L, 0x7ff0000000000000L, 0x7ff0000000000000L, 0x7ff0000000000000L, 0x7ff0000000000000L, 0x7ff0000000000000L, 0x7ff0000000000000L, 0x7ff0000000000000L, 0x7ff0000000000000L, 0x7ff0000000000000L, 0x7ff0000000000000L, 0x7ff0000000000000L, 0x7ff0000000000000L, 0x7ff0000000000000L, 0x7ff0000000000000L, 0x7ff0000000000000L, 0x7ff0000000000000L, 0x7ff0000000000000L, 0x7ff0000000000000L, 0x7ff0000000000000L }; for (int i = 0; i < expecteds.length; i++) { int part = i*11; String inputString = "0x" + part + "." + part + "0123456789abcdefp" + part; double actual = Double.parseDouble(inputString); double expected = Double.longBitsToDouble(expecteds[i]); String expectedString = "0x" + Long.toHexString(Double.doubleToLongBits(expected)); String actualString = "0x" + Long.toHexString(Double.doubleToLongBits(actual)); String errorMsg = i + "th input string is:<" + inputString + ">.The expected result should be:<" + expectedString + ">, but was: <" + actualString + ">. "; assertEquals(errorMsg, expected, actual, 0.0D); } } /** * @tests java.lang.Double#parseDouble(java.lang.String) */ @TestTargetNew( level = TestLevel.PARTIAL_COMPLETE, notes = "Verifies positive functionality.", method = "parseDouble", args = {java.lang.String.class} ) public void test_parseDouble_LString_NormalNegativeExponent() { long[] expecteds = { 0x3f323456789abcdfL, 0x3f8111012345678aL, 0x3ee1110091a2b3c5L, 0x3e39998091a2b3c5L, 0x3d91110048d159e2L, 0x3ce5554048d159e2L, 0x3c39998048d159e2L, 0x3b8dddc048d159e2L, 0x3ae111002468acf1L, 0x3a3333202468acf1L, 0x3991011001234568L, 0x38e2112101234568L, 0x3833213201234568L, 0x3784314301234568L, 0x36d5415401234568L, 0x3626516501234568L, 0x3577617601234568L, 0x34c8718701234568L, 0x3419819801234568L, 0x337049048091a2b4L, 0x32c101100091a2b4L, 0x321189188091a2b4L, 0x316211210091a2b4L, 0x30b299298091a2b4L, 0x300321320091a2b4L, 0x2f53a93a8091a2b4L, 0x2ea431430091a2b4L, 0x2df4b94b8091a2b4L, 0x2d4841840091a2b4L, 0x2c98c98c8091a2b4L, 0x2be981980091a2b4L, 0x2b3a09a08091a2b4L, 0x2a8a91a90091a2b4L, 0x29db19b18091a2b4L, 0x292ba1ba0091a2b4L, 0x287c29c28091a2b4L, 0x27ccb1cb0091a2b4L, 0x27201d01c048d15aL, 0x267061060048d15aL, 0x25c0a50a4048d15aL, 0x251101100048d15aL, 0x246145144048d15aL, 0x23b189188048d15aL, 0x2301cd1cc048d15aL, 0x225211210048d15aL, 0x21a255254048d15aL, 0x20f419418048d15aL, 0x20445d45c048d15aL, 0x1f94a14a0048d15aL, 0x1ee4e54e4048d15aL, 0x1e3541540048d15aL, 0x1d8585584048d15aL, 0x1cd5c95c8048d15aL, 0x1c260d60c048d15aL, 0x1b7651650048d15aL, 0x1ac815814048d15aL, 0x1a1859858048d15aL, 0x19689d89c048d15aL, 0x18b8e18e0048d15aL, 0x180925924048d15aL, 0x175981980048d15aL, 0x16a9c59c4048d15aL, 0x15fa09a08048d15aL, 0x154a4da4c048d15aL, 0x149c11c10048d15aL, 0x13ec55c54048d15aL, 0x133c99c98048d15aL, 0x128cddcdc048d15aL, 0x11dd21d20048d15aL, 0x112d65d64048d15aL, 0x107dc1dc0048d15aL, 0xfce05e04048d15aL, 0xf1e49e48048d15aL, 0xe700700602468adL, 0xdc02902802468adL, 0xd104b04a02468adL, 0xc606d06c02468adL, 0xbb08f08e02468adL, 0xb00b10b002468adL, 0xa50d30d202468adL, 0x9a10110002468adL, 0x8f12312202468adL, 0x8420520402468adL, 0x7922722602468adL, 0x6e24924802468adL, 0x6326b26a02468adL, 0x5828d28c02468adL, 0x4d2af2ae02468adL, 0x422d12d002468adL, 0x372f32f202468adL, 0x2c32132002468adL, 0x220011001012345L, 0x170121012012345L, 0xc0231023012345L, 0x10341034012345L, 0x208a208a024L, 0x41584158L, 0x83388L, 0x108L, 0x0L, 0x0L, 0x0L, 0x0L, 0x0L, 0x0L, 0x0L, 0x0L, 0x0L, 0x0L, 0x0L, 0x0L, 0x0L, 0x0L }; for (int i = 0; i < expecteds.length; i++) { int part = i*11; String inputString = "0x" + part + "." + part + "0123456789abcdefp-" + part; double actual = Double.parseDouble(inputString); double expected = Double.longBitsToDouble(expecteds[i]); String expectedString = "0x" + Long.toHexString(Double.doubleToLongBits(expected)); String actualString = "0x" + Long.toHexString(Double.doubleToLongBits(actual)); String errorMsg = i + "th input string is:<" + inputString + ">.The expected result should be:<" + expectedString + ">, but was: <" + actualString + ">. "; assertEquals(errorMsg, expected, actual, 0.0D); } } /** * @tests java.lang.Double#parseDouble(java.lang.String) */ @TestTargetNew( level = TestLevel.PARTIAL_COMPLETE, notes = "Verifies max boundary.", method = "parseDouble", args = {java.lang.String.class} ) public void test_parseDouble_LString_MaxNormalBoundary() { long[] expecteds = { 0x7fefffffffffffffL, 0x7fefffffffffffffL, 0x7fefffffffffffffL, 0x7fefffffffffffffL, 0x7fefffffffffffffL, 0x7fefffffffffffffL, 0x7fefffffffffffffL, 0x7ff0000000000000L, 0x7ff0000000000000L, 0x7ff0000000000000L, 0x7ff0000000000000L, 0x7ff0000000000000L, 0x7ff0000000000000L, 0x7ff0000000000000L, 0x7ff0000000000000L, 0xffefffffffffffffL, 0xffefffffffffffffL, 0xffefffffffffffffL, 0xffefffffffffffffL, 0xffefffffffffffffL, 0xffefffffffffffffL, 0xffefffffffffffffL, 0xfff0000000000000L, 0xfff0000000000000L, 0xfff0000000000000L, 0xfff0000000000000L, 0xfff0000000000000L, 0xfff0000000000000L, 0xfff0000000000000L, 0xfff0000000000000L }; String[] inputs = { "0x1.fffffffffffffp1023", "0x1.fffffffffffff000000000000000000000000001p1023", "0x1.fffffffffffff1p1023", "0x1.fffffffffffff100000000000000000000000001p1023", "0x1.fffffffffffff1fffffffffffffffffffffffffffffffffffffffffffffp1023", "0x1.fffffffffffff7p1023", "0x1.fffffffffffff700000000000000000000000001p1023", "0x1.fffffffffffff8p1023", "0x1.fffffffffffff800000000000000000000000001p1023", "0x1.fffffffffffff8fffffffffffffffffffffffffffffffffffffffffffffp1023", "0x1.fffffffffffff9p1023", "0x1.fffffffffffff900000000000000000000000001p1023", "0x1.ffffffffffffffp1023", "0x1.ffffffffffffff00000000000000000000000001p1023", "0x1.fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffp1023", "-0x1.fffffffffffffp1023", "-0x1.fffffffffffff000000000000000000000000001p1023", "-0x1.fffffffffffff1p1023", "-0x1.fffffffffffff100000000000000000000000001p1023", "-0x1.fffffffffffff1fffffffffffffffffffffffffffffffffffffffffffffp1023", "-0x1.fffffffffffff7p1023", "-0x1.fffffffffffff700000000000000000000000001p1023", "-0x1.fffffffffffff8p1023", "-0x1.fffffffffffff800000000000000000000000001p1023", "-0x1.fffffffffffff8fffffffffffffffffffffffffffffffffffffffffffffp1023", "-0x1.fffffffffffff9p1023", "-0x1.fffffffffffff900000000000000000000000001p1023", "-0x1.ffffffffffffffp1023", "-0x1.ffffffffffffff00000000000000000000000001p1023", "-0x1.fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffp1023" }; for (int i = 0; i < inputs.length; i++) { double actual = Double.parseDouble(inputs[i]); double expected = Double.longBitsToDouble(expecteds[i]); String expectedString = "0x" + Long.toHexString(Double.doubleToLongBits(expected)); String actualString = "0x" + Long.toHexString(Double.doubleToLongBits(actual)); String errorMsg = i + "th input string is:<" + inputs[i] + ">.The expected result should be:<" + expectedString + ">, but was: <" + actualString + ">. "; assertEquals(errorMsg, expected, actual, 0.0D); } } /** * @tests java.lang.Double#parseDouble(java.lang.String) */ @TestTargetNew( level = TestLevel.PARTIAL_COMPLETE, notes = "Verifies Min boundary.", method = "parseDouble", args = {java.lang.String.class} ) public void test_parseDouble_LString_MinNormalBoundary() { long[] expecteds = { 0x10000000000000L, 0x10000000000000L, 0x10000000000000L, 0x10000000000000L, 0x10000000000000L, 0x10000000000000L, 0x10000000000000L, 0x10000000000000L, 0x10000000000001L, 0x10000000000001L, 0x10000000000001L, 0x10000000000001L, 0x10000000000001L, 0x10000000000001L, 0x10000000000001L, 0x8010000000000000L, 0x8010000000000000L, 0x8010000000000000L, 0x8010000000000000L, 0x8010000000000000L, 0x8010000000000000L, 0x8010000000000000L, 0x8010000000000000L, 0x8010000000000001L, 0x8010000000000001L, 0x8010000000000001L, 0x8010000000000001L, 0x8010000000000001L, 0x8010000000000001L, 0x8010000000000001L }; String[] inputs = { "0x1.0p-1022", "0x1.00000000000001p-1022", "0x1.000000000000010000000000000000001p-1022", "0x1.00000000000001fffffffffffffffffffffffffffffffffp-1022", "0x1.00000000000007p-1022", "0x1.000000000000070000000000000000001p-1022", "0x1.00000000000007fffffffffffffffffffffffffffffffffp-1022", "0x1.00000000000008p-1022", "0x1.000000000000080000000000000000001p-1022", "0x1.00000000000008fffffffffffffffffffffffffffffffffp-1022", "0x1.00000000000009p-1022", "0x1.000000000000090000000000000000001p-1022", "0x1.00000000000009fffffffffffffffffffffffffffffffffp-1022", "0x1.0000000000000fp-1022", "0x1.0000000000000ffffffffffffffffffffffffffffffffffp-1022", "-0x1.0p-1022", "-0x1.00000000000001p-1022", "-0x1.000000000000010000000000000000001p-1022", "-0x1.00000000000001fffffffffffffffffffffffffffffffffp-1022", "-0x1.00000000000007p-1022", "-0x1.000000000000070000000000000000001p-1022", "-0x1.00000000000007fffffffffffffffffffffffffffffffffp-1022", "-0x1.00000000000008p-1022", "-0x1.000000000000080000000000000000001p-1022", "-0x1.00000000000008fffffffffffffffffffffffffffffffffp-1022", "-0x1.00000000000009p-1022", "-0x1.000000000000090000000000000000001p-1022", "-0x1.00000000000009fffffffffffffffffffffffffffffffffp-1022", "-0x1.0000000000000fp-1022", "-0x1.0000000000000ffffffffffffffffffffffffffffffffffp-1022" }; for (int i = 0; i < inputs.length; i++) { double actual = Double.parseDouble(inputs[i]); double expected = Double.longBitsToDouble(expecteds[i]); String expectedString = "0x" + Long.toHexString(Double.doubleToLongBits(expected)); String actualString = "0x" + Long.toHexString(Double.doubleToLongBits(actual)); String errorMsg = i + "th input string is:<" + inputs[i] + ">.The expected result should be:<" + expectedString + ">, but was: <" + actualString + ">. "; assertEquals(errorMsg, expected, actual, 0.0D); } } /** * @tests java.lang.Double#parseDouble(java.lang.String) */ @TestTargetNew( level = TestLevel.PARTIAL_COMPLETE, notes = "Verifies Max boundary.", method = "parseDouble", args = {java.lang.String.class} ) public void test_parseDouble_LString_MaxSubNormalBoundary() { long[] expecteds = { 0xfffffffffffffL, 0xfffffffffffffL, 0xfffffffffffffL, 0xfffffffffffffL, 0xfffffffffffffL, 0xfffffffffffffL, 0xfffffffffffffL, 0x10000000000000L, 0x10000000000000L, 0x10000000000000L, 0x10000000000000L, 0x10000000000000L, 0x10000000000000L, 0x10000000000000L, 0x10000000000000L, 0x800fffffffffffffL, 0x800fffffffffffffL, 0x800fffffffffffffL, 0x800fffffffffffffL, 0x800fffffffffffffL, 0x800fffffffffffffL, 0x800fffffffffffffL, 0x8010000000000000L, 0x8010000000000000L, 0x8010000000000000L, 0x8010000000000000L, 0x8010000000000000L, 0x8010000000000000L, 0x8010000000000000L, 0x8010000000000000L }; String[] inputs = { "0x0.fffffffffffffp-1022", "0x0.fffffffffffff00000000000000000000000000000000001p-1022", "0x0.fffffffffffff1p-1022", "0x0.fffffffffffff10000000000000000000000000000000001p-1022", "0x0.fffffffffffff1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffp-1022", "0x0.fffffffffffff7p-1022", "0x0.fffffffffffff7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffp-1022", "0x0.fffffffffffff8p-1022", "0x0.fffffffffffff80000000000000000000000000000000001p-1022", "0x0.fffffffffffff8ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffp-1022", "0x0.fffffffffffff9p-1022", "0x0.fffffffffffff9ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffp-1022", "0x0.ffffffffffffffp-1022", "0x0.ffffffffffffff0000000000000000000000000000000001p-1022", "0x0.ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffp-1022", "-0x0.fffffffffffffp-1022", "-0x0.fffffffffffff00000000000000000000000000000000001p-1022", "-0x0.fffffffffffff1p-1022", "-0x0.fffffffffffff10000000000000000000000000000000001p-1022", "-0x0.fffffffffffff1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffp-1022", "-0x0.fffffffffffff7p-1022", "-0x0.fffffffffffff7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffp-1022", "-0x0.fffffffffffff8p-1022", "-0x0.fffffffffffff80000000000000000000000000000000001p-1022", "-0x0.fffffffffffff8ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffp-1022", "-0x0.fffffffffffff9p-1022", "-0x0.fffffffffffff9ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffp-1022", "-0x0.ffffffffffffffp-1022", "-0x0.ffffffffffffff0000000000000000000000000000000001p-1022", "-0x0.ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffp-1022" }; for (int i = 0; i < inputs.length; i++) { double actual = Double.parseDouble(inputs[i]); double expected = Double.longBitsToDouble(expecteds[i]); String expectedString = "0x" + Long.toHexString(Double.doubleToLongBits(expected)); String actualString = "0x" + Long.toHexString(Double.doubleToLongBits(actual)); String errorMsg = i + "th input string is:<" + inputs[i] + ">.The expected result should be:<" + expectedString + ">, but was: <" + actualString + ">. "; assertEquals(errorMsg, expected, actual, 0.0D); } } /** * @tests java.lang.Double#parseDouble(java.lang.String) */ @TestTargetNew( level = TestLevel.PARTIAL_COMPLETE, notes = "Verifies Min boundary.", method = "parseDouble", args = {java.lang.String.class} ) public void test_parseDouble_LString_MinSubNormalBoundary() { long[] expecteds = { 0x1L, 0x1L, 0x2L, 0x1L, 0x1L, 0x1L, 0x2L, 0x2L, 0x2L, 0x2L, 0x2L, 0x2L, 0x2L, 0x2L, 0x2L, 0x8000000000000001L, 0x8000000000000001L, 0x8000000000000002L, 0x8000000000000001L, 0x8000000000000001L, 0x8000000000000001L, 0x8000000000000002L, 0x8000000000000002L, 0x8000000000000002L, 0x8000000000000002L, 0x8000000000000002L, 0x8000000000000002L, 0x8000000000000002L, 0x8000000000000002L, 0x8000000000000002L }; String[] inputs = { "0x0.0000000000001p-1022", "0x0.00000000000010000000000000000001p-1022", "0x0.0000000000001fffffffffffffffffffffffffffffffffp-1022", "0x0.00000000000017p-1022", "0x0.000000000000170000000000000000001p-1022", "0x0.00000000000017fffffffffffffffffffffffffffffffffp-1022", "0x0.00000000000018p-1022", "0x0.000000000000180000000000000000001p-1022", "0x0.00000000000018fffffffffffffffffffffffffffffffffp-1022", "0x0.00000000000019p-1022", "0x0.000000000000190000000000000000001p-1022", "0x0.00000000000019fffffffffffffffffffffffffffffffffp-1022", "0x0.0000000000001fp-1022", "0x0.0000000000001f0000000000000000001p-1022", "0x0.0000000000001ffffffffffffffffffffffffffffffffffp-1022", "-0x0.0000000000001p-1022", "-0x0.00000000000010000000000000000001p-1022", "-0x0.0000000000001fffffffffffffffffffffffffffffffffp-1022", "-0x0.00000000000017p-1022", "-0x0.000000000000170000000000000000001p-1022", "-0x0.00000000000017fffffffffffffffffffffffffffffffffp-1022", "-0x0.00000000000018p-1022", "-0x0.000000000000180000000000000000001p-1022", "-0x0.00000000000018fffffffffffffffffffffffffffffffffp-1022", "-0x0.00000000000019p-1022", "-0x0.000000000000190000000000000000001p-1022", "-0x0.00000000000019fffffffffffffffffffffffffffffffffp-1022", "-0x0.0000000000001fp-1022", "-0x0.0000000000001f0000000000000000001p-1022", "-0x0.0000000000001ffffffffffffffffffffffffffffffffffp-1022" }; for (int i = 0; i < inputs.length; i++) { double actual = Double.parseDouble(inputs[i]); double expected = Double.longBitsToDouble(expecteds[i]); String expectedString = "0x" + Long.toHexString(Double.doubleToLongBits(expected)); String actualString = "0x" + Long.toHexString(Double.doubleToLongBits(actual)); String errorMsg = i + "th input string is:<" + inputs[i] + ">.The expected result should be:<" + expectedString + ">, but was: <" + actualString + ">. "; assertEquals(errorMsg, expected, actual, 0.0D); } } /** * @tests java.lang.Double#parseDouble(java.lang.String) */ @TestTargetNew( level = TestLevel.PARTIAL_COMPLETE, notes = "Verifies zero boundary.", method = "parseDouble", args = {java.lang.String.class} ) public void test_parseDouble_LString_ZeroBoundary() { long[] expecteds = { 0x0L, 0x0L, 0x0L, 0x1L, 0x1L, 0x1L, 0x1L, 0x1L, 0x1L, 0x8000000000000000L, 0x8000000000000000L, 0x8000000000000000L, 0x8000000000000001L, 0x8000000000000001L, 0x8000000000000001L, 0x8000000000000001L, 0x8000000000000001L, 0x8000000000000001L }; String[] inputs = { "0x0.00000000000004p-1022", "0x0.00000000000007ffffffffffffffffffffffp-1022", "0x0.00000000000008p-1022", "0x0.000000000000080000000000000000001p-1022", "0x0.00000000000008fffffffffffffffffffffffffffffffp-1022", "0x0.00000000000009p-1022", "0x0.000000000000090000000000000000001p-1022", "0x0.00000000000009fffffffffffffffffffffffffffffffffp-1022", "0x0.0000000000000fffffffffffffffffffffffffffffffffffp-1022", "-0x0.00000000000004p-1022", "-0x0.00000000000007ffffffffffffffffffffffp-1022", "-0x0.00000000000008p-1022", "-0x0.000000000000080000000000000000001p-1022", "-0x0.00000000000008fffffffffffffffffffffffffffffffp-1022", "-0x0.00000000000009p-1022", "-0x0.000000000000090000000000000000001p-1022", "-0x0.00000000000009fffffffffffffffffffffffffffffffffp-1022", "-0x0.0000000000000fffffffffffffffffffffffffffffffffffp-1022" }; for (int i = 0; i < inputs.length; i++) { double actual = Double.parseDouble(inputs[i]); double expected = Double.longBitsToDouble(expecteds[i]); String expectedString = "0x" + Long.toHexString(Double.doubleToLongBits(expected)); String actualString = "0x" + Long.toHexString(Double.doubleToLongBits(actual)); String errorMsg = i + "th input string is:<" + inputs[i] + ">.The expected result should be:<" + expectedString + ">, but was: <" + actualString + ">. "; assertEquals(errorMsg, expected, actual, 0.0D); } } /** * @tests java.lang.Double#shortValue() */ @TestTargetNew( level = TestLevel.COMPLETE, notes = "", method = "shortValue", args = {} ) public void test_shortValue() { // Test for method short java.lang.Double.shortValue() Double d = new Double(1923311.47712); assertEquals("Returned incorrect short value", 22767, d.shortValue()); } /** * @tests java.lang.Double#toString() */ @TestTargetNew( level = TestLevel.COMPLETE, notes = "", method = "toString", args = {} ) public void test_toString() { // Test for method java.lang.String java.lang.Double.toString() test_toString(1.7976931348623157E308, "1.7976931348623157E308"); test_toString(5.0E-4, "5.0E-4"); } /** * @tests java.lang.Double#toString(double) */ @TestTargetNew( level = TestLevel.COMPLETE, notes = "", method = "toString", args = {double.class} ) public void test_toStringD() { // Test for method java.lang.String java.lang.Double.toString(double) test_toString(1.7976931348623157E308, "1.7976931348623157E308"); test_toString(1.0 / 0.0, "Infinity"); test_toString(0.0 / 0.0, "NaN"); test_toString(-1.0 / 0.0, "-Infinity"); double d; d = Double.longBitsToDouble(0x470fffffffffffffL); test_toString(d, "2.0769187434139308E34"); d = Double.longBitsToDouble(0x4710000000000000L); test_toString(d, "2.076918743413931E34"); d = Double.longBitsToDouble(0x470000000000000aL); test_toString(d, "1.0384593717069678E34"); d = Double.longBitsToDouble(0x470000000000000bL); test_toString(d, "1.038459371706968E34"); d = Double.longBitsToDouble(0x4700000000000017L); test_toString(d, "1.0384593717069708E34"); d = Double.longBitsToDouble(0x4700000000000018L); test_toString(d, "1.038459371706971E34"); d = Double.longBitsToDouble(0x4700000000000024L); test_toString(d, "1.0384593717069738E34"); d = Double.longBitsToDouble(0x4700000000000025L); test_toString(d, "1.038459371706974E34"); d = Double.longBitsToDouble(0x4700000000000031L); test_toString(d, "1.0384593717069768E34"); d = Double.longBitsToDouble(0x4700000000000032L); test_toString(d, "1.038459371706977E34"); d = Double.longBitsToDouble(0x470000000000003eL); test_toString(d, "1.0384593717069798E34"); d = Double.longBitsToDouble(0x470000000000003fL); test_toString(d, "1.03845937170698E34"); d = Double.longBitsToDouble(0x7e00000000000003L); test_toString(d, "8.371160993642719E298"); d = Double.longBitsToDouble(0x7e00000000000004L); test_toString(d, "8.37116099364272E298"); d = Double.longBitsToDouble(0x7e00000000000008L); test_toString(d, "8.371160993642728E298"); d = Double.longBitsToDouble(0x7e00000000000009L); test_toString(d, "8.37116099364273E298"); d = Double.longBitsToDouble(0x7e00000000000013L); test_toString(d, "8.371160993642749E298"); d = Double.longBitsToDouble(0x7e00000000000014L); test_toString(d, "8.37116099364275E298"); d = Double.longBitsToDouble(0x7e00000000000023L); test_toString(d, "8.371160993642779E298"); d = Double.longBitsToDouble(0x7e00000000000024L); test_toString(d, "8.37116099364278E298"); d = Double.longBitsToDouble(0x7e0000000000002eL); test_toString(d, "8.371160993642799E298"); d = Double.longBitsToDouble(0x7e0000000000002fL); test_toString(d, "8.3711609936428E298"); d = Double.longBitsToDouble(0xda00000000000001L); test_toString(d, "-3.3846065602060736E125"); d = Double.longBitsToDouble(0xda00000000000002L); test_toString(d, "-3.384606560206074E125"); d = Double.longBitsToDouble(0xda00000000000005L); test_toString(d, "-3.3846065602060766E125"); d = Double.longBitsToDouble(0xda00000000000006L); test_toString(d, "-3.384606560206077E125"); d = Double.longBitsToDouble(0xda00000000000009L); test_toString(d, "-3.3846065602060796E125"); d = Double.longBitsToDouble(0xda0000000000000aL); test_toString(d, "-3.38460656020608E125"); d = Double.longBitsToDouble(0xda0000000000000dL); test_toString(d, "-3.3846065602060826E125"); d = Double.longBitsToDouble(0xda0000000000000eL); test_toString(d, "-3.384606560206083E125"); } /** * @tests java.lang.Double#valueOf(java.lang.String) */ @TestTargetNew( level = TestLevel.COMPLETE, notes = "", method = "valueOf", args = {java.lang.String.class} ) public void test_valueOfLjava_lang_String() { // Test for method java.lang.Double // java.lang.Double.valueOf(java.lang.String) assertTrue("Incorrect double returned", Math.abs(Double.valueOf("999999999999.999") .doubleValue() - 999999999999.999d) < 1); try { Double.valueOf(null); fail("Expected Double.valueOf(null) to throw NPE."); } catch (NullPointerException ex) { // expected } catch (Throwable ex) { fail("Expected Double.valueOf(null) to throw NPE not " + ex.getClass().getName()); } try { Double.valueOf(""); fail("Expected Double.valueOf(\"\") to throw NFE"); } catch (NumberFormatException e) { // expected } Double pi = Double.valueOf("3.141592654"); assertEquals(3.141592654, pi.doubleValue(), 0D); Double posZero = Double.valueOf("+0.0"); Double negZero = Double.valueOf("-0.0"); assertFalse("Doubletest0", posZero.equals(negZero)); // Tests for double values by name. Double expectedNaN = new Double(Double.NaN); Double posNaN = Double.valueOf("NaN"); assertTrue("Doubletest1", posNaN.equals(expectedNaN)); Double posNaNSigned = Double.valueOf("+NaN"); assertTrue("Doubletest2", posNaNSigned.equals(expectedNaN)); Double negNaNSigned = Double.valueOf("-NaN"); assertTrue("Doubletest3", negNaNSigned.equals(expectedNaN)); Double posInfinite = Double.valueOf("Infinity"); assertTrue("Doubletest4", posInfinite.equals(new Double(Double.POSITIVE_INFINITY))); Double posInfiniteSigned = Double.valueOf("+Infinity"); assertTrue("Doubletest5", posInfiniteSigned .equals(new Double(Double.POSITIVE_INFINITY))); Double negInfiniteSigned = Double.valueOf("-Infinity"); assertTrue("Doubletest6", negInfiniteSigned .equals(new Double(Double.NEGATIVE_INFINITY))); } /** * @tests java.lang.Double#compareTo(java.lang.Double) * @tests java.lang.Double#compare(double, double) */ @TestTargetNew( level = TestLevel.COMPLETE, notes = "", method = "compareTo", args = {java.lang.Double.class} ) public void test_compareToLjava_lang_Double() { // A selection of double values in ascending order. double[] values = new double[] { Double.NEGATIVE_INFINITY, -Double.MAX_VALUE, -2d, -Double.MIN_VALUE, -0d, 0d, Double.MIN_VALUE, 2d, Double.MAX_VALUE, Double.POSITIVE_INFINITY, Double.NaN }; for (int i = 0; i < values.length; i++) { double d1 = values[i]; // Test that each value compares equal to itself; and each object is // equal to another object like itself. assertTrue("Assert 0: compare() should be equal: " + d1, Double.compare(d1, d1) == 0); Double objDouble = new Double(d1); assertTrue("Assert 1: compareTo() should be equal: " + d1, objDouble .compareTo(objDouble) == 0); // Test that the Double-defined order is respected for (int j = i + 1; j < values.length; j++) { double d2 = values[j]; assertTrue("Assert 2: compare() " + d1 + " should be less " + d2, Double .compare(d1, d2) == -1); assertTrue("Assert 3: compare() " + d2 + " should be greater " + d1, Double .compare(d2, d1) == 1); Double D2 = new Double(d2); assertTrue("Assert 4: compareTo() " + d1 + " should be less " + d2, objDouble .compareTo(D2) == -1); assertTrue("Assert 5: compareTo() " + d2 + " should be greater " + d1, D2 .compareTo(objDouble) == 1); } } try { new Double(0.0D).compareTo(null); fail("No NPE"); } catch (NullPointerException e) { } } /** * @tests java.lang.Double#equals(java.lang.Object) */ @TestTargetNew( level = TestLevel.COMPLETE, notes = "", method = "equals", args = {java.lang.Object.class} ) public void test_equalsLjava_lang_Object() { Double d1 = new Double(87654321.12345d); Double d2 = new Double(87654321.12345d); Double d3 = new Double(0.0002f); assertTrue("Assert 0: Equality test failed", d1.equals(d2) && !(d1.equals(d3))); assertTrue("Assert 2: NaN should not be == Nan", Double.NaN != Double.NaN); assertTrue("Assert 3: NaN should not be == Nan", new Double(Double.NaN) .equals(new Double(Double.NaN))); assertTrue("Assert 4: -0d should be == 0d", 0d == -0d); assertTrue("Assert 5: -0d should not be equals() 0d", !new Double(0d) .equals(new Double(-0d))); Double dmax = new Double(Double.MAX_VALUE); Double dmax1 = new Double(Double.MAX_VALUE); assertTrue("Equality test failed", dmax.equals(dmax1) && !(dmax.equals(new Object()))); } /** * @tests java.lang.Double#toHexString(double) */ @TestTargetNew( level = TestLevel.COMPLETE, notes = "", method = "toHexString", args = {double.class} ) public void test_toHexStringF() { // the follow values come from the Double Javadoc/Spec assertEquals("0x0.0p0", Double.toHexString(0.0D)); assertEquals("-0x0.0p0", Double.toHexString(-0.0D)); assertEquals("0x1.0p0", Double.toHexString(1.0D)); assertEquals("-0x1.0p0", Double.toHexString(-1.0D)); assertEquals("0x1.0p1", Double.toHexString(2.0D)); assertEquals("0x1.8p1", Double.toHexString(3.0D)); assertEquals("0x1.0p-1", Double.toHexString(0.5D)); assertEquals("0x1.0p-2", Double.toHexString(0.25D)); assertEquals("0x1.fffffffffffffp1023", Double.toHexString(Double.MAX_VALUE)); assertEquals("0x0.0000000000001p-1022", Double.toHexString(Double.MIN_VALUE)); // test edge cases assertEquals("NaN", Double.toHexString(Double.NaN)); assertEquals("-Infinity", Double.toHexString(Double.NEGATIVE_INFINITY)); assertEquals("Infinity", Double.toHexString(Double.POSITIVE_INFINITY)); // test various numbers assertEquals("-0x1.da8p6", Double.toHexString(-118.625D)); assertEquals("0x1.2957874cccccdp23", Double.toHexString(9743299.65D)); assertEquals("0x1.2957874cccccdp23", Double.toHexString(9743299.65000D)); assertEquals("0x1.2957874cccf63p23", Double.toHexString(9743299.650001234D)); assertEquals("0x1.700d1061d3333p33", Double.toHexString(12349743299.65000D)); // test HARMONY-2132 assertEquals("0x1.01p10", Double.toHexString(0x1.01p10)); } /** * @tests java.lang.Double#valueOf(double) */ @TestTargetNew( level = TestLevel.COMPLETE, notes = "", method = "valueOf", args = {double.class} ) public void test_valueOfD() { assertEquals(new Double(Double.MIN_VALUE), Double.valueOf(Double.MIN_VALUE)); assertEquals(new Double(Double.MAX_VALUE), Double.valueOf(Double.MAX_VALUE)); assertEquals(new Double(0), Double.valueOf(0)); int s = -128; while (s < 128) { assertEquals(new Double(s), Double.valueOf(s)); assertEquals(new Double(s + 0.1D), Double.valueOf(s + 0.1D)); s++; } } }
apache-2.0
citywander/pinpoint
commons/src/main/java/com/navercorp/pinpoint/common/util/ThreadMXBeanUtils.java
4438
/* * Copyright 2014 NAVER Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.navercorp.pinpoint.common.util; import java.lang.management.ManagementFactory; import java.lang.management.ThreadInfo; import java.lang.management.ThreadMXBean; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * @author emeroad */ public final class ThreadMXBeanUtils { private static final ThreadMXBean THREAD_MX_BEAN = ManagementFactory.getThreadMXBean(); private static final boolean OBJECT_MONITOR_USAGE_SUPPORT; private static final boolean SYNCHRONIZER_USAGE_SUPPORT; // check support -> getWaitedTime(), getBlockedTime() private static final boolean CONTENTION_MONITORING_SUPPORT; private static final int DEFAULT_STACK_TRACE_MAX_DEPTH = 32; private ThreadMXBeanUtils() { } static { OBJECT_MONITOR_USAGE_SUPPORT = THREAD_MX_BEAN.isObjectMonitorUsageSupported(); SYNCHRONIZER_USAGE_SUPPORT = THREAD_MX_BEAN.isSynchronizerUsageSupported(); CONTENTION_MONITORING_SUPPORT = THREAD_MX_BEAN.isThreadContentionMonitoringSupported(); } // for test static String getOption() { final StringBuilder builder = new StringBuilder(); builder.append("ThreadMXBean SupportOption:{OBJECT_MONITOR_USAGE_SUPPORT="); builder.append(OBJECT_MONITOR_USAGE_SUPPORT); builder.append("}, {SYNCHRONIZER_USAGE_SUPPORT="); builder.append(SYNCHRONIZER_USAGE_SUPPORT); builder.append("}, {CONTENTION_MONITORING_SUPPORT="); builder.append(CONTENTION_MONITORING_SUPPORT); builder.append('}'); return builder.toString(); } public static ThreadInfo[] dumpAllThread() { // try { return THREAD_MX_BEAN.dumpAllThreads(OBJECT_MONITOR_USAGE_SUPPORT, SYNCHRONIZER_USAGE_SUPPORT); // ?? handle exception // } catch (java.lang.SecurityException se) { // log?? // return new ThreadInfo[]{}; // } catch (java.lang.UnsupportedOperationException ue) { // log?? // return new ThreadInfo[]{}; // } } public static ThreadInfo findThread(Thread thread) { return findThread(thread.getId()); } public static ThreadInfo findThread(Thread thread, int stackTraceMaxDepth) { return findThread(thread.getId(), stackTraceMaxDepth); } public static ThreadInfo findThread(long id) { return findThread(id, DEFAULT_STACK_TRACE_MAX_DEPTH); } public static ThreadInfo findThread(long id, int stackTraceMaxDepth) { if (stackTraceMaxDepth <= 0) { return THREAD_MX_BEAN.getThreadInfo(id); } else { return THREAD_MX_BEAN.getThreadInfo(id, stackTraceMaxDepth); } } public static List<ThreadInfo> findThread(String threadName) { Asserts.notNull(threadName, "threadName may not be null."); ThreadInfo[] threadInfos = dumpAllThread(); if (threadInfos == null) { return Collections.emptyList(); } ArrayList<ThreadInfo> threadInfoList = new ArrayList<ThreadInfo>(1); for (ThreadInfo threadInfo : threadInfos) { if (threadName.equals(threadInfo.getThreadName())) { threadInfoList.add(threadInfo); } } return threadInfoList; } public static boolean findThreadName(ThreadInfo[] threadInfos, String threadName) { if (threadInfos == null) { return false; } for (ThreadInfo threadInfo : threadInfos) { if (threadInfo.getThreadName().equals(threadName)) { return true; } } return false; } public static boolean findThreadName(String threadName) { final ThreadInfo[] threadInfos = dumpAllThread(); return findThreadName(threadInfos, threadName); } }
apache-2.0
ern/elasticsearch
modules/transport-netty4/src/test/java/org/elasticsearch/transport/netty4/Netty4UtilsTests.java
4296
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ package org.elasticsearch.transport.netty4; import io.netty.buffer.ByteBuf; import io.netty.buffer.CompositeByteBuf; import io.netty.buffer.Unpooled; import org.apache.lucene.util.BytesRef; import org.elasticsearch.common.breaker.CircuitBreaker; import org.elasticsearch.common.bytes.AbstractBytesReferenceTestCase; import org.elasticsearch.common.bytes.BytesArray; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.io.stream.ReleasableBytesStreamOutput; import org.elasticsearch.common.util.BigArrays; import org.elasticsearch.common.util.PageCacheRecycler; import org.elasticsearch.indices.breaker.NoneCircuitBreakerService; import org.elasticsearch.test.ESTestCase; import java.io.IOException; public class Netty4UtilsTests extends ESTestCase { private static final int PAGE_SIZE = PageCacheRecycler.BYTE_PAGE_SIZE; private final BigArrays bigarrays = new BigArrays(null, new NoneCircuitBreakerService(), CircuitBreaker.REQUEST); public void testToChannelBufferWithEmptyRef() throws IOException { ByteBuf buffer = Netty4Utils.toByteBuf(getRandomizedBytesReference(0)); assertSame(Unpooled.EMPTY_BUFFER, buffer); } public void testToChannelBufferWithSlice() throws IOException { BytesReference ref = getRandomizedBytesReference(randomIntBetween(1, 3 * PAGE_SIZE)); int sliceOffset = randomIntBetween(0, ref.length()); int sliceLength = randomIntBetween(ref.length() - sliceOffset, ref.length() - sliceOffset); BytesReference slice = ref.slice(sliceOffset, sliceLength); ByteBuf buffer = Netty4Utils.toByteBuf(slice); BytesReference bytesReference = Netty4Utils.toBytesReference(buffer); assertArrayEquals(BytesReference.toBytes(slice), BytesReference.toBytes(bytesReference)); } public void testToChannelBufferWithSliceAfter() throws IOException { BytesReference ref = getRandomizedBytesReference(randomIntBetween(1, 3 * PAGE_SIZE)); int sliceOffset = randomIntBetween(0, ref.length()); int sliceLength = randomIntBetween(ref.length() - sliceOffset, ref.length() - sliceOffset); ByteBuf buffer = Netty4Utils.toByteBuf(ref); BytesReference bytesReference = Netty4Utils.toBytesReference(buffer); assertArrayEquals(BytesReference.toBytes(ref.slice(sliceOffset, sliceLength)), BytesReference.toBytes(bytesReference.slice(sliceOffset, sliceLength))); } public void testToChannelBuffer() throws IOException { BytesReference ref = getRandomizedBytesReference(randomIntBetween(1, 3 * PAGE_SIZE)); ByteBuf buffer = Netty4Utils.toByteBuf(ref); BytesReference bytesReference = Netty4Utils.toBytesReference(buffer); if (AbstractBytesReferenceTestCase.getNumPages(ref) > 1) { // we gather the buffers into a channel buffer assertTrue(buffer instanceof CompositeByteBuf); } assertArrayEquals(BytesReference.toBytes(ref), BytesReference.toBytes(bytesReference)); } private BytesReference getRandomizedBytesReference(int length) throws IOException { // we know bytes stream output always creates a paged bytes reference, we use it to create randomized content ReleasableBytesStreamOutput out = new ReleasableBytesStreamOutput(length, bigarrays); for (int i = 0; i < length; i++) { out.writeByte((byte) random().nextInt(1 << 8)); } assertEquals(out.size(), length); BytesReference ref = out.bytes(); assertEquals(ref.length(), length); if (randomBoolean()) { return new BytesArray(ref.toBytesRef()); } else if (randomBoolean()) { BytesRef bytesRef = ref.toBytesRef(); return Netty4Utils.toBytesReference(Unpooled.wrappedBuffer(bytesRef.bytes, bytesRef.offset, bytesRef.length)); } else { return ref; } } }
apache-2.0
CChengz/dot.r
workspace/fits/spring-mvc-showcase/src/main/java/org/springframework/samples/mvc/validation/JavaBean.java
701
package org.springframework.samples.mvc.validation; import java.util.Date; import javax.validation.constraints.Future; import javax.validation.constraints.Max; import javax.validation.constraints.NotNull; import org.springframework.format.annotation.DateTimeFormat; import org.springframework.format.annotation.DateTimeFormat.ISO; public class JavaBean { @NotNull @Max(5) private Integer number; @NotNull @Future @DateTimeFormat(iso=ISO.DATE) private Date date; public Integer getNumber() { return number; } public void setNumber(Integer number) { this.number = number; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } }
apache-2.0
erguotou520/weex-uikit
platforms/android/WeexSDK/src/main/java/com/taobao/weex/utils/WXResourceUtils.java
27032
/** * * Apache License * Version 2.0, January 2004 * http://www.apache.org/licenses/ * * TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION * * 1. Definitions. * * "License" shall mean the terms and conditions for use, reproduction, * and distribution as defined by Sections 1 through 9 of this document. * * "Licensor" shall mean the copyright owner or entity authorized by * the copyright owner that is granting the License. * * "Legal Entity" shall mean the union of the acting entity and all * other entities that control, are controlled by, or are under common * control with that entity. For the purposes of this definition, * "control" means (i) the power, direct or indirect, to cause the * direction or management of such entity, whether by contract or * otherwise, or (ii) ownership of fifty percent (50%) or more of the * outstanding shares, or (iii) beneficial ownership of such entity. * * "You" (or "Your") shall mean an individual or Legal Entity * exercising permissions granted by this License. * * "Source" form shall mean the preferred form for making modifications, * including but not limited to software source code, documentation * source, and configuration files. * * "Object" form shall mean any form resulting from mechanical * transformation or translation of a Source form, including but * not limited to compiled object code, generated documentation, * and conversions to other media types. * * "Work" shall mean the work of authorship, whether in Source or * Object form, made available under the License, as indicated by a * copyright notice that is included in or attached to the work * (an example is provided in the Appendix below). * * "Derivative Works" shall mean any work, whether in Source or Object * form, that is based on (or derived from) the Work and for which the * editorial revisions, annotations, elaborations, or other modifications * represent, as a whole, an original work of authorship. For the purposes * of this License, Derivative Works shall not include works that remain * separable from, or merely link (or bind by name) to the interfaces of, * the Work and Derivative Works thereof. * * "Contribution" shall mean any work of authorship, including * the original version of the Work and any modifications or additions * to that Work or Derivative Works thereof, that is intentionally * submitted to Licensor for inclusion in the Work by the copyright owner * or by an individual or Legal Entity authorized to submit on behalf of * the copyright owner. For the purposes of this definition, "submitted" * means any form of electronic, verbal, or written communication sent * to the Licensor or its representatives, including but not limited to * communication on electronic mailing lists, source code control systems, * and issue tracking systems that are managed by, or on behalf of, the * Licensor for the purpose of discussing and improving the Work, but * excluding communication that is conspicuously marked or otherwise * designated in writing by the copyright owner as "Not a Contribution." * * "Contributor" shall mean Licensor and any individual or Legal Entity * on behalf of whom a Contribution has been received by Licensor and * subsequently incorporated within the Work. * * 2. Grant of Copyright License. Subject to the terms and conditions of * this License, each Contributor hereby grants to You a perpetual, * worldwide, non-exclusive, no-charge, royalty-free, irrevocable * copyright license to reproduce, prepare Derivative Works of, * publicly display, publicly perform, sublicense, and distribute the * Work and such Derivative Works in Source or Object form. * * 3. Grant of Patent License. Subject to the terms and conditions of * this License, each Contributor hereby grants to You a perpetual, * worldwide, non-exclusive, no-charge, royalty-free, irrevocable * (except as stated in this section) patent license to make, have made, * use, offer to sell, sell, import, and otherwise transfer the Work, * where such license applies only to those patent claims licensable * by such Contributor that are necessarily infringed by their * Contribution(s) alone or by combination of their Contribution(s) * with the Work to which such Contribution(s) was submitted. If You * institute patent litigation against any entity (including a * cross-claim or counterclaim in a lawsuit) alleging that the Work * or a Contribution incorporated within the Work constitutes direct * or contributory patent infringement, then any patent licenses * granted to You under this License for that Work shall terminate * as of the date such litigation is filed. * * 4. Redistribution. You may reproduce and distribute copies of the * Work or Derivative Works thereof in any medium, with or without * modifications, and in Source or Object form, provided that You * meet the following conditions: * * (a) You must give any other recipients of the Work or * Derivative Works a copy of this License; and * * (b) You must cause any modified files to carry prominent notices * stating that You changed the files; and * * (c) You must retain, in the Source form of any Derivative Works * that You distribute, all copyright, patent, trademark, and * attribution notices from the Source form of the Work, * excluding those notices that do not pertain to any part of * the Derivative Works; and * * (d) If the Work includes a "NOTICE" text file as part of its * distribution, then any Derivative Works that You distribute must * include a readable copy of the attribution notices contained * within such NOTICE file, excluding those notices that do not * pertain to any part of the Derivative Works, in at least one * of the following places: within a NOTICE text file distributed * as part of the Derivative Works; within the Source form or * documentation, if provided along with the Derivative Works; or, * within a display generated by the Derivative Works, if and * wherever such third-party notices normally appear. The contents * of the NOTICE file are for informational purposes only and * do not modify the License. You may add Your own attribution * notices within Derivative Works that You distribute, alongside * or as an addendum to the NOTICE text from the Work, provided * that such additional attribution notices cannot be construed * as modifying the License. * * You may add Your own copyright statement to Your modifications and * may provide additional or different license terms and conditions * for use, reproduction, or distribution of Your modifications, or * for any such Derivative Works as a whole, provided Your use, * reproduction, and distribution of the Work otherwise complies with * the conditions stated in this License. * * 5. Submission of Contributions. Unless You explicitly state otherwise, * any Contribution intentionally submitted for inclusion in the Work * by You to the Licensor shall be under the terms and conditions of * this License, without any additional terms or conditions. * Notwithstanding the above, nothing herein shall supersede or modify * the terms of any separate license agreement you may have executed * with Licensor regarding such Contributions. * * 6. Trademarks. This License does not grant permission to use the trade * names, trademarks, service marks, or product names of the Licensor, * except as required for reasonable and customary use in describing the * origin of the Work and reproducing the content of the NOTICE file. * * 7. Disclaimer of Warranty. Unless required by applicable law or * agreed to in writing, Licensor provides the Work (and each * Contributor provides its Contributions) on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied, including, without limitation, any warranties or conditions * of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A * PARTICULAR PURPOSE. You are solely responsible for determining the * appropriateness of using or redistributing the Work and assume any * risks associated with Your exercise of permissions under this License. * * 8. Limitation of Liability. In no event and under no legal theory, * whether in tort (including negligence), contract, or otherwise, * unless required by applicable law (such as deliberate and grossly * negligent acts) or agreed to in writing, shall any Contributor be * liable to You for damages, including any direct, indirect, special, * incidental, or consequential damages of any character arising as a * result of this License or out of the use or inability to use the * Work (including but not limited to damages for loss of goodwill, * work stoppage, computer failure or malfunction, or any and all * other commercial damages or losses), even if such Contributor * has been advised of the possibility of such damages. * * 9. Accepting Warranty or Additional Liability. While redistributing * the Work or Derivative Works thereof, You may choose to offer, * and charge a fee for, acceptance of support, warranty, indemnity, * or other liability obligations and/or rights consistent with this * License. However, in accepting such obligations, You may act only * on Your own behalf and on Your sole responsibility, not on behalf * of any other Contributor, and only if You agree to indemnify, * defend, and hold each Contributor harmless for any liability * incurred by, or claims asserted against, such Contributor by reason * of your accepting any such warranty or additional liability. * * END OF TERMS AND CONDITIONS * * APPENDIX: How to apply the Apache License to your work. * * To apply the Apache License to your work, attach the following * boilerplate notice, with the fields enclosed by brackets "[]" * replaced with your own identifying information. (Don't include * the brackets!) The text should be enclosed in the appropriate * comment syntax for the file format. We also recommend that a * file or class name and description of purpose be included on the * same "printed page" as the copyright notice for easier * identification within third-party archives. * * Copyright 2016 Alibaba Group * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.taobao.weex.utils; import android.graphics.Color; import android.graphics.LinearGradient; import android.graphics.Shader; import android.support.annotation.NonNull; import android.text.TextUtils; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.StringTokenizer; /** * Class for parse color */ public class WXResourceUtils { private final static Map<String, Integer> colorMap = new HashMap<>(); private final static int RGB_SIZE = 3; private final static int RGBA_SIZE = 4; private final static int HEX = 16; private final static int COLOR_RANGE = 255; private final static String RGB = "rgb"; private final static String RGBA = "rgba"; private final static SingleFunctionParser.FlatMapper<Integer> FUNCTIONAL_RGB_MAPPER = new SingleFunctionParser.FlatMapper<Integer>() { @Override public Integer map(String raw) { int color = WXUtils.parseUnitOrPercent(raw, COLOR_RANGE); if (color < 0) { color = 0; } else if (color > COLOR_RANGE) { color = COLOR_RANGE; } return color; } }; private final static SingleFunctionParser.NonUniformMapper<Number> FUNCTIONAL_RGBA_MAPPER = new SingleFunctionParser.NonUniformMapper<Number>() { @Override public List<Number> map(List<String> raw) { List<Number> result = new ArrayList<>(RGBA_SIZE); int i, color; for (i = 0; i < RGB_SIZE; i++) { color = WXUtils.parseUnitOrPercent(raw.get(i), COLOR_RANGE); if (color < 0) { color = 0; } else if (color > COLOR_RANGE) { color = COLOR_RANGE; } result.add(color); } result.add(Float.valueOf(raw.get(i))); return result; } }; static { colorMap.put("aliceblue", 0XFFF0F8FF); colorMap.put("antiquewhite", 0XFFFAEBD7); colorMap.put("aqua", 0XFF00FFFF); colorMap.put("aquamarine", 0XFF7FFFD4); colorMap.put("azure", 0XFFF0FFFF); colorMap.put("beige", 0XFFF5F5DC); colorMap.put("bisque", 0XFFFFE4C4); colorMap.put("black", 0XFF000000); colorMap.put("blanchedalmond", 0XFFFFEBCD); colorMap.put("blue", 0XFF0000FF); colorMap.put("blueviolet", 0XFF8A2BE2); colorMap.put("brown", 0XFFA52A2A); colorMap.put("burlywood", 0XFFDEB887); colorMap.put("cadetblue", 0XFF5F9EA0); colorMap.put("chartreuse", 0XFF7FFF00); colorMap.put("chocolate", 0XFFD2691E); colorMap.put("coral", 0XFFFF7F50); colorMap.put("cornflowerblue", 0XFF6495ED); colorMap.put("cornsilk", 0XFFFFF8DC); colorMap.put("crimson", 0XFFDC143C); colorMap.put("cyan", 0XFF00FFFF); colorMap.put("darkblue", 0XFF00008B); colorMap.put("darkcyan", 0XFF008B8B); colorMap.put("darkgoldenrod", 0XFFB8860B); colorMap.put("darkgray", 0XFFA9A9A9); colorMap.put("darkgreen", 0XFF006400); colorMap.put("darkkhaki", 0XFFBDB76B); colorMap.put("darkmagenta", 0XFF8B008B); colorMap.put("darkolivegreen", 0XFF556B2F); colorMap.put("darkorange", 0XFFFF8C00); colorMap.put("darkorchid", 0XFF9932CC); colorMap.put("darkred", 0XFF8B0000); colorMap.put("darksalmon", 0XFFE9967A); colorMap.put("darkseagreen", 0XFF8FBC8F); colorMap.put("darkslateblue", 0XFF483D8B); colorMap.put("darkslategray", 0XFF2F4F4F); colorMap.put("darkslategrey", 0XFF2F4F4F); colorMap.put("darkturquoise", 0XFF00CED1); colorMap.put("darkviolet", 0XFF9400D3); colorMap.put("deeppink", 0XFFFF1493); colorMap.put("deepskyblue", 0XFF00BFFF); colorMap.put("dimgray", 0XFF696969); colorMap.put("dimgrey", 0XFF696969); colorMap.put("dodgerblue", 0XFF1E90FF); colorMap.put("firebrick", 0XFFB22222); colorMap.put("floralwhite", 0XFFFFFAF0); colorMap.put("forestgreen", 0XFF228B22); colorMap.put("fuchsia", 0XFFFF00FF); colorMap.put("gainsboro", 0XFFDCDCDC); colorMap.put("ghostwhite", 0XFFF8F8FF); colorMap.put("gold", 0XFFFFD700); colorMap.put("goldenrod", 0XFFDAA520); colorMap.put("gray", 0XFF808080); colorMap.put("grey", 0XFF808080); colorMap.put("green", 0XFF008000); colorMap.put("greenyellow", 0XFFADFF2F); colorMap.put("honeydew", 0XFFF0FFF0); colorMap.put("hotpink", 0XFFFF69B4); colorMap.put("indianred", 0XFFCD5C5C); colorMap.put("indigo", 0XFF4B0082); colorMap.put("ivory", 0XFFFFFFF0); colorMap.put("khaki", 0XFFF0E68C); colorMap.put("lavender", 0XFFE6E6FA); colorMap.put("lavenderblush", 0XFFFFF0F5); colorMap.put("lawngreen", 0XFF7CFC00); colorMap.put("lemonchiffon", 0XFFFFFACD); colorMap.put("lightblue", 0XFFADD8E6); colorMap.put("lightcoral", 0XFFF08080); colorMap.put("lightcyan", 0XFFE0FFFF); colorMap.put("lightgoldenrodyellow", 0XFFFAFAD2); colorMap.put("lightgray", 0XFFD3D3D3); colorMap.put("lightgrey", 0XFFD3D3D3); colorMap.put("lightgreen", 0XFF90EE90); colorMap.put("lightpink", 0XFFFFB6C1); colorMap.put("lightsalmon", 0XFFFFA07A); colorMap.put("lightseagreen", 0XFF20B2AA); colorMap.put("lightskyblue", 0XFF87CEFA); colorMap.put("lightslategray", 0XFF778899); colorMap.put("lightslategrey", 0XFF778899); colorMap.put("lightsteelblue", 0XFFB0C4DE); colorMap.put("lightyellow", 0XFFFFFFE0); colorMap.put("lime", 0XFF00FF00); colorMap.put("limegreen", 0XFF32CD32); colorMap.put("linen", 0XFFFAF0E6); colorMap.put("magenta", 0XFFFF00FF); colorMap.put("maroon", 0XFF800000); colorMap.put("mediumaquamarine", 0XFF66CDAA); colorMap.put("mediumblue", 0XFF0000CD); colorMap.put("mediumorchid", 0XFFBA55D3); colorMap.put("mediumpurple", 0XFF9370DB); colorMap.put("mediumseagreen", 0XFF3CB371); colorMap.put("mediumslateblue", 0XFF7B68EE); colorMap.put("mediumspringgreen", 0XFF00FA9A); colorMap.put("mediumturquoise", 0XFF48D1CC); colorMap.put("mediumvioletred", 0XFFC71585); colorMap.put("midnightblue", 0XFF191970); colorMap.put("mintcream", 0XFFF5FFFA); colorMap.put("mistyrose", 0XFFFFE4E1); colorMap.put("moccasin", 0XFFFFE4B5); colorMap.put("navajowhite", 0XFFFFDEAD); colorMap.put("navy", 0XFF000080); colorMap.put("oldlace", 0XFFFDF5E6); colorMap.put("olive", 0XFF808000); colorMap.put("olivedrab", 0XFF6B8E23); colorMap.put("orange", 0XFFFFA500); colorMap.put("orangered", 0XFFFF4500); colorMap.put("orchid", 0XFFDA70D6); colorMap.put("palegoldenrod", 0XFFEEE8AA); colorMap.put("palegreen", 0XFF98FB98); colorMap.put("paleturquoise", 0XFFAFEEEE); colorMap.put("palevioletred", 0XFFDB7093); colorMap.put("papayawhip", 0XFFFFEFD5); colorMap.put("peachpuff", 0XFFFFDAB9); colorMap.put("peru", 0XFFCD853F); colorMap.put("pink", 0XFFFFC0CB); colorMap.put("plum", 0XFFDDA0DD); colorMap.put("powderblue", 0XFFB0E0E6); colorMap.put("purple", 0XFF800080); colorMap.put("rebeccapurple", 0XFF663399); colorMap.put("red", 0XFFFF0000); colorMap.put("rosybrown", 0XFFBC8F8F); colorMap.put("royalblue", 0XFF4169E1); colorMap.put("saddlebrown", 0XFF8B4513); colorMap.put("salmon", 0XFFFA8072); colorMap.put("sandybrown", 0XFFF4A460); colorMap.put("seagreen", 0XFF2E8B57); colorMap.put("seashell", 0XFFFFF5EE); colorMap.put("sienna", 0XFFA0522D); colorMap.put("silver", 0XFFC0C0C0); colorMap.put("skyblue", 0XFF87CEEB); colorMap.put("slateblue", 0XFF6A5ACD); colorMap.put("slategray", 0XFF708090); colorMap.put("slategrey", 0XFF708090); colorMap.put("snow", 0XFFFFFAFA); colorMap.put("springgreen", 0XFF00FF7F); colorMap.put("steelblue", 0XFF4682B4); colorMap.put("tan", 0XFFD2B48C); colorMap.put("teal", 0XFF008080); colorMap.put("thistle", 0XFFD8BFD8); colorMap.put("tomato", 0XFFFF6347); colorMap.put("turquoise", 0XFF40E0D0); colorMap.put("violet", 0XFFEE82EE); colorMap.put("wheat", 0XFFF5DEB3); colorMap.put("white", 0XFFFFFFFF); colorMap.put("whitesmoke", 0XFFF5F5F5); colorMap.put("yellow", 0XFFFFFF00); colorMap.put("yellowgreen", 0XFF9ACD32); colorMap.put("transparent", 0x00000000); } public static int getColor(String color) { return getColor(color, Integer.MIN_VALUE); } public static int getColor(String color, int defaultColor) { if (TextUtils.isEmpty(color)) { return defaultColor; } color = color.trim(); //remove non visible codes int resultColor = defaultColor; try { ColorConvertHandler[] handlers = ColorConvertHandler.values(); for (ColorConvertHandler handler : handlers) { try { resultColor = handler.handle(color); break; } catch (IllegalArgumentException e) { WXLogUtils.v("Color", "Color convert fails"); } } } catch (Exception e) { WXLogUtils.e("WXResourceUtils getColor failed: " + color); } return resultColor; } /** * Assembly gradients * @param image gradient values contains direction、colors * @param width component width * @param height component height * @return gradient shader */ public static Shader getShader(String image, float width, float height) { List<String> valueList = parseGradientValues(image); if (valueList != null && valueList.size() == 3) { float[] points = parseGradientDirection(valueList.get(0), width, height); Shader shader = new LinearGradient(points[0], points[1], points[2], points[3], getColor(valueList.get(1), Color.WHITE), getColor(valueList.get(2), Color.WHITE), Shader.TileMode.REPEAT); return shader; } return null; } /** * parse gradient values contains direction、colors * @param image gradient values * @return split values by comma */ @NonNull private static List<String> parseGradientValues(String image) { if (TextUtils.isEmpty(image)) { return null; } image.trim(); if(image.startsWith("linear-gradient")){ String valueStr = image.substring(image.indexOf("(") + 1, image.lastIndexOf(")")); StringTokenizer tokenizer = new StringTokenizer(valueStr, ","); List<String> values = new ArrayList<>(); String temp = null; while (tokenizer.hasMoreTokens()) { String token = tokenizer.nextToken(); if (token.contains("(")) { temp = token + ","; continue; } if (token.contains(")")) { temp += token; values.add(temp); temp = null; continue; } if (temp != null) { temp += (token + ","); continue; } values.add(token); } return values; } return null; } /** * parse gradient direction * @param direction gradient direction * @param width component width * @param height component height * @return gradient points */ private static float[] parseGradientDirection(String direction, float width, float height) { int x1 = 0, y1 = 1, x2 = 2, y2 = 3; float[] points = {0, 0, 0, 0}; if (!TextUtils.isEmpty(direction)) { direction = direction.replaceAll("\\s*", "").toLowerCase(); } switch (direction) { //to right case "toright": points[x2] = width; break; //to left case "toleft": points[x1] = width; break; //to bottom case "tobottom": points[y2] = height; break; //to top case "totop": points[y1] = height; break; //to bottom right case "tobottomright": points[x2] = width; points[y2] = height; break; //to top left case "totopleft": points[x1] = width; points[y1] = height; break; } return points; } enum ColorConvertHandler { NAMED_COLOR_HANDLER { @Override int handle(String rawColor) { try { return colorMap.get(rawColor); } catch (RuntimeException e) { throw new IllegalArgumentException(e); } } }, RGB_HANDLER { @Override int handle(String rawColor) { try { if (rawColor.length() == 4) { //#eee, #333 int r, g, b; r = Integer.parseInt(rawColor.substring(1, 2), HEX); g = Integer.parseInt(rawColor.substring(2, 3), HEX); b = Integer.parseInt(rawColor.substring(3, 4), HEX); return Color.rgb(r + (r << 4), g + (g << 4), b + (b << 4)); } else if (rawColor.length() == 7 || rawColor.length() == 9) { //#eeeeee, #333333 return Color.parseColor(rawColor); } else { throw new IllegalArgumentException("ColorConvertHandler invalid color: " + rawColor); } } catch (RuntimeException e) { throw new IllegalArgumentException(e); } } }, FUNCTIONAL_RGB_HANDLER { @Override int handle(String rawColor) { try { SingleFunctionParser<Integer> functionParser = new SingleFunctionParser<>(rawColor, FUNCTIONAL_RGB_MAPPER); List<Integer> rgb = functionParser.parse(RGB); if (rgb.size() == RGB_SIZE) { return Color.rgb(rgb.get(0), rgb.get(1), rgb.get(2)); } else { throw new IllegalArgumentException("Conversion of functional RGB fails"); } } catch (RuntimeException e) { throw new IllegalArgumentException(e); } } }, FUNCTIONAL_RGBA_HANDLER { @Override int handle(String rawColor) { try { SingleFunctionParser<Number> functionParser = new SingleFunctionParser<>(rawColor, FUNCTIONAL_RGBA_MAPPER); List<Number> rgba = functionParser.parse(RGBA); if (rgba.size() == RGBA_SIZE) { return Color.argb( parseAlpha(rgba.get(3).floatValue()), rgba.get(0).intValue(), rgba.get(1).intValue(), rgba.get(2).intValue()); } else { throw new IllegalArgumentException("Conversion of functional RGBA fails"); } } catch (RuntimeException e) { throw new IllegalArgumentException(e); } } }; /** * Parse color to #RRGGBB or #AARRGGBB. The parsing algorithm depends on sub-class. * * @param rawColor color, maybe functional RGB(RGBA), #RGB, keywords color or transparent * @return #RRGGBB or #AARRGGBB */ abstract int handle(String rawColor) throws IllegalArgumentException; /** * Parse alpha gradient of color from range 0-1 to range 0-255 * * @param alpha the alpha value, in range 0-1 * @return the alpha value, in range 0-255 */ private static int parseAlpha(float alpha) { return (int) (alpha * COLOR_RANGE); } } }
mit
rokn/Count_Words_2015
testing/openjdk2/jdk/src/windows/classes/java/net/DualStackPlainDatagramSocketImpl.java
10133
/* * Copyright (c) 2007, 2013, 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 java.net; import java.io.IOException; import sun.misc.SharedSecrets; import sun.misc.JavaIOFileDescriptorAccess; /** * This class defines the plain DatagramSocketImpl that is used on * Windows platforms greater than or equal to Windows Vista. These * platforms have a dual layer TCP/IP stack and can handle both IPv4 * and IPV6 through a single file descriptor. * <p> * Note: Multicasting on a dual layer TCP/IP stack is always done with * TwoStacksPlainDatagramSocketImpl. This is to overcome the lack * of behavior defined for multicasting over a dual layer socket by the RFC. * * @author Chris Hegarty */ class DualStackPlainDatagramSocketImpl extends AbstractPlainDatagramSocketImpl { static JavaIOFileDescriptorAccess fdAccess = SharedSecrets.getJavaIOFileDescriptorAccess(); // true if this socket is exclusively bound private final boolean exclusiveBind; /* * Set to true if SO_REUSEADDR is set after the socket is bound to * indicate SO_REUSEADDR is being emulated */ private boolean reuseAddressEmulated; // emulates SO_REUSEADDR when exclusiveBind is true and socket is bound private boolean isReuseAddress; DualStackPlainDatagramSocketImpl(boolean exclBind) { exclusiveBind = exclBind; } protected void datagramSocketCreate() throws SocketException { if (fd == null) throw new SocketException("Socket closed"); int newfd = socketCreate(false /* v6Only */); fdAccess.set(fd, newfd); } protected synchronized void bind0(int lport, InetAddress laddr) throws SocketException { int nativefd = checkAndReturnNativeFD(); if (laddr == null) throw new NullPointerException("argument address"); socketBind(nativefd, laddr, lport, exclusiveBind); if (lport == 0) { localPort = socketLocalPort(nativefd); } else { localPort = lport; } } protected synchronized int peek(InetAddress address) throws IOException { int nativefd = checkAndReturnNativeFD(); if (address == null) throw new NullPointerException("Null address in peek()"); // Use peekData() DatagramPacket peekPacket = new DatagramPacket(new byte[1], 1); int peekPort = peekData(peekPacket); address = peekPacket.getAddress(); return peekPort; } protected synchronized int peekData(DatagramPacket p) throws IOException { int nativefd = checkAndReturnNativeFD(); if (p == null) throw new NullPointerException("packet"); if (p.getData() == null) throw new NullPointerException("packet buffer"); return socketReceiveOrPeekData(nativefd, p, timeout, connected, true /*peek*/); } protected synchronized void receive0(DatagramPacket p) throws IOException { int nativefd = checkAndReturnNativeFD(); if (p == null) throw new NullPointerException("packet"); if (p.getData() == null) throw new NullPointerException("packet buffer"); socketReceiveOrPeekData(nativefd, p, timeout, connected, false /*receive*/); } protected void send(DatagramPacket p) throws IOException { int nativefd = checkAndReturnNativeFD(); if (p == null) throw new NullPointerException("null packet"); if (p.getAddress() == null ||p.getData() ==null) throw new NullPointerException("null address || null buffer"); socketSend(nativefd, p.getData(), p.getOffset(), p.getLength(), p.getAddress(), p.getPort(), connected); } protected void connect0(InetAddress address, int port) throws SocketException { int nativefd = checkAndReturnNativeFD(); if (address == null) throw new NullPointerException("address"); socketConnect(nativefd, address, port); } protected void disconnect0(int family /*unused*/) { if (fd == null || !fd.valid()) return; // disconnect doesn't throw any exceptions socketDisconnect(fdAccess.get(fd)); } protected void datagramSocketClose() { if (fd == null || !fd.valid()) return; // close doesn't throw any exceptions socketClose(fdAccess.get(fd)); fdAccess.set(fd, -1); } @SuppressWarnings("fallthrough") protected void socketSetOption(int opt, Object val) throws SocketException { int nativefd = checkAndReturnNativeFD(); int optionValue = 0; switch(opt) { case IP_TOS : case SO_RCVBUF : case SO_SNDBUF : optionValue = ((Integer)val).intValue(); break; case SO_REUSEADDR : if (exclusiveBind && localPort != 0) { // socket already bound, emulate SO_REUSEADDR reuseAddressEmulated = true; isReuseAddress = (Boolean)val; return; } //Intentional fallthrough case SO_BROADCAST : optionValue = ((Boolean)val).booleanValue() ? 1 : 0; break; default: /* shouldn't get here */ throw new SocketException("Option not supported"); } socketSetIntOption(nativefd, opt, optionValue); } protected Object socketGetOption(int opt) throws SocketException { int nativefd = checkAndReturnNativeFD(); // SO_BINDADDR is not a socket option. if (opt == SO_BINDADDR) { return socketLocalAddress(nativefd); } if (opt == SO_REUSEADDR && reuseAddressEmulated) return isReuseAddress; int value = socketGetIntOption(nativefd, opt); Object returnValue = null; switch (opt) { case SO_REUSEADDR : case SO_BROADCAST : returnValue = (value == 0) ? Boolean.FALSE : Boolean.TRUE; break; case IP_TOS : case SO_RCVBUF : case SO_SNDBUF : returnValue = new Integer(value); break; default: /* shouldn't get here */ throw new SocketException("Option not supported"); } return returnValue; } /* Multicast specific methods. * Multicasting on a dual layer TCP/IP stack is always done with * TwoStacksPlainDatagramSocketImpl. This is to overcome the lack * of behavior defined for multicasting over a dual layer socket by the RFC. */ protected void join(InetAddress inetaddr, NetworkInterface netIf) throws IOException { throw new IOException("Method not implemented!"); } protected void leave(InetAddress inetaddr, NetworkInterface netIf) throws IOException { throw new IOException("Method not implemented!"); } protected void setTimeToLive(int ttl) throws IOException { throw new IOException("Method not implemented!"); } protected int getTimeToLive() throws IOException { throw new IOException("Method not implemented!"); } @Deprecated protected void setTTL(byte ttl) throws IOException { throw new IOException("Method not implemented!"); } @Deprecated protected byte getTTL() throws IOException { throw new IOException("Method not implemented!"); } /* END Multicast specific methods */ private int checkAndReturnNativeFD() throws SocketException { if (fd == null || !fd.valid()) throw new SocketException("Socket closed"); return fdAccess.get(fd); } /* Native methods */ private static native void initIDs(); private static native int socketCreate(boolean v6Only); private static native void socketBind(int fd, InetAddress localAddress, int localport, boolean exclBind) throws SocketException; private static native void socketConnect(int fd, InetAddress address, int port) throws SocketException; private static native void socketDisconnect(int fd); private static native void socketClose(int fd); private static native int socketLocalPort(int fd) throws SocketException; private static native Object socketLocalAddress(int fd) throws SocketException; private static native int socketReceiveOrPeekData(int fd, DatagramPacket packet, int timeout, boolean connected, boolean peek) throws IOException; private static native void socketSend(int fd, byte[] data, int offset, int length, InetAddress address, int port, boolean connected) throws IOException; private static native void socketSetIntOption(int fd, int cmd, int optionValue) throws SocketException; private static native int socketGetIntOption(int fd, int cmd) throws SocketException; }
mit
codeck/XChange
xchange-core/src/main/java/com/xeiam/xchange/dto/trade/UserTrades.java
499
package com.xeiam.xchange.dto.trade; import java.util.List; import com.xeiam.xchange.dto.marketdata.Trades; public class UserTrades extends Trades { public UserTrades(List<UserTrade> trades, TradeSortType tradeSortType) { super((List) trades, tradeSortType); } public UserTrades(List<UserTrade> trades, long lastID, TradeSortType tradeSortType) { super((List) trades, lastID, tradeSortType); } public List<UserTrade> getUserTrades() { return (List) getTrades(); } }
mit
andrewmcvearry/mille-bean
lwjgl/src/generated/org/lwjgl/opencl/CL10.java
105972
/* MACHINE GENERATED FILE, DO NOT EDIT */ package org.lwjgl.opencl; import org.lwjgl.*; import java.nio.*; /** * The core OpenCL 1.0 API */ public final class CL10 { /** * Error Codes */ public static final int CL_SUCCESS = 0x0, CL_DEVICE_NOT_FOUND = 0xFFFFFFFF, CL_DEVICE_NOT_AVAILABLE = 0xFFFFFFFE, CL_COMPILER_NOT_AVAILABLE = 0xFFFFFFFD, CL_MEM_OBJECT_ALLOCATION_FAILURE = 0xFFFFFFFC, CL_OUT_OF_RESOURCES = 0xFFFFFFFB, CL_OUT_OF_HOST_MEMORY = 0xFFFFFFFA, CL_PROFILING_INFO_NOT_AVAILABLE = 0xFFFFFFF9, CL_MEM_COPY_OVERLAP = 0xFFFFFFF8, CL_IMAGE_FORMAT_MISMATCH = 0xFFFFFFF7, CL_IMAGE_FORMAT_NOT_SUPPORTED = 0xFFFFFFF6, CL_BUILD_PROGRAM_FAILURE = 0xFFFFFFF5, CL_MAP_FAILURE = 0xFFFFFFF4, CL_INVALID_VALUE = 0xFFFFFFE2, CL_INVALID_DEVICE_TYPE = 0xFFFFFFE1, CL_INVALID_PLATFORM = 0xFFFFFFE0, CL_INVALID_DEVICE = 0xFFFFFFDF, CL_INVALID_CONTEXT = 0xFFFFFFDE, CL_INVALID_QUEUE_PROPERTIES = 0xFFFFFFDD, CL_INVALID_COMMAND_QUEUE = 0xFFFFFFDC, CL_INVALID_HOST_PTR = 0xFFFFFFDB, CL_INVALID_MEM_OBJECT = 0xFFFFFFDA, CL_INVALID_IMAGE_FORMAT_DESCRIPTOR = 0xFFFFFFD9, CL_INVALID_IMAGE_SIZE = 0xFFFFFFD8, CL_INVALID_SAMPLER = 0xFFFFFFD7, CL_INVALID_BINARY = 0xFFFFFFD6, CL_INVALID_BUILD_OPTIONS = 0xFFFFFFD5, CL_INVALID_PROGRAM = 0xFFFFFFD4, CL_INVALID_PROGRAM_EXECUTABLE = 0xFFFFFFD3, CL_INVALID_KERNEL_NAME = 0xFFFFFFD2, CL_INVALID_KERNEL_DEFINITION = 0xFFFFFFD1, CL_INVALID_KERNEL = 0xFFFFFFD0, CL_INVALID_ARG_INDEX = 0xFFFFFFCF, CL_INVALID_ARG_VALUE = 0xFFFFFFCE, CL_INVALID_ARG_SIZE = 0xFFFFFFCD, CL_INVALID_KERNEL_ARGS = 0xFFFFFFCC, CL_INVALID_WORK_DIMENSION = 0xFFFFFFCB, CL_INVALID_WORK_GROUP_SIZE = 0xFFFFFFCA, CL_INVALID_WORK_ITEM_SIZE = 0xFFFFFFC9, CL_INVALID_GLOBAL_OFFSET = 0xFFFFFFC8, CL_INVALID_EVENT_WAIT_LIST = 0xFFFFFFC7, CL_INVALID_EVENT = 0xFFFFFFC6, CL_INVALID_OPERATION = 0xFFFFFFC5, CL_INVALID_GL_OBJECT = 0xFFFFFFC4, CL_INVALID_BUFFER_SIZE = 0xFFFFFFC3, CL_INVALID_MIP_LEVEL = 0xFFFFFFC2, CL_INVALID_GLOBAL_WORK_SIZE = 0xFFFFFFC1; /** * OpenCL Version */ public static final int CL_VERSION_1_0 = 0x1; /** * cl_bool */ public static final int CL_FALSE = 0x0, CL_TRUE = 0x1; /** * cl_platform_info */ public static final int CL_PLATFORM_PROFILE = 0x900, CL_PLATFORM_VERSION = 0x901, CL_PLATFORM_NAME = 0x902, CL_PLATFORM_VENDOR = 0x903, CL_PLATFORM_EXTENSIONS = 0x904; /** * cl_device_type - bitfield */ public static final int CL_DEVICE_TYPE_DEFAULT = 0x1, CL_DEVICE_TYPE_CPU = 0x2, CL_DEVICE_TYPE_GPU = 0x4, CL_DEVICE_TYPE_ACCELERATOR = 0x8, CL_DEVICE_TYPE_ALL = 0xFFFFFFFF; /** * cl_device_info */ public static final int CL_DEVICE_TYPE = 0x1000, CL_DEVICE_VENDOR_ID = 0x1001, CL_DEVICE_MAX_COMPUTE_UNITS = 0x1002, CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS = 0x1003, CL_DEVICE_MAX_WORK_GROUP_SIZE = 0x1004, CL_DEVICE_MAX_WORK_ITEM_SIZES = 0x1005, CL_DEVICE_PREFERRED_VECTOR_WIDTH_CHAR = 0x1006, CL_DEVICE_PREFERRED_VECTOR_WIDTH_SHORT = 0x1007, CL_DEVICE_PREFERRED_VECTOR_WIDTH_ = 0x1008, CL_DEVICE_PREFERRED_VECTOR_WIDTH_LONG = 0x1009, CL_DEVICE_PREFERRED_VECTOR_WIDTH_FLOAT = 0x100A, CL_DEVICE_PREFERRED_VECTOR_WIDTH_DOUBLE = 0x100B, CL_DEVICE_MAX_CLOCK_FREQUENCY = 0x100C, CL_DEVICE_ADDRESS_BITS = 0x100D, CL_DEVICE_MAX_READ_IMAGE_ARGS = 0x100E, CL_DEVICE_MAX_WRITE_IMAGE_ARGS = 0x100F, CL_DEVICE_MAX_MEM_ALLOC_SIZE = 0x1010, CL_DEVICE_IMAGE2D_MAX_WIDTH = 0x1011, CL_DEVICE_IMAGE2D_MAX_HEIGHT = 0x1012, CL_DEVICE_IMAGE3D_MAX_WIDTH = 0x1013, CL_DEVICE_IMAGE3D_MAX_HEIGHT = 0x1014, CL_DEVICE_IMAGE3D_MAX_DEPTH = 0x1015, CL_DEVICE_IMAGE_SUPPORT = 0x1016, CL_DEVICE_MAX_PARAMETER_SIZE = 0x1017, CL_DEVICE_MAX_SAMPLERS = 0x1018, CL_DEVICE_MEM_BASE_ADDR_ALIGN = 0x1019, CL_DEVICE_MIN_DATA_TYPE_ALIGN_SIZE = 0x101A, CL_DEVICE_SINGLE_FP_CONFIG = 0x101B, CL_DEVICE_GLOBAL_MEM_CACHE_TYPE = 0x101C, CL_DEVICE_GLOBAL_MEM_CACHELINE_SIZE = 0x101D, CL_DEVICE_GLOBAL_MEM_CACHE_SIZE = 0x101E, CL_DEVICE_GLOBAL_MEM_SIZE = 0x101F, CL_DEVICE_MAX_CONSTANT_BUFFER_SIZE = 0x1020, CL_DEVICE_MAX_CONSTANT_ARGS = 0x1021, CL_DEVICE_LOCAL_MEM_TYPE = 0x1022, CL_DEVICE_LOCAL_MEM_SIZE = 0x1023, CL_DEVICE_ERROR_CORRECTION_SUPPORT = 0x1024, CL_DEVICE_PROFILING_TIMER_RESOLUTION = 0x1025, CL_DEVICE_ENDIAN_LITTLE = 0x1026, CL_DEVICE_AVAILABLE = 0x1027, CL_DEVICE_COMPILER_AVAILABLE = 0x1028, CL_DEVICE_EXECUTION_CAPABILITIES = 0x1029, CL_DEVICE_QUEUE_PROPERTIES = 0x102A, CL_DEVICE_NAME = 0x102B, CL_DEVICE_VENDOR = 0x102C, CL_DRIVER_VERSION = 0x102D, CL_DEVICE_PROFILE = 0x102E, CL_DEVICE_VERSION = 0x102F, CL_DEVICE_EXTENSIONS = 0x1030, CL_DEVICE_PLATFORM = 0x1031; /** * cl_device_fp_config - bitfield */ public static final int CL_FP_DENORM = 0x1, CL_FP_INF_NAN = 0x2, CL_FP_ROUND_TO_NEAREST = 0x4, CL_FP_ROUND_TO_ZERO = 0x8, CL_FP_ROUND_TO_INF = 0x10, CL_FP_FMA = 0x20; /** * cl_device_mem_cache_type */ public static final int CL_NONE = 0x0, CL_READ_ONLY_CACHE = 0x1, CL_READ_WRITE_CACHE = 0x2; /** * cl_device_local_mem_type */ public static final int CL_LOCAL = 0x1, CL_GLOBAL = 0x2; /** * cl_device_exec_capabilities - bitfield */ public static final int CL_EXEC_KERNEL = 0x1, CL_EXEC_NATIVE_KERNEL = 0x2; /** * cl_command_queue_properties - bitfield */ public static final int CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE = 0x1, CL_QUEUE_PROFILING_ENABLE = 0x2; /** * cl_context_info */ public static final int CL_CONTEXT_REFERENCE_COUNT = 0x1080, CL_CONTEXT_DEVICES = 0x1081, CL_CONTEXT_PROPERTIES = 0x1082; /** * cl_context_info + cl_context_properties */ public static final int CL_CONTEXT_PLATFORM = 0x1084; /** * cl_command_queue_info */ public static final int CL_QUEUE_CONTEXT = 0x1090, CL_QUEUE_DEVICE = 0x1091, CL_QUEUE_REFERENCE_COUNT = 0x1092, CL_QUEUE_PROPERTIES = 0x1093; /** * cl_mem_flags - bitfield */ public static final int CL_MEM_READ_WRITE = 0x1, CL_MEM_WRITE_ONLY = 0x2, CL_MEM_READ_ONLY = 0x4, CL_MEM_USE_HOST_PTR = 0x8, CL_MEM_ALLOC_HOST_PTR = 0x10, CL_MEM_COPY_HOST_PTR = 0x20; /** * cl_channel_order */ public static final int CL_R = 0x10B0, CL_A = 0x10B1, CL_RG = 0x10B2, CL_RA = 0x10B3, CL_RGB = 0x10B4, CL_RGBA = 0x10B5, CL_BGRA = 0x10B6, CL_ARGB = 0x10B7, CL_INTENSITY = 0x10B8, CL_LUMINANCE = 0x10B9; /** * cl_channel_type */ public static final int CL_SNORM_INT8 = 0x10D0, CL_SNORM_INT16 = 0x10D1, CL_UNORM_INT8 = 0x10D2, CL_UNORM_INT16 = 0x10D3, CL_UNORM_SHORT_565 = 0x10D4, CL_UNORM_SHORT_555 = 0x10D5, CL_UNORM_INT_101010 = 0x10D6, CL_SIGNED_INT8 = 0x10D7, CL_SIGNED_INT16 = 0x10D8, CL_SIGNED_INT32 = 0x10D9, CL_UNSIGNED_INT8 = 0x10DA, CL_UNSIGNED_INT16 = 0x10DB, CL_UNSIGNED_INT32 = 0x10DC, CL_HALF_FLOAT = 0x10DD, CL_FLOAT = 0x10DE; /** * cl_mem_object_type */ public static final int CL_MEM_OBJECT_BUFFER = 0x10F0, CL_MEM_OBJECT_IMAGE2D = 0x10F1, CL_MEM_OBJECT_IMAGE3D = 0x10F2; /** * cl_mem_info */ public static final int CL_MEM_TYPE = 0x1100, CL_MEM_FLAGS = 0x1101, CL_MEM_SIZE = 0x1102, CL_MEM_HOST_PTR = 0x1103, CL_MEM_MAP_COUNT = 0x1104, CL_MEM_REFERENCE_COUNT = 0x1105, CL_MEM_CONTEXT = 0x1106; /** * cl_image_info */ public static final int CL_IMAGE_FORMAT = 0x1110, CL_IMAGE_ELEMENT_SIZE = 0x1111, CL_IMAGE_ROW_PITCH = 0x1112, CL_IMAGE_SLICE_PITCH = 0x1113, CL_IMAGE_WIDTH = 0x1114, CL_IMAGE_HEIGHT = 0x1115, CL_IMAGE_DEPTH = 0x1116; /** * cl_addressing_mode */ public static final int CL_ADDRESS_NONE = 0x1130, CL_ADDRESS_CLAMP_TO_EDGE = 0x1131, CL_ADDRESS_CLAMP = 0x1132, CL_ADDRESS_REPEAT = 0x1133; /** * cl_filter_mode */ public static final int CL_FILTER_NEAREST = 0x1140, CL_FILTER_LINEAR = 0x1141; /** * cl_sampler_info */ public static final int CL_SAMPLER_REFERENCE_COUNT = 0x1150, CL_SAMPLER_CONTEXT = 0x1151, CL_SAMPLER_NORMALIZED_COORDS = 0x1152, CL_SAMPLER_ADDRESSING_MODE = 0x1153, CL_SAMPLER_FILTER_MODE = 0x1154; /** * cl_map_flags - bitfield */ public static final int CL_MAP_READ = 0x1, CL_MAP_WRITE = 0x2; /** * cl_program_info */ public static final int CL_PROGRAM_REFERENCE_COUNT = 0x1160, CL_PROGRAM_CONTEXT = 0x1161, CL_PROGRAM_NUM_DEVICES = 0x1162, CL_PROGRAM_DEVICES = 0x1163, CL_PROGRAM_SOURCE = 0x1164, CL_PROGRAM_BINARY_SIZES = 0x1165, CL_PROGRAM_BINARIES = 0x1166; /** * cl_program_build_info */ public static final int CL_PROGRAM_BUILD_STATUS = 0x1181, CL_PROGRAM_BUILD_OPTIONS = 0x1182, CL_PROGRAM_BUILD_LOG = 0x1183; /** * cl_build_status */ public static final int CL_BUILD_SUCCESS = 0x0, CL_BUILD_NONE = 0xFFFFFFFF, CL_BUILD_ERROR = 0xFFFFFFFE, CL_BUILD_IN_PROGRESS = 0xFFFFFFFD; /** * cl_kernel_info */ public static final int CL_KERNEL_FUNCTION_NAME = 0x1190, CL_KERNEL_NUM_ARGS = 0x1191, CL_KERNEL_REFERENCE_COUNT = 0x1192, CL_KERNEL_CONTEXT = 0x1193, CL_KERNEL_PROGRAM = 0x1194; /** * cl_kernel_work_group_info */ public static final int CL_KERNEL_WORK_GROUP_SIZE = 0x11B0, CL_KERNEL_COMPILE_WORK_GROUP_SIZE = 0x11B1, CL_KERNEL_LOCAL_MEM_SIZE = 0x11B2; /** * cl_event_info */ public static final int CL_EVENT_COMMAND_QUEUE = 0x11D0, CL_EVENT_COMMAND_TYPE = 0x11D1, CL_EVENT_REFERENCE_COUNT = 0x11D2, CL_EVENT_COMMAND_EXECUTION_STATUS = 0x11D3; /** * cl_command_type */ public static final int CL_COMMAND_NDRANGE_KERNEL = 0x11F0, CL_COMMAND_TASK = 0x11F1, CL_COMMAND_NATIVE_KERNEL = 0x11F2, CL_COMMAND_READ_BUFFER = 0x11F3, CL_COMMAND_WRITE_BUFFER = 0x11F4, CL_COMMAND_COPY_BUFFER = 0x11F5, CL_COMMAND_READ_IMAGE = 0x11F6, CL_COMMAND_WRITE_IMAGE = 0x11F7, CL_COMMAND_COPY_IMAGE = 0x11F8, CL_COMMAND_COPY_IMAGE_TO_BUFFER = 0x11F9, CL_COMMAND_COPY_BUFFER_TO_IMAGE = 0x11FA, CL_COMMAND_MAP_BUFFER = 0x11FB, CL_COMMAND_MAP_IMAGE = 0x11FC, CL_COMMAND_UNMAP_MEM_OBJECT = 0x11FD, CL_COMMAND_MARKER = 0x11FE, CL_COMMAND_ACQUIRE_GL_OBJECTS = 0x11FF, CL_COMMAND_RELEASE_GL_OBJECTS = 0x1200; /** * command execution status */ public static final int CL_COMPLETE = 0x0, CL_RUNNING = 0x1, CL_SUBMITTED = 0x2, CL_QUEUED = 0x3; /** * cl_profiling_info */ public static final int CL_PROFILING_COMMAND_QUEUED = 0x1280, CL_PROFILING_COMMAND_SUBMIT = 0x1281, CL_PROFILING_COMMAND_START = 0x1282, CL_PROFILING_COMMAND_END = 0x1283; private CL10() {} public static int clGetPlatformIDs(PointerBuffer platforms, IntBuffer num_platforms) { long function_pointer = CLCapabilities.clGetPlatformIDs; BufferChecks.checkFunctionAddress(function_pointer); if (platforms != null) BufferChecks.checkDirect(platforms); if (num_platforms != null) BufferChecks.checkBuffer(num_platforms, 1); if ( num_platforms == null ) num_platforms = APIUtil.getBufferInt(); int __result = nclGetPlatformIDs((platforms == null ? 0 : platforms.remaining()), MemoryUtil.getAddressSafe(platforms), MemoryUtil.getAddressSafe(num_platforms), function_pointer); if ( __result == CL_SUCCESS && platforms != null ) CLPlatform.registerCLPlatforms(platforms, num_platforms); return __result; } static native int nclGetPlatformIDs(int platforms_num_entries, long platforms, long num_platforms, long function_pointer); public static int clGetPlatformInfo(CLPlatform platform, int param_name, ByteBuffer param_value, PointerBuffer param_value_size_ret) { long function_pointer = CLCapabilities.clGetPlatformInfo; BufferChecks.checkFunctionAddress(function_pointer); if (param_value != null) BufferChecks.checkDirect(param_value); if (param_value_size_ret != null) BufferChecks.checkBuffer(param_value_size_ret, 1); int __result = nclGetPlatformInfo(platform == null ? 0 : platform.getPointer(), param_name, (param_value == null ? 0 : param_value.remaining()), MemoryUtil.getAddressSafe(param_value), MemoryUtil.getAddressSafe(param_value_size_ret), function_pointer); return __result; } static native int nclGetPlatformInfo(long platform, int param_name, long param_value_param_value_size, long param_value, long param_value_size_ret, long function_pointer); public static int clGetDeviceIDs(CLPlatform platform, long device_type, PointerBuffer devices, IntBuffer num_devices) { long function_pointer = CLCapabilities.clGetDeviceIDs; BufferChecks.checkFunctionAddress(function_pointer); if (devices != null) BufferChecks.checkDirect(devices); if (num_devices != null) BufferChecks.checkBuffer(num_devices, 1); else num_devices = APIUtil.getBufferInt(); int __result = nclGetDeviceIDs(platform.getPointer(), device_type, (devices == null ? 0 : devices.remaining()), MemoryUtil.getAddressSafe(devices), MemoryUtil.getAddressSafe(num_devices), function_pointer); if ( __result == CL_SUCCESS && devices != null ) platform.registerCLDevices(devices, num_devices); return __result; } static native int nclGetDeviceIDs(long platform, long device_type, int devices_num_entries, long devices, long num_devices, long function_pointer); public static int clGetDeviceInfo(CLDevice device, int param_name, ByteBuffer param_value, PointerBuffer param_value_size_ret) { long function_pointer = CLCapabilities.clGetDeviceInfo; BufferChecks.checkFunctionAddress(function_pointer); if (param_value != null) BufferChecks.checkDirect(param_value); if (param_value_size_ret != null) BufferChecks.checkBuffer(param_value_size_ret, 1); int __result = nclGetDeviceInfo(device.getPointer(), param_name, (param_value == null ? 0 : param_value.remaining()), MemoryUtil.getAddressSafe(param_value), MemoryUtil.getAddressSafe(param_value_size_ret), function_pointer); return __result; } static native int nclGetDeviceInfo(long device, int param_name, long param_value_param_value_size, long param_value, long param_value_size_ret, long function_pointer); /** * LWJGL requires CL_CONTEXT_PLATFORM to be present in the cl_context_properties buffer. */ public static CLContext clCreateContext(PointerBuffer properties, PointerBuffer devices, CLContextCallback pfn_notify, IntBuffer errcode_ret) { long function_pointer = CLCapabilities.clCreateContext; BufferChecks.checkFunctionAddress(function_pointer); BufferChecks.checkBuffer(properties, 3); BufferChecks.checkNullTerminated(properties); BufferChecks.checkBuffer(devices, 1); if (errcode_ret != null) BufferChecks.checkBuffer(errcode_ret, 1); long user_data = pfn_notify == null || pfn_notify.isCustom() ? 0 : CallbackUtil.createGlobalRef(pfn_notify); CLContext __result = null; try { __result = new CLContext(nclCreateContext(MemoryUtil.getAddress(properties), devices.remaining(), MemoryUtil.getAddress(devices), pfn_notify == null ? 0 : pfn_notify.getPointer(), user_data, MemoryUtil.getAddressSafe(errcode_ret), function_pointer), APIUtil.getCLPlatform(properties)); return __result; } finally { if ( __result != null ) __result.setContextCallback(user_data); } } static native long nclCreateContext(long properties, int devices_num_devices, long devices, long pfn_notify, long user_data, long errcode_ret, long function_pointer); /** * Overloads clCreateContext. * <p> * LWJGL requires CL_CONTEXT_PLATFORM to be present in the cl_context_properties buffer. */ public static CLContext clCreateContext(PointerBuffer properties, CLDevice device, CLContextCallback pfn_notify, IntBuffer errcode_ret) { long function_pointer = CLCapabilities.clCreateContext; BufferChecks.checkFunctionAddress(function_pointer); BufferChecks.checkBuffer(properties, 3); BufferChecks.checkNullTerminated(properties); if (errcode_ret != null) BufferChecks.checkBuffer(errcode_ret, 1); long user_data = pfn_notify == null || pfn_notify.isCustom() ? 0 : CallbackUtil.createGlobalRef(pfn_notify); CLContext __result = null; try { __result = new CLContext(nclCreateContext(MemoryUtil.getAddress(properties), 1, APIUtil.getPointer(device), pfn_notify == null ? 0 : pfn_notify.getPointer(), user_data, MemoryUtil.getAddressSafe(errcode_ret), function_pointer), APIUtil.getCLPlatform(properties)); return __result; } finally { if ( __result != null ) __result.setContextCallback(user_data); } } /** * LWJGL requires CL_CONTEXT_PLATFORM to be present in the cl_context_properties buffer. */ public static CLContext clCreateContextFromType(PointerBuffer properties, long device_type, CLContextCallback pfn_notify, IntBuffer errcode_ret) { long function_pointer = CLCapabilities.clCreateContextFromType; BufferChecks.checkFunctionAddress(function_pointer); BufferChecks.checkBuffer(properties, 3); BufferChecks.checkNullTerminated(properties); if (errcode_ret != null) BufferChecks.checkBuffer(errcode_ret, 1); long user_data = pfn_notify == null || pfn_notify.isCustom() ? 0 : CallbackUtil.createGlobalRef(pfn_notify); CLContext __result = null; try { __result = new CLContext(nclCreateContextFromType(MemoryUtil.getAddress(properties), device_type, pfn_notify == null ? 0 : pfn_notify.getPointer(), user_data, MemoryUtil.getAddressSafe(errcode_ret), function_pointer), APIUtil.getCLPlatform(properties)); return __result; } finally { if ( __result != null ) __result.setContextCallback(user_data); } } static native long nclCreateContextFromType(long properties, long device_type, long pfn_notify, long user_data, long errcode_ret, long function_pointer); public static int clRetainContext(CLContext context) { long function_pointer = CLCapabilities.clRetainContext; BufferChecks.checkFunctionAddress(function_pointer); int __result = nclRetainContext(context.getPointer(), function_pointer); if ( __result == CL_SUCCESS ) context.retain(); return __result; } static native int nclRetainContext(long context, long function_pointer); public static int clReleaseContext(CLContext context) { long function_pointer = CLCapabilities.clReleaseContext; BufferChecks.checkFunctionAddress(function_pointer); APIUtil.releaseObjects(context); int __result = nclReleaseContext(context.getPointer(), function_pointer); if ( __result == CL_SUCCESS ) context.releaseImpl(); return __result; } static native int nclReleaseContext(long context, long function_pointer); public static int clGetContextInfo(CLContext context, int param_name, ByteBuffer param_value, PointerBuffer param_value_size_ret) { long function_pointer = CLCapabilities.clGetContextInfo; BufferChecks.checkFunctionAddress(function_pointer); if (param_value != null) BufferChecks.checkDirect(param_value); if (param_value_size_ret != null) BufferChecks.checkBuffer(param_value_size_ret, 1); if ( param_value_size_ret == null && APIUtil.isDevicesParam(param_name) ) param_value_size_ret = APIUtil.getBufferPointer(); int __result = nclGetContextInfo(context.getPointer(), param_name, (param_value == null ? 0 : param_value.remaining()), MemoryUtil.getAddressSafe(param_value), MemoryUtil.getAddressSafe(param_value_size_ret), function_pointer); if ( __result == CL_SUCCESS && param_value != null && APIUtil.isDevicesParam(param_name) ) context.getParent().registerCLDevices(param_value, param_value_size_ret); return __result; } static native int nclGetContextInfo(long context, int param_name, long param_value_param_value_size, long param_value, long param_value_size_ret, long function_pointer); public static CLCommandQueue clCreateCommandQueue(CLContext context, CLDevice device, long properties, IntBuffer errcode_ret) { long function_pointer = CLCapabilities.clCreateCommandQueue; BufferChecks.checkFunctionAddress(function_pointer); if (errcode_ret != null) BufferChecks.checkBuffer(errcode_ret, 1); CLCommandQueue __result = new CLCommandQueue(nclCreateCommandQueue(context.getPointer(), device.getPointer(), properties, MemoryUtil.getAddressSafe(errcode_ret), function_pointer), context, device); return __result; } static native long nclCreateCommandQueue(long context, long device, long properties, long errcode_ret, long function_pointer); public static int clRetainCommandQueue(CLCommandQueue command_queue) { long function_pointer = CLCapabilities.clRetainCommandQueue; BufferChecks.checkFunctionAddress(function_pointer); int __result = nclRetainCommandQueue(command_queue.getPointer(), function_pointer); if ( __result == CL_SUCCESS ) command_queue.retain(); return __result; } static native int nclRetainCommandQueue(long command_queue, long function_pointer); public static int clReleaseCommandQueue(CLCommandQueue command_queue) { long function_pointer = CLCapabilities.clReleaseCommandQueue; BufferChecks.checkFunctionAddress(function_pointer); APIUtil.releaseObjects(command_queue); int __result = nclReleaseCommandQueue(command_queue.getPointer(), function_pointer); if ( __result == CL_SUCCESS ) command_queue.release(); return __result; } static native int nclReleaseCommandQueue(long command_queue, long function_pointer); public static int clGetCommandQueueInfo(CLCommandQueue command_queue, int param_name, ByteBuffer param_value, PointerBuffer param_value_size_ret) { long function_pointer = CLCapabilities.clGetCommandQueueInfo; BufferChecks.checkFunctionAddress(function_pointer); if (param_value != null) BufferChecks.checkDirect(param_value); if (param_value_size_ret != null) BufferChecks.checkBuffer(param_value_size_ret, 1); int __result = nclGetCommandQueueInfo(command_queue.getPointer(), param_name, (param_value == null ? 0 : param_value.remaining()), MemoryUtil.getAddressSafe(param_value), MemoryUtil.getAddressSafe(param_value_size_ret), function_pointer); return __result; } static native int nclGetCommandQueueInfo(long command_queue, int param_name, long param_value_param_value_size, long param_value, long param_value_size_ret, long function_pointer); public static CLMem clCreateBuffer(CLContext context, long flags, long host_ptr_size, IntBuffer errcode_ret) { long function_pointer = CLCapabilities.clCreateBuffer; BufferChecks.checkFunctionAddress(function_pointer); if (errcode_ret != null) BufferChecks.checkBuffer(errcode_ret, 1); CLMem __result = new CLMem(nclCreateBuffer(context.getPointer(), flags, host_ptr_size, 0L, MemoryUtil.getAddressSafe(errcode_ret), function_pointer), context); return __result; } public static CLMem clCreateBuffer(CLContext context, long flags, ByteBuffer host_ptr, IntBuffer errcode_ret) { long function_pointer = CLCapabilities.clCreateBuffer; BufferChecks.checkFunctionAddress(function_pointer); BufferChecks.checkDirect(host_ptr); if (errcode_ret != null) BufferChecks.checkBuffer(errcode_ret, 1); CLMem __result = new CLMem(nclCreateBuffer(context.getPointer(), flags, host_ptr.remaining(), MemoryUtil.getAddress(host_ptr), MemoryUtil.getAddressSafe(errcode_ret), function_pointer), context); return __result; } public static CLMem clCreateBuffer(CLContext context, long flags, DoubleBuffer host_ptr, IntBuffer errcode_ret) { long function_pointer = CLCapabilities.clCreateBuffer; BufferChecks.checkFunctionAddress(function_pointer); BufferChecks.checkDirect(host_ptr); if (errcode_ret != null) BufferChecks.checkBuffer(errcode_ret, 1); CLMem __result = new CLMem(nclCreateBuffer(context.getPointer(), flags, (host_ptr.remaining() << 3), MemoryUtil.getAddress(host_ptr), MemoryUtil.getAddressSafe(errcode_ret), function_pointer), context); return __result; } public static CLMem clCreateBuffer(CLContext context, long flags, FloatBuffer host_ptr, IntBuffer errcode_ret) { long function_pointer = CLCapabilities.clCreateBuffer; BufferChecks.checkFunctionAddress(function_pointer); BufferChecks.checkDirect(host_ptr); if (errcode_ret != null) BufferChecks.checkBuffer(errcode_ret, 1); CLMem __result = new CLMem(nclCreateBuffer(context.getPointer(), flags, (host_ptr.remaining() << 2), MemoryUtil.getAddress(host_ptr), MemoryUtil.getAddressSafe(errcode_ret), function_pointer), context); return __result; } public static CLMem clCreateBuffer(CLContext context, long flags, IntBuffer host_ptr, IntBuffer errcode_ret) { long function_pointer = CLCapabilities.clCreateBuffer; BufferChecks.checkFunctionAddress(function_pointer); BufferChecks.checkDirect(host_ptr); if (errcode_ret != null) BufferChecks.checkBuffer(errcode_ret, 1); CLMem __result = new CLMem(nclCreateBuffer(context.getPointer(), flags, (host_ptr.remaining() << 2), MemoryUtil.getAddress(host_ptr), MemoryUtil.getAddressSafe(errcode_ret), function_pointer), context); return __result; } public static CLMem clCreateBuffer(CLContext context, long flags, LongBuffer host_ptr, IntBuffer errcode_ret) { long function_pointer = CLCapabilities.clCreateBuffer; BufferChecks.checkFunctionAddress(function_pointer); BufferChecks.checkDirect(host_ptr); if (errcode_ret != null) BufferChecks.checkBuffer(errcode_ret, 1); CLMem __result = new CLMem(nclCreateBuffer(context.getPointer(), flags, (host_ptr.remaining() << 3), MemoryUtil.getAddress(host_ptr), MemoryUtil.getAddressSafe(errcode_ret), function_pointer), context); return __result; } public static CLMem clCreateBuffer(CLContext context, long flags, ShortBuffer host_ptr, IntBuffer errcode_ret) { long function_pointer = CLCapabilities.clCreateBuffer; BufferChecks.checkFunctionAddress(function_pointer); BufferChecks.checkDirect(host_ptr); if (errcode_ret != null) BufferChecks.checkBuffer(errcode_ret, 1); CLMem __result = new CLMem(nclCreateBuffer(context.getPointer(), flags, (host_ptr.remaining() << 1), MemoryUtil.getAddress(host_ptr), MemoryUtil.getAddressSafe(errcode_ret), function_pointer), context); return __result; } static native long nclCreateBuffer(long context, long flags, long host_ptr_size, long host_ptr, long errcode_ret, long function_pointer); public static int clEnqueueReadBuffer(CLCommandQueue command_queue, CLMem buffer, int blocking_read, long offset, ByteBuffer ptr, PointerBuffer event_wait_list, PointerBuffer event) { long function_pointer = CLCapabilities.clEnqueueReadBuffer; BufferChecks.checkFunctionAddress(function_pointer); BufferChecks.checkDirect(ptr); if (event_wait_list != null) BufferChecks.checkDirect(event_wait_list); if (event != null) BufferChecks.checkBuffer(event, 1); int __result = nclEnqueueReadBuffer(command_queue.getPointer(), buffer.getPointer(), blocking_read, offset, ptr.remaining(), MemoryUtil.getAddress(ptr), (event_wait_list == null ? 0 : event_wait_list.remaining()), MemoryUtil.getAddressSafe(event_wait_list), MemoryUtil.getAddressSafe(event), function_pointer); if ( __result == CL_SUCCESS ) command_queue.registerCLEvent(event); return __result; } public static int clEnqueueReadBuffer(CLCommandQueue command_queue, CLMem buffer, int blocking_read, long offset, DoubleBuffer ptr, PointerBuffer event_wait_list, PointerBuffer event) { long function_pointer = CLCapabilities.clEnqueueReadBuffer; BufferChecks.checkFunctionAddress(function_pointer); BufferChecks.checkDirect(ptr); if (event_wait_list != null) BufferChecks.checkDirect(event_wait_list); if (event != null) BufferChecks.checkBuffer(event, 1); int __result = nclEnqueueReadBuffer(command_queue.getPointer(), buffer.getPointer(), blocking_read, offset, (ptr.remaining() << 3), MemoryUtil.getAddress(ptr), (event_wait_list == null ? 0 : event_wait_list.remaining()), MemoryUtil.getAddressSafe(event_wait_list), MemoryUtil.getAddressSafe(event), function_pointer); if ( __result == CL_SUCCESS ) command_queue.registerCLEvent(event); return __result; } public static int clEnqueueReadBuffer(CLCommandQueue command_queue, CLMem buffer, int blocking_read, long offset, FloatBuffer ptr, PointerBuffer event_wait_list, PointerBuffer event) { long function_pointer = CLCapabilities.clEnqueueReadBuffer; BufferChecks.checkFunctionAddress(function_pointer); BufferChecks.checkDirect(ptr); if (event_wait_list != null) BufferChecks.checkDirect(event_wait_list); if (event != null) BufferChecks.checkBuffer(event, 1); int __result = nclEnqueueReadBuffer(command_queue.getPointer(), buffer.getPointer(), blocking_read, offset, (ptr.remaining() << 2), MemoryUtil.getAddress(ptr), (event_wait_list == null ? 0 : event_wait_list.remaining()), MemoryUtil.getAddressSafe(event_wait_list), MemoryUtil.getAddressSafe(event), function_pointer); if ( __result == CL_SUCCESS ) command_queue.registerCLEvent(event); return __result; } public static int clEnqueueReadBuffer(CLCommandQueue command_queue, CLMem buffer, int blocking_read, long offset, IntBuffer ptr, PointerBuffer event_wait_list, PointerBuffer event) { long function_pointer = CLCapabilities.clEnqueueReadBuffer; BufferChecks.checkFunctionAddress(function_pointer); BufferChecks.checkDirect(ptr); if (event_wait_list != null) BufferChecks.checkDirect(event_wait_list); if (event != null) BufferChecks.checkBuffer(event, 1); int __result = nclEnqueueReadBuffer(command_queue.getPointer(), buffer.getPointer(), blocking_read, offset, (ptr.remaining() << 2), MemoryUtil.getAddress(ptr), (event_wait_list == null ? 0 : event_wait_list.remaining()), MemoryUtil.getAddressSafe(event_wait_list), MemoryUtil.getAddressSafe(event), function_pointer); if ( __result == CL_SUCCESS ) command_queue.registerCLEvent(event); return __result; } public static int clEnqueueReadBuffer(CLCommandQueue command_queue, CLMem buffer, int blocking_read, long offset, LongBuffer ptr, PointerBuffer event_wait_list, PointerBuffer event) { long function_pointer = CLCapabilities.clEnqueueReadBuffer; BufferChecks.checkFunctionAddress(function_pointer); BufferChecks.checkDirect(ptr); if (event_wait_list != null) BufferChecks.checkDirect(event_wait_list); if (event != null) BufferChecks.checkBuffer(event, 1); int __result = nclEnqueueReadBuffer(command_queue.getPointer(), buffer.getPointer(), blocking_read, offset, (ptr.remaining() << 3), MemoryUtil.getAddress(ptr), (event_wait_list == null ? 0 : event_wait_list.remaining()), MemoryUtil.getAddressSafe(event_wait_list), MemoryUtil.getAddressSafe(event), function_pointer); if ( __result == CL_SUCCESS ) command_queue.registerCLEvent(event); return __result; } public static int clEnqueueReadBuffer(CLCommandQueue command_queue, CLMem buffer, int blocking_read, long offset, ShortBuffer ptr, PointerBuffer event_wait_list, PointerBuffer event) { long function_pointer = CLCapabilities.clEnqueueReadBuffer; BufferChecks.checkFunctionAddress(function_pointer); BufferChecks.checkDirect(ptr); if (event_wait_list != null) BufferChecks.checkDirect(event_wait_list); if (event != null) BufferChecks.checkBuffer(event, 1); int __result = nclEnqueueReadBuffer(command_queue.getPointer(), buffer.getPointer(), blocking_read, offset, (ptr.remaining() << 1), MemoryUtil.getAddress(ptr), (event_wait_list == null ? 0 : event_wait_list.remaining()), MemoryUtil.getAddressSafe(event_wait_list), MemoryUtil.getAddressSafe(event), function_pointer); if ( __result == CL_SUCCESS ) command_queue.registerCLEvent(event); return __result; } static native int nclEnqueueReadBuffer(long command_queue, long buffer, int blocking_read, long offset, long ptr_size, long ptr, int event_wait_list_num_events_in_wait_list, long event_wait_list, long event, long function_pointer); public static int clEnqueueWriteBuffer(CLCommandQueue command_queue, CLMem buffer, int blocking_write, long offset, ByteBuffer ptr, PointerBuffer event_wait_list, PointerBuffer event) { long function_pointer = CLCapabilities.clEnqueueWriteBuffer; BufferChecks.checkFunctionAddress(function_pointer); BufferChecks.checkDirect(ptr); if (event_wait_list != null) BufferChecks.checkDirect(event_wait_list); if (event != null) BufferChecks.checkBuffer(event, 1); int __result = nclEnqueueWriteBuffer(command_queue.getPointer(), buffer.getPointer(), blocking_write, offset, ptr.remaining(), MemoryUtil.getAddress(ptr), (event_wait_list == null ? 0 : event_wait_list.remaining()), MemoryUtil.getAddressSafe(event_wait_list), MemoryUtil.getAddressSafe(event), function_pointer); if ( __result == CL_SUCCESS ) command_queue.registerCLEvent(event); return __result; } public static int clEnqueueWriteBuffer(CLCommandQueue command_queue, CLMem buffer, int blocking_write, long offset, DoubleBuffer ptr, PointerBuffer event_wait_list, PointerBuffer event) { long function_pointer = CLCapabilities.clEnqueueWriteBuffer; BufferChecks.checkFunctionAddress(function_pointer); BufferChecks.checkDirect(ptr); if (event_wait_list != null) BufferChecks.checkDirect(event_wait_list); if (event != null) BufferChecks.checkBuffer(event, 1); int __result = nclEnqueueWriteBuffer(command_queue.getPointer(), buffer.getPointer(), blocking_write, offset, (ptr.remaining() << 3), MemoryUtil.getAddress(ptr), (event_wait_list == null ? 0 : event_wait_list.remaining()), MemoryUtil.getAddressSafe(event_wait_list), MemoryUtil.getAddressSafe(event), function_pointer); if ( __result == CL_SUCCESS ) command_queue.registerCLEvent(event); return __result; } public static int clEnqueueWriteBuffer(CLCommandQueue command_queue, CLMem buffer, int blocking_write, long offset, FloatBuffer ptr, PointerBuffer event_wait_list, PointerBuffer event) { long function_pointer = CLCapabilities.clEnqueueWriteBuffer; BufferChecks.checkFunctionAddress(function_pointer); BufferChecks.checkDirect(ptr); if (event_wait_list != null) BufferChecks.checkDirect(event_wait_list); if (event != null) BufferChecks.checkBuffer(event, 1); int __result = nclEnqueueWriteBuffer(command_queue.getPointer(), buffer.getPointer(), blocking_write, offset, (ptr.remaining() << 2), MemoryUtil.getAddress(ptr), (event_wait_list == null ? 0 : event_wait_list.remaining()), MemoryUtil.getAddressSafe(event_wait_list), MemoryUtil.getAddressSafe(event), function_pointer); if ( __result == CL_SUCCESS ) command_queue.registerCLEvent(event); return __result; } public static int clEnqueueWriteBuffer(CLCommandQueue command_queue, CLMem buffer, int blocking_write, long offset, IntBuffer ptr, PointerBuffer event_wait_list, PointerBuffer event) { long function_pointer = CLCapabilities.clEnqueueWriteBuffer; BufferChecks.checkFunctionAddress(function_pointer); BufferChecks.checkDirect(ptr); if (event_wait_list != null) BufferChecks.checkDirect(event_wait_list); if (event != null) BufferChecks.checkBuffer(event, 1); int __result = nclEnqueueWriteBuffer(command_queue.getPointer(), buffer.getPointer(), blocking_write, offset, (ptr.remaining() << 2), MemoryUtil.getAddress(ptr), (event_wait_list == null ? 0 : event_wait_list.remaining()), MemoryUtil.getAddressSafe(event_wait_list), MemoryUtil.getAddressSafe(event), function_pointer); if ( __result == CL_SUCCESS ) command_queue.registerCLEvent(event); return __result; } public static int clEnqueueWriteBuffer(CLCommandQueue command_queue, CLMem buffer, int blocking_write, long offset, LongBuffer ptr, PointerBuffer event_wait_list, PointerBuffer event) { long function_pointer = CLCapabilities.clEnqueueWriteBuffer; BufferChecks.checkFunctionAddress(function_pointer); BufferChecks.checkDirect(ptr); if (event_wait_list != null) BufferChecks.checkDirect(event_wait_list); if (event != null) BufferChecks.checkBuffer(event, 1); int __result = nclEnqueueWriteBuffer(command_queue.getPointer(), buffer.getPointer(), blocking_write, offset, (ptr.remaining() << 3), MemoryUtil.getAddress(ptr), (event_wait_list == null ? 0 : event_wait_list.remaining()), MemoryUtil.getAddressSafe(event_wait_list), MemoryUtil.getAddressSafe(event), function_pointer); if ( __result == CL_SUCCESS ) command_queue.registerCLEvent(event); return __result; } public static int clEnqueueWriteBuffer(CLCommandQueue command_queue, CLMem buffer, int blocking_write, long offset, ShortBuffer ptr, PointerBuffer event_wait_list, PointerBuffer event) { long function_pointer = CLCapabilities.clEnqueueWriteBuffer; BufferChecks.checkFunctionAddress(function_pointer); BufferChecks.checkDirect(ptr); if (event_wait_list != null) BufferChecks.checkDirect(event_wait_list); if (event != null) BufferChecks.checkBuffer(event, 1); int __result = nclEnqueueWriteBuffer(command_queue.getPointer(), buffer.getPointer(), blocking_write, offset, (ptr.remaining() << 1), MemoryUtil.getAddress(ptr), (event_wait_list == null ? 0 : event_wait_list.remaining()), MemoryUtil.getAddressSafe(event_wait_list), MemoryUtil.getAddressSafe(event), function_pointer); if ( __result == CL_SUCCESS ) command_queue.registerCLEvent(event); return __result; } static native int nclEnqueueWriteBuffer(long command_queue, long buffer, int blocking_write, long offset, long ptr_size, long ptr, int event_wait_list_num_events_in_wait_list, long event_wait_list, long event, long function_pointer); public static int clEnqueueCopyBuffer(CLCommandQueue command_queue, CLMem src_buffer, CLMem dst_buffer, long src_offset, long dst_offset, long size, PointerBuffer event_wait_list, PointerBuffer event) { long function_pointer = CLCapabilities.clEnqueueCopyBuffer; BufferChecks.checkFunctionAddress(function_pointer); if (event_wait_list != null) BufferChecks.checkDirect(event_wait_list); if (event != null) BufferChecks.checkBuffer(event, 1); int __result = nclEnqueueCopyBuffer(command_queue.getPointer(), src_buffer.getPointer(), dst_buffer.getPointer(), src_offset, dst_offset, size, (event_wait_list == null ? 0 : event_wait_list.remaining()), MemoryUtil.getAddressSafe(event_wait_list), MemoryUtil.getAddressSafe(event), function_pointer); if ( __result == CL_SUCCESS ) command_queue.registerCLEvent(event); return __result; } static native int nclEnqueueCopyBuffer(long command_queue, long src_buffer, long dst_buffer, long src_offset, long dst_offset, long size, int event_wait_list_num_events_in_wait_list, long event_wait_list, long event, long function_pointer); public static ByteBuffer clEnqueueMapBuffer(CLCommandQueue command_queue, CLMem buffer, int blocking_map, long map_flags, long offset, long size, PointerBuffer event_wait_list, PointerBuffer event, IntBuffer errcode_ret) { long function_pointer = CLCapabilities.clEnqueueMapBuffer; BufferChecks.checkFunctionAddress(function_pointer); if (event_wait_list != null) BufferChecks.checkDirect(event_wait_list); if (event != null) BufferChecks.checkBuffer(event, 1); if (errcode_ret != null) BufferChecks.checkBuffer(errcode_ret, 1); ByteBuffer __result = nclEnqueueMapBuffer(command_queue.getPointer(), buffer.getPointer(), blocking_map, map_flags, offset, size, (event_wait_list == null ? 0 : event_wait_list.remaining()), MemoryUtil.getAddressSafe(event_wait_list), MemoryUtil.getAddressSafe(event), MemoryUtil.getAddressSafe(errcode_ret), size, function_pointer); if ( __result != null ) command_queue.registerCLEvent(event); return LWJGLUtil.CHECKS && __result == null ? null : __result.order(ByteOrder.nativeOrder()); } static native ByteBuffer nclEnqueueMapBuffer(long command_queue, long buffer, int blocking_map, long map_flags, long offset, long size, int event_wait_list_num_events_in_wait_list, long event_wait_list, long event, long errcode_ret, long result_size, long function_pointer); public static CLMem clCreateImage2D(CLContext context, long flags, ByteBuffer image_format, long image_width, long image_height, long image_row_pitch, ByteBuffer host_ptr, IntBuffer errcode_ret) { long function_pointer = CLCapabilities.clCreateImage2D; BufferChecks.checkFunctionAddress(function_pointer); BufferChecks.checkBuffer(image_format, 2 * 4); if (host_ptr != null) BufferChecks.checkBuffer(host_ptr, CLChecks.calculateImage2DSize(image_format, image_width, image_height, image_row_pitch)); if (errcode_ret != null) BufferChecks.checkBuffer(errcode_ret, 1); CLMem __result = new CLMem(nclCreateImage2D(context.getPointer(), flags, MemoryUtil.getAddress(image_format), image_width, image_height, image_row_pitch, MemoryUtil.getAddressSafe(host_ptr), MemoryUtil.getAddressSafe(errcode_ret), function_pointer), context); return __result; } public static CLMem clCreateImage2D(CLContext context, long flags, ByteBuffer image_format, long image_width, long image_height, long image_row_pitch, FloatBuffer host_ptr, IntBuffer errcode_ret) { long function_pointer = CLCapabilities.clCreateImage2D; BufferChecks.checkFunctionAddress(function_pointer); BufferChecks.checkBuffer(image_format, 2 * 4); if (host_ptr != null) BufferChecks.checkBuffer(host_ptr, CLChecks.calculateImage2DSize(image_format, image_width, image_height, image_row_pitch)); if (errcode_ret != null) BufferChecks.checkBuffer(errcode_ret, 1); CLMem __result = new CLMem(nclCreateImage2D(context.getPointer(), flags, MemoryUtil.getAddress(image_format), image_width, image_height, image_row_pitch, MemoryUtil.getAddressSafe(host_ptr), MemoryUtil.getAddressSafe(errcode_ret), function_pointer), context); return __result; } public static CLMem clCreateImage2D(CLContext context, long flags, ByteBuffer image_format, long image_width, long image_height, long image_row_pitch, IntBuffer host_ptr, IntBuffer errcode_ret) { long function_pointer = CLCapabilities.clCreateImage2D; BufferChecks.checkFunctionAddress(function_pointer); BufferChecks.checkBuffer(image_format, 2 * 4); if (host_ptr != null) BufferChecks.checkBuffer(host_ptr, CLChecks.calculateImage2DSize(image_format, image_width, image_height, image_row_pitch)); if (errcode_ret != null) BufferChecks.checkBuffer(errcode_ret, 1); CLMem __result = new CLMem(nclCreateImage2D(context.getPointer(), flags, MemoryUtil.getAddress(image_format), image_width, image_height, image_row_pitch, MemoryUtil.getAddressSafe(host_ptr), MemoryUtil.getAddressSafe(errcode_ret), function_pointer), context); return __result; } public static CLMem clCreateImage2D(CLContext context, long flags, ByteBuffer image_format, long image_width, long image_height, long image_row_pitch, ShortBuffer host_ptr, IntBuffer errcode_ret) { long function_pointer = CLCapabilities.clCreateImage2D; BufferChecks.checkFunctionAddress(function_pointer); BufferChecks.checkBuffer(image_format, 2 * 4); if (host_ptr != null) BufferChecks.checkBuffer(host_ptr, CLChecks.calculateImage2DSize(image_format, image_width, image_height, image_row_pitch)); if (errcode_ret != null) BufferChecks.checkBuffer(errcode_ret, 1); CLMem __result = new CLMem(nclCreateImage2D(context.getPointer(), flags, MemoryUtil.getAddress(image_format), image_width, image_height, image_row_pitch, MemoryUtil.getAddressSafe(host_ptr), MemoryUtil.getAddressSafe(errcode_ret), function_pointer), context); return __result; } static native long nclCreateImage2D(long context, long flags, long image_format, long image_width, long image_height, long image_row_pitch, long host_ptr, long errcode_ret, long function_pointer); public static CLMem clCreateImage3D(CLContext context, long flags, ByteBuffer image_format, long image_width, long image_height, long image_depth, long image_row_pitch, long image_slice_pitch, ByteBuffer host_ptr, IntBuffer errcode_ret) { long function_pointer = CLCapabilities.clCreateImage3D; BufferChecks.checkFunctionAddress(function_pointer); BufferChecks.checkBuffer(image_format, 2 * 4); if (host_ptr != null) BufferChecks.checkBuffer(host_ptr, CLChecks.calculateImage3DSize(image_format, image_width, image_height, image_height, image_row_pitch, image_slice_pitch)); if (errcode_ret != null) BufferChecks.checkBuffer(errcode_ret, 1); CLMem __result = new CLMem(nclCreateImage3D(context.getPointer(), flags, MemoryUtil.getAddress(image_format), image_width, image_height, image_depth, image_row_pitch, image_slice_pitch, MemoryUtil.getAddressSafe(host_ptr), MemoryUtil.getAddressSafe(errcode_ret), function_pointer), context); return __result; } public static CLMem clCreateImage3D(CLContext context, long flags, ByteBuffer image_format, long image_width, long image_height, long image_depth, long image_row_pitch, long image_slice_pitch, FloatBuffer host_ptr, IntBuffer errcode_ret) { long function_pointer = CLCapabilities.clCreateImage3D; BufferChecks.checkFunctionAddress(function_pointer); BufferChecks.checkBuffer(image_format, 2 * 4); if (host_ptr != null) BufferChecks.checkBuffer(host_ptr, CLChecks.calculateImage3DSize(image_format, image_width, image_height, image_height, image_row_pitch, image_slice_pitch)); if (errcode_ret != null) BufferChecks.checkBuffer(errcode_ret, 1); CLMem __result = new CLMem(nclCreateImage3D(context.getPointer(), flags, MemoryUtil.getAddress(image_format), image_width, image_height, image_depth, image_row_pitch, image_slice_pitch, MemoryUtil.getAddressSafe(host_ptr), MemoryUtil.getAddressSafe(errcode_ret), function_pointer), context); return __result; } public static CLMem clCreateImage3D(CLContext context, long flags, ByteBuffer image_format, long image_width, long image_height, long image_depth, long image_row_pitch, long image_slice_pitch, IntBuffer host_ptr, IntBuffer errcode_ret) { long function_pointer = CLCapabilities.clCreateImage3D; BufferChecks.checkFunctionAddress(function_pointer); BufferChecks.checkBuffer(image_format, 2 * 4); if (host_ptr != null) BufferChecks.checkBuffer(host_ptr, CLChecks.calculateImage3DSize(image_format, image_width, image_height, image_height, image_row_pitch, image_slice_pitch)); if (errcode_ret != null) BufferChecks.checkBuffer(errcode_ret, 1); CLMem __result = new CLMem(nclCreateImage3D(context.getPointer(), flags, MemoryUtil.getAddress(image_format), image_width, image_height, image_depth, image_row_pitch, image_slice_pitch, MemoryUtil.getAddressSafe(host_ptr), MemoryUtil.getAddressSafe(errcode_ret), function_pointer), context); return __result; } public static CLMem clCreateImage3D(CLContext context, long flags, ByteBuffer image_format, long image_width, long image_height, long image_depth, long image_row_pitch, long image_slice_pitch, ShortBuffer host_ptr, IntBuffer errcode_ret) { long function_pointer = CLCapabilities.clCreateImage3D; BufferChecks.checkFunctionAddress(function_pointer); BufferChecks.checkBuffer(image_format, 2 * 4); if (host_ptr != null) BufferChecks.checkBuffer(host_ptr, CLChecks.calculateImage3DSize(image_format, image_width, image_height, image_height, image_row_pitch, image_slice_pitch)); if (errcode_ret != null) BufferChecks.checkBuffer(errcode_ret, 1); CLMem __result = new CLMem(nclCreateImage3D(context.getPointer(), flags, MemoryUtil.getAddress(image_format), image_width, image_height, image_depth, image_row_pitch, image_slice_pitch, MemoryUtil.getAddressSafe(host_ptr), MemoryUtil.getAddressSafe(errcode_ret), function_pointer), context); return __result; } static native long nclCreateImage3D(long context, long flags, long image_format, long image_width, long image_height, long image_depth, long image_row_pitch, long image_slice_pitch, long host_ptr, long errcode_ret, long function_pointer); public static int clGetSupportedImageFormats(CLContext context, long flags, int image_type, ByteBuffer image_formats, IntBuffer num_image_formats) { long function_pointer = CLCapabilities.clGetSupportedImageFormats; BufferChecks.checkFunctionAddress(function_pointer); if (image_formats != null) BufferChecks.checkDirect(image_formats); if (num_image_formats != null) BufferChecks.checkBuffer(num_image_formats, 1); int __result = nclGetSupportedImageFormats(context.getPointer(), flags, image_type, (image_formats == null ? 0 : image_formats.remaining()) / (2 * 4), MemoryUtil.getAddressSafe(image_formats), MemoryUtil.getAddressSafe(num_image_formats), function_pointer); return __result; } static native int nclGetSupportedImageFormats(long context, long flags, int image_type, int image_formats_num_entries, long image_formats, long num_image_formats, long function_pointer); public static int clEnqueueReadImage(CLCommandQueue command_queue, CLMem image, int blocking_read, PointerBuffer origin, PointerBuffer region, long row_pitch, long slice_pitch, ByteBuffer ptr, PointerBuffer event_wait_list, PointerBuffer event) { long function_pointer = CLCapabilities.clEnqueueReadImage; BufferChecks.checkFunctionAddress(function_pointer); BufferChecks.checkBuffer(origin, 3); BufferChecks.checkBuffer(region, 3); BufferChecks.checkBuffer(ptr, CLChecks.calculateImageSize(region, row_pitch, slice_pitch)); if (event_wait_list != null) BufferChecks.checkDirect(event_wait_list); if (event != null) BufferChecks.checkBuffer(event, 1); int __result = nclEnqueueReadImage(command_queue.getPointer(), image.getPointer(), blocking_read, MemoryUtil.getAddress(origin), MemoryUtil.getAddress(region), row_pitch, slice_pitch, MemoryUtil.getAddress(ptr), (event_wait_list == null ? 0 : event_wait_list.remaining()), MemoryUtil.getAddressSafe(event_wait_list), MemoryUtil.getAddressSafe(event), function_pointer); if ( __result == CL_SUCCESS ) command_queue.registerCLEvent(event); return __result; } public static int clEnqueueReadImage(CLCommandQueue command_queue, CLMem image, int blocking_read, PointerBuffer origin, PointerBuffer region, long row_pitch, long slice_pitch, FloatBuffer ptr, PointerBuffer event_wait_list, PointerBuffer event) { long function_pointer = CLCapabilities.clEnqueueReadImage; BufferChecks.checkFunctionAddress(function_pointer); BufferChecks.checkBuffer(origin, 3); BufferChecks.checkBuffer(region, 3); BufferChecks.checkBuffer(ptr, CLChecks.calculateImageSize(region, row_pitch, slice_pitch)); if (event_wait_list != null) BufferChecks.checkDirect(event_wait_list); if (event != null) BufferChecks.checkBuffer(event, 1); int __result = nclEnqueueReadImage(command_queue.getPointer(), image.getPointer(), blocking_read, MemoryUtil.getAddress(origin), MemoryUtil.getAddress(region), row_pitch, slice_pitch, MemoryUtil.getAddress(ptr), (event_wait_list == null ? 0 : event_wait_list.remaining()), MemoryUtil.getAddressSafe(event_wait_list), MemoryUtil.getAddressSafe(event), function_pointer); if ( __result == CL_SUCCESS ) command_queue.registerCLEvent(event); return __result; } public static int clEnqueueReadImage(CLCommandQueue command_queue, CLMem image, int blocking_read, PointerBuffer origin, PointerBuffer region, long row_pitch, long slice_pitch, IntBuffer ptr, PointerBuffer event_wait_list, PointerBuffer event) { long function_pointer = CLCapabilities.clEnqueueReadImage; BufferChecks.checkFunctionAddress(function_pointer); BufferChecks.checkBuffer(origin, 3); BufferChecks.checkBuffer(region, 3); BufferChecks.checkBuffer(ptr, CLChecks.calculateImageSize(region, row_pitch, slice_pitch)); if (event_wait_list != null) BufferChecks.checkDirect(event_wait_list); if (event != null) BufferChecks.checkBuffer(event, 1); int __result = nclEnqueueReadImage(command_queue.getPointer(), image.getPointer(), blocking_read, MemoryUtil.getAddress(origin), MemoryUtil.getAddress(region), row_pitch, slice_pitch, MemoryUtil.getAddress(ptr), (event_wait_list == null ? 0 : event_wait_list.remaining()), MemoryUtil.getAddressSafe(event_wait_list), MemoryUtil.getAddressSafe(event), function_pointer); if ( __result == CL_SUCCESS ) command_queue.registerCLEvent(event); return __result; } public static int clEnqueueReadImage(CLCommandQueue command_queue, CLMem image, int blocking_read, PointerBuffer origin, PointerBuffer region, long row_pitch, long slice_pitch, ShortBuffer ptr, PointerBuffer event_wait_list, PointerBuffer event) { long function_pointer = CLCapabilities.clEnqueueReadImage; BufferChecks.checkFunctionAddress(function_pointer); BufferChecks.checkBuffer(origin, 3); BufferChecks.checkBuffer(region, 3); BufferChecks.checkBuffer(ptr, CLChecks.calculateImageSize(region, row_pitch, slice_pitch)); if (event_wait_list != null) BufferChecks.checkDirect(event_wait_list); if (event != null) BufferChecks.checkBuffer(event, 1); int __result = nclEnqueueReadImage(command_queue.getPointer(), image.getPointer(), blocking_read, MemoryUtil.getAddress(origin), MemoryUtil.getAddress(region), row_pitch, slice_pitch, MemoryUtil.getAddress(ptr), (event_wait_list == null ? 0 : event_wait_list.remaining()), MemoryUtil.getAddressSafe(event_wait_list), MemoryUtil.getAddressSafe(event), function_pointer); if ( __result == CL_SUCCESS ) command_queue.registerCLEvent(event); return __result; } static native int nclEnqueueReadImage(long command_queue, long image, int blocking_read, long origin, long region, long row_pitch, long slice_pitch, long ptr, int event_wait_list_num_events_in_wait_list, long event_wait_list, long event, long function_pointer); public static int clEnqueueWriteImage(CLCommandQueue command_queue, CLMem image, int blocking_write, PointerBuffer origin, PointerBuffer region, long input_row_pitch, long input_slice_pitch, ByteBuffer ptr, PointerBuffer event_wait_list, PointerBuffer event) { long function_pointer = CLCapabilities.clEnqueueWriteImage; BufferChecks.checkFunctionAddress(function_pointer); BufferChecks.checkBuffer(origin, 3); BufferChecks.checkBuffer(region, 3); BufferChecks.checkBuffer(ptr, CLChecks.calculateImageSize(region, input_row_pitch, input_slice_pitch)); if (event_wait_list != null) BufferChecks.checkDirect(event_wait_list); if (event != null) BufferChecks.checkBuffer(event, 1); int __result = nclEnqueueWriteImage(command_queue.getPointer(), image.getPointer(), blocking_write, MemoryUtil.getAddress(origin), MemoryUtil.getAddress(region), input_row_pitch, input_slice_pitch, MemoryUtil.getAddress(ptr), (event_wait_list == null ? 0 : event_wait_list.remaining()), MemoryUtil.getAddressSafe(event_wait_list), MemoryUtil.getAddressSafe(event), function_pointer); if ( __result == CL_SUCCESS ) command_queue.registerCLEvent(event); return __result; } public static int clEnqueueWriteImage(CLCommandQueue command_queue, CLMem image, int blocking_write, PointerBuffer origin, PointerBuffer region, long input_row_pitch, long input_slice_pitch, FloatBuffer ptr, PointerBuffer event_wait_list, PointerBuffer event) { long function_pointer = CLCapabilities.clEnqueueWriteImage; BufferChecks.checkFunctionAddress(function_pointer); BufferChecks.checkBuffer(origin, 3); BufferChecks.checkBuffer(region, 3); BufferChecks.checkBuffer(ptr, CLChecks.calculateImageSize(region, input_row_pitch, input_slice_pitch)); if (event_wait_list != null) BufferChecks.checkDirect(event_wait_list); if (event != null) BufferChecks.checkBuffer(event, 1); int __result = nclEnqueueWriteImage(command_queue.getPointer(), image.getPointer(), blocking_write, MemoryUtil.getAddress(origin), MemoryUtil.getAddress(region), input_row_pitch, input_slice_pitch, MemoryUtil.getAddress(ptr), (event_wait_list == null ? 0 : event_wait_list.remaining()), MemoryUtil.getAddressSafe(event_wait_list), MemoryUtil.getAddressSafe(event), function_pointer); if ( __result == CL_SUCCESS ) command_queue.registerCLEvent(event); return __result; } public static int clEnqueueWriteImage(CLCommandQueue command_queue, CLMem image, int blocking_write, PointerBuffer origin, PointerBuffer region, long input_row_pitch, long input_slice_pitch, IntBuffer ptr, PointerBuffer event_wait_list, PointerBuffer event) { long function_pointer = CLCapabilities.clEnqueueWriteImage; BufferChecks.checkFunctionAddress(function_pointer); BufferChecks.checkBuffer(origin, 3); BufferChecks.checkBuffer(region, 3); BufferChecks.checkBuffer(ptr, CLChecks.calculateImageSize(region, input_row_pitch, input_slice_pitch)); if (event_wait_list != null) BufferChecks.checkDirect(event_wait_list); if (event != null) BufferChecks.checkBuffer(event, 1); int __result = nclEnqueueWriteImage(command_queue.getPointer(), image.getPointer(), blocking_write, MemoryUtil.getAddress(origin), MemoryUtil.getAddress(region), input_row_pitch, input_slice_pitch, MemoryUtil.getAddress(ptr), (event_wait_list == null ? 0 : event_wait_list.remaining()), MemoryUtil.getAddressSafe(event_wait_list), MemoryUtil.getAddressSafe(event), function_pointer); if ( __result == CL_SUCCESS ) command_queue.registerCLEvent(event); return __result; } public static int clEnqueueWriteImage(CLCommandQueue command_queue, CLMem image, int blocking_write, PointerBuffer origin, PointerBuffer region, long input_row_pitch, long input_slice_pitch, ShortBuffer ptr, PointerBuffer event_wait_list, PointerBuffer event) { long function_pointer = CLCapabilities.clEnqueueWriteImage; BufferChecks.checkFunctionAddress(function_pointer); BufferChecks.checkBuffer(origin, 3); BufferChecks.checkBuffer(region, 3); BufferChecks.checkBuffer(ptr, CLChecks.calculateImageSize(region, input_row_pitch, input_slice_pitch)); if (event_wait_list != null) BufferChecks.checkDirect(event_wait_list); if (event != null) BufferChecks.checkBuffer(event, 1); int __result = nclEnqueueWriteImage(command_queue.getPointer(), image.getPointer(), blocking_write, MemoryUtil.getAddress(origin), MemoryUtil.getAddress(region), input_row_pitch, input_slice_pitch, MemoryUtil.getAddress(ptr), (event_wait_list == null ? 0 : event_wait_list.remaining()), MemoryUtil.getAddressSafe(event_wait_list), MemoryUtil.getAddressSafe(event), function_pointer); if ( __result == CL_SUCCESS ) command_queue.registerCLEvent(event); return __result; } static native int nclEnqueueWriteImage(long command_queue, long image, int blocking_write, long origin, long region, long input_row_pitch, long input_slice_pitch, long ptr, int event_wait_list_num_events_in_wait_list, long event_wait_list, long event, long function_pointer); public static int clEnqueueCopyImage(CLCommandQueue command_queue, CLMem src_image, CLMem dst_image, PointerBuffer src_origin, PointerBuffer dst_origin, PointerBuffer region, PointerBuffer event_wait_list, PointerBuffer event) { long function_pointer = CLCapabilities.clEnqueueCopyImage; BufferChecks.checkFunctionAddress(function_pointer); BufferChecks.checkBuffer(src_origin, 3); BufferChecks.checkBuffer(dst_origin, 3); BufferChecks.checkBuffer(region, 3); if (event_wait_list != null) BufferChecks.checkDirect(event_wait_list); if (event != null) BufferChecks.checkBuffer(event, 1); int __result = nclEnqueueCopyImage(command_queue.getPointer(), src_image.getPointer(), dst_image.getPointer(), MemoryUtil.getAddress(src_origin), MemoryUtil.getAddress(dst_origin), MemoryUtil.getAddress(region), (event_wait_list == null ? 0 : event_wait_list.remaining()), MemoryUtil.getAddressSafe(event_wait_list), MemoryUtil.getAddressSafe(event), function_pointer); if ( __result == CL_SUCCESS ) command_queue.registerCLEvent(event); return __result; } static native int nclEnqueueCopyImage(long command_queue, long src_image, long dst_image, long src_origin, long dst_origin, long region, int event_wait_list_num_events_in_wait_list, long event_wait_list, long event, long function_pointer); public static int clEnqueueCopyImageToBuffer(CLCommandQueue command_queue, CLMem src_image, CLMem dst_buffer, PointerBuffer src_origin, PointerBuffer region, long dst_offset, PointerBuffer event_wait_list, PointerBuffer event) { long function_pointer = CLCapabilities.clEnqueueCopyImageToBuffer; BufferChecks.checkFunctionAddress(function_pointer); BufferChecks.checkBuffer(src_origin, 3); BufferChecks.checkBuffer(region, 3); if (event_wait_list != null) BufferChecks.checkDirect(event_wait_list); if (event != null) BufferChecks.checkBuffer(event, 1); int __result = nclEnqueueCopyImageToBuffer(command_queue.getPointer(), src_image.getPointer(), dst_buffer.getPointer(), MemoryUtil.getAddress(src_origin), MemoryUtil.getAddress(region), dst_offset, (event_wait_list == null ? 0 : event_wait_list.remaining()), MemoryUtil.getAddressSafe(event_wait_list), MemoryUtil.getAddressSafe(event), function_pointer); if ( __result == CL_SUCCESS ) command_queue.registerCLEvent(event); return __result; } static native int nclEnqueueCopyImageToBuffer(long command_queue, long src_image, long dst_buffer, long src_origin, long region, long dst_offset, int event_wait_list_num_events_in_wait_list, long event_wait_list, long event, long function_pointer); public static int clEnqueueCopyBufferToImage(CLCommandQueue command_queue, CLMem src_buffer, CLMem dst_image, long src_offset, PointerBuffer dst_origin, PointerBuffer region, PointerBuffer event_wait_list, PointerBuffer event) { long function_pointer = CLCapabilities.clEnqueueCopyBufferToImage; BufferChecks.checkFunctionAddress(function_pointer); BufferChecks.checkBuffer(dst_origin, 3); BufferChecks.checkBuffer(region, 3); if (event_wait_list != null) BufferChecks.checkDirect(event_wait_list); if (event != null) BufferChecks.checkBuffer(event, 1); int __result = nclEnqueueCopyBufferToImage(command_queue.getPointer(), src_buffer.getPointer(), dst_image.getPointer(), src_offset, MemoryUtil.getAddress(dst_origin), MemoryUtil.getAddress(region), (event_wait_list == null ? 0 : event_wait_list.remaining()), MemoryUtil.getAddressSafe(event_wait_list), MemoryUtil.getAddressSafe(event), function_pointer); if ( __result == CL_SUCCESS ) command_queue.registerCLEvent(event); return __result; } static native int nclEnqueueCopyBufferToImage(long command_queue, long src_buffer, long dst_image, long src_offset, long dst_origin, long region, int event_wait_list_num_events_in_wait_list, long event_wait_list, long event, long function_pointer); public static ByteBuffer clEnqueueMapImage(CLCommandQueue command_queue, CLMem image, int blocking_map, long map_flags, PointerBuffer origin, PointerBuffer region, PointerBuffer image_row_pitch, PointerBuffer image_slice_pitch, PointerBuffer event_wait_list, PointerBuffer event, IntBuffer errcode_ret) { long function_pointer = CLCapabilities.clEnqueueMapImage; BufferChecks.checkFunctionAddress(function_pointer); BufferChecks.checkBuffer(origin, 3); BufferChecks.checkBuffer(region, 3); BufferChecks.checkBuffer(image_row_pitch, 1); if (image_slice_pitch != null) BufferChecks.checkBuffer(image_slice_pitch, 1); if (event_wait_list != null) BufferChecks.checkDirect(event_wait_list); if (event != null) BufferChecks.checkBuffer(event, 1); if (errcode_ret != null) BufferChecks.checkBuffer(errcode_ret, 1); ByteBuffer __result = nclEnqueueMapImage(command_queue.getPointer(), image.getPointer(), blocking_map, map_flags, MemoryUtil.getAddress(origin), MemoryUtil.getAddress(region), MemoryUtil.getAddress(image_row_pitch), MemoryUtil.getAddressSafe(image_slice_pitch), (event_wait_list == null ? 0 : event_wait_list.remaining()), MemoryUtil.getAddressSafe(event_wait_list), MemoryUtil.getAddressSafe(event), MemoryUtil.getAddressSafe(errcode_ret), function_pointer); if ( __result != null ) command_queue.registerCLEvent(event); return LWJGLUtil.CHECKS && __result == null ? null : __result.order(ByteOrder.nativeOrder()); } static native ByteBuffer nclEnqueueMapImage(long command_queue, long image, int blocking_map, long map_flags, long origin, long region, long image_row_pitch, long image_slice_pitch, int event_wait_list_num_events_in_wait_list, long event_wait_list, long event, long errcode_ret, long function_pointer); public static int clGetImageInfo(CLMem image, int param_name, ByteBuffer param_value, PointerBuffer param_value_size_ret) { long function_pointer = CLCapabilities.clGetImageInfo; BufferChecks.checkFunctionAddress(function_pointer); if (param_value != null) BufferChecks.checkDirect(param_value); if (param_value_size_ret != null) BufferChecks.checkBuffer(param_value_size_ret, 1); int __result = nclGetImageInfo(image.getPointer(), param_name, (param_value == null ? 0 : param_value.remaining()), MemoryUtil.getAddressSafe(param_value), MemoryUtil.getAddressSafe(param_value_size_ret), function_pointer); return __result; } static native int nclGetImageInfo(long image, int param_name, long param_value_param_value_size, long param_value, long param_value_size_ret, long function_pointer); public static int clRetainMemObject(CLMem memobj) { long function_pointer = CLCapabilities.clRetainMemObject; BufferChecks.checkFunctionAddress(function_pointer); int __result = nclRetainMemObject(memobj.getPointer(), function_pointer); if ( __result == CL_SUCCESS ) memobj.retain(); return __result; } static native int nclRetainMemObject(long memobj, long function_pointer); public static int clReleaseMemObject(CLMem memobj) { long function_pointer = CLCapabilities.clReleaseMemObject; BufferChecks.checkFunctionAddress(function_pointer); int __result = nclReleaseMemObject(memobj.getPointer(), function_pointer); if ( __result == CL_SUCCESS ) memobj.release(); return __result; } static native int nclReleaseMemObject(long memobj, long function_pointer); public static int clEnqueueUnmapMemObject(CLCommandQueue command_queue, CLMem memobj, ByteBuffer mapped_ptr, PointerBuffer event_wait_list, PointerBuffer event) { long function_pointer = CLCapabilities.clEnqueueUnmapMemObject; BufferChecks.checkFunctionAddress(function_pointer); BufferChecks.checkDirect(mapped_ptr); if (event_wait_list != null) BufferChecks.checkDirect(event_wait_list); if (event != null) BufferChecks.checkBuffer(event, 1); int __result = nclEnqueueUnmapMemObject(command_queue.getPointer(), memobj.getPointer(), MemoryUtil.getAddress(mapped_ptr), (event_wait_list == null ? 0 : event_wait_list.remaining()), MemoryUtil.getAddressSafe(event_wait_list), MemoryUtil.getAddressSafe(event), function_pointer); if ( __result == CL_SUCCESS ) command_queue.registerCLEvent(event); return __result; } static native int nclEnqueueUnmapMemObject(long command_queue, long memobj, long mapped_ptr, int event_wait_list_num_events_in_wait_list, long event_wait_list, long event, long function_pointer); public static int clGetMemObjectInfo(CLMem memobj, int param_name, ByteBuffer param_value, PointerBuffer param_value_size_ret) { long function_pointer = CLCapabilities.clGetMemObjectInfo; BufferChecks.checkFunctionAddress(function_pointer); if (param_value != null) BufferChecks.checkDirect(param_value); if (param_value_size_ret != null) BufferChecks.checkBuffer(param_value_size_ret, 1); int __result = nclGetMemObjectInfo(memobj.getPointer(), param_name, (param_value == null ? 0 : param_value.remaining()), MemoryUtil.getAddressSafe(param_value), MemoryUtil.getAddressSafe(param_value_size_ret), function_pointer); return __result; } static native int nclGetMemObjectInfo(long memobj, int param_name, long param_value_param_value_size, long param_value, long param_value_size_ret, long function_pointer); public static CLSampler clCreateSampler(CLContext context, int normalized_coords, int addressing_mode, int filter_mode, IntBuffer errcode_ret) { long function_pointer = CLCapabilities.clCreateSampler; BufferChecks.checkFunctionAddress(function_pointer); if (errcode_ret != null) BufferChecks.checkBuffer(errcode_ret, 1); CLSampler __result = new CLSampler(nclCreateSampler(context.getPointer(), normalized_coords, addressing_mode, filter_mode, MemoryUtil.getAddressSafe(errcode_ret), function_pointer), context); return __result; } static native long nclCreateSampler(long context, int normalized_coords, int addressing_mode, int filter_mode, long errcode_ret, long function_pointer); public static int clRetainSampler(CLSampler sampler) { long function_pointer = CLCapabilities.clRetainSampler; BufferChecks.checkFunctionAddress(function_pointer); int __result = nclRetainSampler(sampler.getPointer(), function_pointer); if ( __result == CL_SUCCESS ) sampler.retain(); return __result; } static native int nclRetainSampler(long sampler, long function_pointer); public static int clReleaseSampler(CLSampler sampler) { long function_pointer = CLCapabilities.clReleaseSampler; BufferChecks.checkFunctionAddress(function_pointer); int __result = nclReleaseSampler(sampler.getPointer(), function_pointer); if ( __result == CL_SUCCESS ) sampler.release(); return __result; } static native int nclReleaseSampler(long sampler, long function_pointer); public static int clGetSamplerInfo(CLSampler sampler, int param_name, ByteBuffer param_value, PointerBuffer param_value_size_ret) { long function_pointer = CLCapabilities.clGetSamplerInfo; BufferChecks.checkFunctionAddress(function_pointer); if (param_value != null) BufferChecks.checkDirect(param_value); if (param_value_size_ret != null) BufferChecks.checkBuffer(param_value_size_ret, 1); int __result = nclGetSamplerInfo(sampler.getPointer(), param_name, (param_value == null ? 0 : param_value.remaining()), MemoryUtil.getAddressSafe(param_value), MemoryUtil.getAddressSafe(param_value_size_ret), function_pointer); return __result; } static native int nclGetSamplerInfo(long sampler, int param_name, long param_value_param_value_size, long param_value, long param_value_size_ret, long function_pointer); public static CLProgram clCreateProgramWithSource(CLContext context, ByteBuffer string, IntBuffer errcode_ret) { long function_pointer = CLCapabilities.clCreateProgramWithSource; BufferChecks.checkFunctionAddress(function_pointer); BufferChecks.checkDirect(string); if (errcode_ret != null) BufferChecks.checkBuffer(errcode_ret, 1); CLProgram __result = new CLProgram(nclCreateProgramWithSource(context.getPointer(), 1, MemoryUtil.getAddress(string), string.remaining(), MemoryUtil.getAddressSafe(errcode_ret), function_pointer), context); return __result; } static native long nclCreateProgramWithSource(long context, int count, long string, long string_lengths, long errcode_ret, long function_pointer); /** Overloads clCreateProgramWithSource. */ public static CLProgram clCreateProgramWithSource(CLContext context, ByteBuffer strings, PointerBuffer lengths, IntBuffer errcode_ret) { long function_pointer = CLCapabilities.clCreateProgramWithSource; BufferChecks.checkFunctionAddress(function_pointer); BufferChecks.checkBuffer(strings, APIUtil.getSize(lengths)); BufferChecks.checkBuffer(lengths, 1); if (errcode_ret != null) BufferChecks.checkBuffer(errcode_ret, 1); CLProgram __result = new CLProgram(nclCreateProgramWithSource2(context.getPointer(), lengths.remaining(), MemoryUtil.getAddress(strings), MemoryUtil.getAddress(lengths), MemoryUtil.getAddressSafe(errcode_ret), function_pointer), context); return __result; } static native long nclCreateProgramWithSource2(long context, int lengths_count, long strings, long lengths, long errcode_ret, long function_pointer); /** Overloads clCreateProgramWithSource. */ public static CLProgram clCreateProgramWithSource(CLContext context, ByteBuffer[] strings, IntBuffer errcode_ret) { long function_pointer = CLCapabilities.clCreateProgramWithSource; BufferChecks.checkFunctionAddress(function_pointer); BufferChecks.checkArray(strings, 1); if (errcode_ret != null) BufferChecks.checkBuffer(errcode_ret, 1); CLProgram __result = new CLProgram(nclCreateProgramWithSource3(context.getPointer(), strings.length, strings, APIUtil.getLengths(strings), MemoryUtil.getAddressSafe(errcode_ret), function_pointer), context); return __result; } static native long nclCreateProgramWithSource3(long context, int count, ByteBuffer[] strings, long lengths, long errcode_ret, long function_pointer); /** Overloads clCreateProgramWithSource. */ public static CLProgram clCreateProgramWithSource(CLContext context, CharSequence string, IntBuffer errcode_ret) { long function_pointer = CLCapabilities.clCreateProgramWithSource; BufferChecks.checkFunctionAddress(function_pointer); if (errcode_ret != null) BufferChecks.checkBuffer(errcode_ret, 1); CLProgram __result = new CLProgram(nclCreateProgramWithSource(context.getPointer(), 1, APIUtil.getBuffer(string), string.length(), MemoryUtil.getAddressSafe(errcode_ret), function_pointer), context); return __result; } /** Overloads clCreateProgramWithSource. */ public static CLProgram clCreateProgramWithSource(CLContext context, CharSequence[] strings, IntBuffer errcode_ret) { long function_pointer = CLCapabilities.clCreateProgramWithSource; BufferChecks.checkFunctionAddress(function_pointer); BufferChecks.checkArray(strings); if (errcode_ret != null) BufferChecks.checkBuffer(errcode_ret, 1); CLProgram __result = new CLProgram(nclCreateProgramWithSource4(context.getPointer(), strings.length, APIUtil.getBuffer(strings), APIUtil.getLengths(strings), MemoryUtil.getAddressSafe(errcode_ret), function_pointer), context); return __result; } static native long nclCreateProgramWithSource4(long context, int count, long strings, long lengths, long errcode_ret, long function_pointer); public static CLProgram clCreateProgramWithBinary(CLContext context, CLDevice device, ByteBuffer binary, IntBuffer binary_status, IntBuffer errcode_ret) { long function_pointer = CLCapabilities.clCreateProgramWithBinary; BufferChecks.checkFunctionAddress(function_pointer); BufferChecks.checkDirect(binary); BufferChecks.checkBuffer(binary_status, 1); if (errcode_ret != null) BufferChecks.checkBuffer(errcode_ret, 1); CLProgram __result = new CLProgram(nclCreateProgramWithBinary(context.getPointer(), 1, device.getPointer(), binary.remaining(), MemoryUtil.getAddress(binary), MemoryUtil.getAddress(binary_status), MemoryUtil.getAddressSafe(errcode_ret), function_pointer), context); return __result; } static native long nclCreateProgramWithBinary(long context, int num_devices, long device, long binary_lengths, long binary, long binary_status, long errcode_ret, long function_pointer); /** Overloads clCreateProgramWithBinary. */ public static CLProgram clCreateProgramWithBinary(CLContext context, PointerBuffer device_list, PointerBuffer lengths, ByteBuffer binaries, IntBuffer binary_status, IntBuffer errcode_ret) { long function_pointer = CLCapabilities.clCreateProgramWithBinary; BufferChecks.checkFunctionAddress(function_pointer); BufferChecks.checkBuffer(device_list, 1); BufferChecks.checkBuffer(lengths, device_list.remaining()); BufferChecks.checkBuffer(binaries, APIUtil.getSize(lengths)); BufferChecks.checkBuffer(binary_status, device_list.remaining()); if (errcode_ret != null) BufferChecks.checkBuffer(errcode_ret, 1); CLProgram __result = new CLProgram(nclCreateProgramWithBinary2(context.getPointer(), device_list.remaining(), MemoryUtil.getAddress(device_list), MemoryUtil.getAddress(lengths), MemoryUtil.getAddress(binaries), MemoryUtil.getAddress(binary_status), MemoryUtil.getAddressSafe(errcode_ret), function_pointer), context); return __result; } static native long nclCreateProgramWithBinary2(long context, int device_list_num_devices, long device_list, long lengths, long binaries, long binary_status, long errcode_ret, long function_pointer); /** Overloads clCreateProgramWithBinary. */ public static CLProgram clCreateProgramWithBinary(CLContext context, PointerBuffer device_list, ByteBuffer[] binaries, IntBuffer binary_status, IntBuffer errcode_ret) { long function_pointer = CLCapabilities.clCreateProgramWithBinary; BufferChecks.checkFunctionAddress(function_pointer); BufferChecks.checkBuffer(device_list, binaries.length); BufferChecks.checkArray(binaries, 1); BufferChecks.checkBuffer(binary_status, binaries.length); if (errcode_ret != null) BufferChecks.checkBuffer(errcode_ret, 1); CLProgram __result = new CLProgram(nclCreateProgramWithBinary3(context.getPointer(), binaries.length, MemoryUtil.getAddress(device_list), APIUtil.getLengths(binaries), binaries, MemoryUtil.getAddress(binary_status), MemoryUtil.getAddressSafe(errcode_ret), function_pointer), context); return __result; } static native long nclCreateProgramWithBinary3(long context, int num_devices, long device_list, long lengths, ByteBuffer[] binaries, long binary_status, long errcode_ret, long function_pointer); public static int clRetainProgram(CLProgram program) { long function_pointer = CLCapabilities.clRetainProgram; BufferChecks.checkFunctionAddress(function_pointer); int __result = nclRetainProgram(program.getPointer(), function_pointer); if ( __result == CL_SUCCESS ) program.retain(); return __result; } static native int nclRetainProgram(long program, long function_pointer); public static int clReleaseProgram(CLProgram program) { long function_pointer = CLCapabilities.clReleaseProgram; BufferChecks.checkFunctionAddress(function_pointer); APIUtil.releaseObjects(program); int __result = nclReleaseProgram(program.getPointer(), function_pointer); if ( __result == CL_SUCCESS ) program.release(); return __result; } static native int nclReleaseProgram(long program, long function_pointer); public static int clBuildProgram(CLProgram program, PointerBuffer device_list, ByteBuffer options, CLBuildProgramCallback pfn_notify) { long function_pointer = CLCapabilities.clBuildProgram; BufferChecks.checkFunctionAddress(function_pointer); if (device_list != null) BufferChecks.checkDirect(device_list); BufferChecks.checkDirect(options); BufferChecks.checkNullTerminated(options); long user_data = CallbackUtil.createGlobalRef(pfn_notify); if ( pfn_notify != null ) pfn_notify.setContext(program.getParent()); int __result = 0; try { __result = nclBuildProgram(program.getPointer(), (device_list == null ? 0 : device_list.remaining()), MemoryUtil.getAddressSafe(device_list), MemoryUtil.getAddress(options), pfn_notify == null ? 0 : pfn_notify.getPointer(), user_data, function_pointer); return __result; } finally { CallbackUtil.checkCallback(__result, user_data); } } static native int nclBuildProgram(long program, int device_list_num_devices, long device_list, long options, long pfn_notify, long user_data, long function_pointer); /** Overloads clBuildProgram. */ public static int clBuildProgram(CLProgram program, PointerBuffer device_list, CharSequence options, CLBuildProgramCallback pfn_notify) { long function_pointer = CLCapabilities.clBuildProgram; BufferChecks.checkFunctionAddress(function_pointer); if (device_list != null) BufferChecks.checkDirect(device_list); long user_data = CallbackUtil.createGlobalRef(pfn_notify); if ( pfn_notify != null ) pfn_notify.setContext(program.getParent()); int __result = 0; try { __result = nclBuildProgram(program.getPointer(), (device_list == null ? 0 : device_list.remaining()), MemoryUtil.getAddressSafe(device_list), APIUtil.getBufferNT(options), pfn_notify == null ? 0 : pfn_notify.getPointer(), user_data, function_pointer); return __result; } finally { CallbackUtil.checkCallback(__result, user_data); } } /** Overloads clBuildProgram. */ public static int clBuildProgram(CLProgram program, CLDevice device, CharSequence options, CLBuildProgramCallback pfn_notify) { long function_pointer = CLCapabilities.clBuildProgram; BufferChecks.checkFunctionAddress(function_pointer); long user_data = CallbackUtil.createGlobalRef(pfn_notify); if ( pfn_notify != null ) pfn_notify.setContext(program.getParent()); int __result = 0; try { __result = nclBuildProgram(program.getPointer(), 1, APIUtil.getPointer(device), APIUtil.getBufferNT(options), pfn_notify == null ? 0 : pfn_notify.getPointer(), user_data, function_pointer); return __result; } finally { CallbackUtil.checkCallback(__result, user_data); } } public static int clUnloadCompiler() { long function_pointer = CLCapabilities.clUnloadCompiler; BufferChecks.checkFunctionAddress(function_pointer); int __result = nclUnloadCompiler(function_pointer); return __result; } static native int nclUnloadCompiler(long function_pointer); public static int clGetProgramInfo(CLProgram program, int param_name, ByteBuffer param_value, PointerBuffer param_value_size_ret) { long function_pointer = CLCapabilities.clGetProgramInfo; BufferChecks.checkFunctionAddress(function_pointer); if (param_value != null) BufferChecks.checkDirect(param_value); if (param_value_size_ret != null) BufferChecks.checkBuffer(param_value_size_ret, 1); int __result = nclGetProgramInfo(program.getPointer(), param_name, (param_value == null ? 0 : param_value.remaining()), MemoryUtil.getAddressSafe(param_value), MemoryUtil.getAddressSafe(param_value_size_ret), function_pointer); return __result; } static native int nclGetProgramInfo(long program, int param_name, long param_value_param_value_size, long param_value, long param_value_size_ret, long function_pointer); /** * Overloads clGetProgramInfo. * <p> * This method can be used to get program binaries. The binary for each device (in the * order returned by <code>CL_PROGRAM_DEVICES</code>) will be written sequentially to * the <code>param_value</code> buffer. The buffer size must be big enough to hold * all the binaries, as returned by <code>CL_PROGRAM_BINARY_SIZES</code>. * <p> * @param program the program * @param param_value the buffers where the binaries will be written to. * @param param_value_size_ret optional size result * <p> * @return the error code */ public static int clGetProgramInfo(CLProgram program, PointerBuffer sizes, ByteBuffer param_value, PointerBuffer param_value_size_ret) { long function_pointer = CLCapabilities.clGetProgramInfo; BufferChecks.checkFunctionAddress(function_pointer); BufferChecks.checkBuffer(sizes, 1); BufferChecks.checkBuffer(param_value, APIUtil.getSize(sizes)); if (param_value_size_ret != null) BufferChecks.checkBuffer(param_value_size_ret, 1); int __result = nclGetProgramInfo2(program.getPointer(), CL_PROGRAM_BINARIES, sizes.remaining(), MemoryUtil.getAddress(sizes), MemoryUtil.getAddress(param_value), MemoryUtil.getAddressSafe(param_value_size_ret), function_pointer); return __result; } static native int nclGetProgramInfo2(long program, int param_name, long sizes_len, long sizes, long param_value, long param_value_size_ret, long function_pointer); /** * Overloads clGetProgramInfo. * <p> * This method can be used to get program binaries. The binary for each device (in the * order returned by <code>CL_PROGRAM_DEVICES</code>) will be written to the corresponding * slot of the <code>param_value</code> array. The size of each buffer must be big enough to * hold the corresponding binary, as returned by <code>CL_PROGRAM_BINARY_SIZES</code>. * <p> * @param program the program * @param param_value the buffers where the binaries will be written to. * @param param_value_size_ret optional size result * <p> * @return the error code */ public static int clGetProgramInfo(CLProgram program, ByteBuffer[] param_value, PointerBuffer param_value_size_ret) { long function_pointer = CLCapabilities.clGetProgramInfo; BufferChecks.checkFunctionAddress(function_pointer); BufferChecks.checkArray(param_value); if (param_value_size_ret != null) BufferChecks.checkBuffer(param_value_size_ret, 1); int __result = nclGetProgramInfo3(program.getPointer(), CL_PROGRAM_BINARIES, param_value.length, param_value, MemoryUtil.getAddressSafe(param_value_size_ret), function_pointer); return __result; } static native int nclGetProgramInfo3(long program, int param_name, long param_value_len, ByteBuffer[] param_value, long param_value_size_ret, long function_pointer); public static int clGetProgramBuildInfo(CLProgram program, CLDevice device, int param_name, ByteBuffer param_value, PointerBuffer param_value_size_ret) { long function_pointer = CLCapabilities.clGetProgramBuildInfo; BufferChecks.checkFunctionAddress(function_pointer); if (param_value != null) BufferChecks.checkDirect(param_value); if (param_value_size_ret != null) BufferChecks.checkBuffer(param_value_size_ret, 1); int __result = nclGetProgramBuildInfo(program.getPointer(), device.getPointer(), param_name, (param_value == null ? 0 : param_value.remaining()), MemoryUtil.getAddressSafe(param_value), MemoryUtil.getAddressSafe(param_value_size_ret), function_pointer); return __result; } static native int nclGetProgramBuildInfo(long program, long device, int param_name, long param_value_param_value_size, long param_value, long param_value_size_ret, long function_pointer); public static CLKernel clCreateKernel(CLProgram program, ByteBuffer kernel_name, IntBuffer errcode_ret) { long function_pointer = CLCapabilities.clCreateKernel; BufferChecks.checkFunctionAddress(function_pointer); BufferChecks.checkDirect(kernel_name); BufferChecks.checkNullTerminated(kernel_name); if (errcode_ret != null) BufferChecks.checkBuffer(errcode_ret, 1); CLKernel __result = new CLKernel(nclCreateKernel(program.getPointer(), MemoryUtil.getAddress(kernel_name), MemoryUtil.getAddressSafe(errcode_ret), function_pointer), program); return __result; } static native long nclCreateKernel(long program, long kernel_name, long errcode_ret, long function_pointer); /** Overloads clCreateKernel. */ public static CLKernel clCreateKernel(CLProgram program, CharSequence kernel_name, IntBuffer errcode_ret) { long function_pointer = CLCapabilities.clCreateKernel; BufferChecks.checkFunctionAddress(function_pointer); if (errcode_ret != null) BufferChecks.checkBuffer(errcode_ret, 1); CLKernel __result = new CLKernel(nclCreateKernel(program.getPointer(), APIUtil.getBufferNT(kernel_name), MemoryUtil.getAddressSafe(errcode_ret), function_pointer), program); return __result; } public static int clCreateKernelsInProgram(CLProgram program, PointerBuffer kernels, IntBuffer num_kernels_ret) { long function_pointer = CLCapabilities.clCreateKernelsInProgram; BufferChecks.checkFunctionAddress(function_pointer); if (kernels != null) BufferChecks.checkDirect(kernels); if (num_kernels_ret != null) BufferChecks.checkBuffer(num_kernels_ret, 1); int __result = nclCreateKernelsInProgram(program.getPointer(), (kernels == null ? 0 : kernels.remaining()), MemoryUtil.getAddressSafe(kernels), MemoryUtil.getAddressSafe(num_kernels_ret), function_pointer); if ( __result == CL_SUCCESS && kernels != null ) program.registerCLKernels(kernels); return __result; } static native int nclCreateKernelsInProgram(long program, int kernels_num_kernels, long kernels, long num_kernels_ret, long function_pointer); public static int clRetainKernel(CLKernel kernel) { long function_pointer = CLCapabilities.clRetainKernel; BufferChecks.checkFunctionAddress(function_pointer); int __result = nclRetainKernel(kernel.getPointer(), function_pointer); if ( __result == CL_SUCCESS ) kernel.retain(); return __result; } static native int nclRetainKernel(long kernel, long function_pointer); public static int clReleaseKernel(CLKernel kernel) { long function_pointer = CLCapabilities.clReleaseKernel; BufferChecks.checkFunctionAddress(function_pointer); int __result = nclReleaseKernel(kernel.getPointer(), function_pointer); if ( __result == CL_SUCCESS ) kernel.release(); return __result; } static native int nclReleaseKernel(long kernel, long function_pointer); public static int clSetKernelArg(CLKernel kernel, int arg_index, long arg_value_arg_size) { long function_pointer = CLCapabilities.clSetKernelArg; BufferChecks.checkFunctionAddress(function_pointer); int __result = nclSetKernelArg(kernel.getPointer(), arg_index, arg_value_arg_size, 0L, function_pointer); return __result; } public static int clSetKernelArg(CLKernel kernel, int arg_index, ByteBuffer arg_value) { long function_pointer = CLCapabilities.clSetKernelArg; BufferChecks.checkFunctionAddress(function_pointer); BufferChecks.checkDirect(arg_value); int __result = nclSetKernelArg(kernel.getPointer(), arg_index, arg_value.remaining(), MemoryUtil.getAddress(arg_value), function_pointer); return __result; } public static int clSetKernelArg(CLKernel kernel, int arg_index, DoubleBuffer arg_value) { long function_pointer = CLCapabilities.clSetKernelArg; BufferChecks.checkFunctionAddress(function_pointer); BufferChecks.checkDirect(arg_value); int __result = nclSetKernelArg(kernel.getPointer(), arg_index, (arg_value.remaining() << 3), MemoryUtil.getAddress(arg_value), function_pointer); return __result; } public static int clSetKernelArg(CLKernel kernel, int arg_index, FloatBuffer arg_value) { long function_pointer = CLCapabilities.clSetKernelArg; BufferChecks.checkFunctionAddress(function_pointer); BufferChecks.checkDirect(arg_value); int __result = nclSetKernelArg(kernel.getPointer(), arg_index, (arg_value.remaining() << 2), MemoryUtil.getAddress(arg_value), function_pointer); return __result; } public static int clSetKernelArg(CLKernel kernel, int arg_index, IntBuffer arg_value) { long function_pointer = CLCapabilities.clSetKernelArg; BufferChecks.checkFunctionAddress(function_pointer); BufferChecks.checkDirect(arg_value); int __result = nclSetKernelArg(kernel.getPointer(), arg_index, (arg_value.remaining() << 2), MemoryUtil.getAddress(arg_value), function_pointer); return __result; } public static int clSetKernelArg(CLKernel kernel, int arg_index, LongBuffer arg_value) { long function_pointer = CLCapabilities.clSetKernelArg; BufferChecks.checkFunctionAddress(function_pointer); BufferChecks.checkDirect(arg_value); int __result = nclSetKernelArg(kernel.getPointer(), arg_index, (arg_value.remaining() << 3), MemoryUtil.getAddress(arg_value), function_pointer); return __result; } public static int clSetKernelArg(CLKernel kernel, int arg_index, ShortBuffer arg_value) { long function_pointer = CLCapabilities.clSetKernelArg; BufferChecks.checkFunctionAddress(function_pointer); BufferChecks.checkDirect(arg_value); int __result = nclSetKernelArg(kernel.getPointer(), arg_index, (arg_value.remaining() << 1), MemoryUtil.getAddress(arg_value), function_pointer); return __result; } static native int nclSetKernelArg(long kernel, int arg_index, long arg_value_arg_size, long arg_value, long function_pointer); /** Overloads clSetKernelArg. */ public static int clSetKernelArg(CLKernel kernel, int arg_index, CLObject arg_value) { long function_pointer = CLCapabilities.clSetKernelArg; BufferChecks.checkFunctionAddress(function_pointer); int __result = nclSetKernelArg(kernel.getPointer(), arg_index, PointerBuffer.getPointerSize(), APIUtil.getPointerSafe(arg_value), function_pointer); return __result; } /** Overloads clSetKernelArg. */ static int clSetKernelArg(CLKernel kernel, int arg_index, long arg_size, Buffer arg_value) { long function_pointer = CLCapabilities.clSetKernelArg; BufferChecks.checkFunctionAddress(function_pointer); int __result = nclSetKernelArg(kernel.getPointer(), arg_index, arg_size, MemoryUtil.getAddress0(arg_value), function_pointer); return __result; } public static int clGetKernelInfo(CLKernel kernel, int param_name, ByteBuffer param_value, PointerBuffer param_value_size_ret) { long function_pointer = CLCapabilities.clGetKernelInfo; BufferChecks.checkFunctionAddress(function_pointer); if (param_value != null) BufferChecks.checkDirect(param_value); if (param_value_size_ret != null) BufferChecks.checkBuffer(param_value_size_ret, 1); int __result = nclGetKernelInfo(kernel.getPointer(), param_name, (param_value == null ? 0 : param_value.remaining()), MemoryUtil.getAddressSafe(param_value), MemoryUtil.getAddressSafe(param_value_size_ret), function_pointer); return __result; } static native int nclGetKernelInfo(long kernel, int param_name, long param_value_param_value_size, long param_value, long param_value_size_ret, long function_pointer); public static int clGetKernelWorkGroupInfo(CLKernel kernel, CLDevice device, int param_name, ByteBuffer param_value, PointerBuffer param_value_size_ret) { long function_pointer = CLCapabilities.clGetKernelWorkGroupInfo; BufferChecks.checkFunctionAddress(function_pointer); if (param_value != null) BufferChecks.checkDirect(param_value); if (param_value_size_ret != null) BufferChecks.checkBuffer(param_value_size_ret, 1); int __result = nclGetKernelWorkGroupInfo(kernel.getPointer(), device == null ? 0 : device.getPointer(), param_name, (param_value == null ? 0 : param_value.remaining()), MemoryUtil.getAddressSafe(param_value), MemoryUtil.getAddressSafe(param_value_size_ret), function_pointer); return __result; } static native int nclGetKernelWorkGroupInfo(long kernel, long device, int param_name, long param_value_param_value_size, long param_value, long param_value_size_ret, long function_pointer); public static int clEnqueueNDRangeKernel(CLCommandQueue command_queue, CLKernel kernel, int work_dim, PointerBuffer global_work_offset, PointerBuffer global_work_size, PointerBuffer local_work_size, PointerBuffer event_wait_list, PointerBuffer event) { long function_pointer = CLCapabilities.clEnqueueNDRangeKernel; BufferChecks.checkFunctionAddress(function_pointer); if (global_work_offset != null) BufferChecks.checkBuffer(global_work_offset, work_dim); if (global_work_size != null) BufferChecks.checkBuffer(global_work_size, work_dim); if (local_work_size != null) BufferChecks.checkBuffer(local_work_size, work_dim); if (event_wait_list != null) BufferChecks.checkDirect(event_wait_list); if (event != null) BufferChecks.checkBuffer(event, 1); int __result = nclEnqueueNDRangeKernel(command_queue.getPointer(), kernel.getPointer(), work_dim, MemoryUtil.getAddressSafe(global_work_offset), MemoryUtil.getAddressSafe(global_work_size), MemoryUtil.getAddressSafe(local_work_size), (event_wait_list == null ? 0 : event_wait_list.remaining()), MemoryUtil.getAddressSafe(event_wait_list), MemoryUtil.getAddressSafe(event), function_pointer); if ( __result == CL_SUCCESS ) command_queue.registerCLEvent(event); return __result; } static native int nclEnqueueNDRangeKernel(long command_queue, long kernel, int work_dim, long global_work_offset, long global_work_size, long local_work_size, int event_wait_list_num_events_in_wait_list, long event_wait_list, long event, long function_pointer); public static int clEnqueueTask(CLCommandQueue command_queue, CLKernel kernel, PointerBuffer event_wait_list, PointerBuffer event) { long function_pointer = CLCapabilities.clEnqueueTask; BufferChecks.checkFunctionAddress(function_pointer); if (event_wait_list != null) BufferChecks.checkDirect(event_wait_list); if (event != null) BufferChecks.checkBuffer(event, 1); int __result = nclEnqueueTask(command_queue.getPointer(), kernel.getPointer(), (event_wait_list == null ? 0 : event_wait_list.remaining()), MemoryUtil.getAddressSafe(event_wait_list), MemoryUtil.getAddressSafe(event), function_pointer); if ( __result == CL_SUCCESS ) command_queue.registerCLEvent(event); return __result; } static native int nclEnqueueTask(long command_queue, long kernel, int event_wait_list_num_events_in_wait_list, long event_wait_list, long event, long function_pointer); /** * Enqueues a native kernel to the specified command queue. The <code>mem_list</code> parameter * can be used to pass a list of <code>CLMem</code> objects that will be mapped to global memory space and * exposed as a <code>ByteBuffer</code> array in the <code>CLNativeKernel#execute</code> method. The * <code>sizes</code> parameter will be used to allocate direct <code>ByteBuffer</code>s with the correct * capacities. The user is responsible for passing appropriate values to avoid crashes. * <p> * @param command_queue the command queue * @param user_func the native kernel * @param mem_list the CLMem objects * @param sizes the CLMem object sizes * @param event_wait_list the event wait list * @param event the queue event * <p> * @return the error code */ public static int clEnqueueNativeKernel(CLCommandQueue command_queue, CLNativeKernel user_func, CLMem[] mem_list, long[] sizes, PointerBuffer event_wait_list, PointerBuffer event) { long function_pointer = CLCapabilities.clEnqueueNativeKernel; BufferChecks.checkFunctionAddress(function_pointer); if (mem_list != null) BufferChecks.checkArray(mem_list, 1); if (sizes != null) BufferChecks.checkArray(sizes, mem_list.length); if (event_wait_list != null) BufferChecks.checkDirect(event_wait_list); if (event != null) BufferChecks.checkBuffer(event, 1); long user_func_ref = CallbackUtil.createGlobalRef(user_func); ByteBuffer args = APIUtil.getNativeKernelArgs(user_func_ref, mem_list, sizes); int __result = 0; try { __result = nclEnqueueNativeKernel(command_queue.getPointer(), user_func.getPointer(), MemoryUtil.getAddress0(args), args.remaining(), mem_list == null ? 0 : mem_list.length, mem_list, (event_wait_list == null ? 0 : event_wait_list.remaining()), MemoryUtil.getAddressSafe(event_wait_list), MemoryUtil.getAddressSafe(event), function_pointer); if ( __result == CL_SUCCESS ) command_queue.registerCLEvent(event); return __result; } finally { CallbackUtil.checkCallback(__result, user_func_ref); } } static native int nclEnqueueNativeKernel(long command_queue, long user_func, long args, long args_cb_args, int num_mem_objects, CLMem[] mem_list, int event_wait_list_num_events_in_wait_list, long event_wait_list, long event, long function_pointer); public static int clWaitForEvents(PointerBuffer event_list) { long function_pointer = CLCapabilities.clWaitForEvents; BufferChecks.checkFunctionAddress(function_pointer); BufferChecks.checkBuffer(event_list, 1); int __result = nclWaitForEvents(event_list.remaining(), MemoryUtil.getAddress(event_list), function_pointer); return __result; } static native int nclWaitForEvents(int event_list_num_events, long event_list, long function_pointer); /** Overloads clWaitForEvents. */ public static int clWaitForEvents(CLEvent event) { long function_pointer = CLCapabilities.clWaitForEvents; BufferChecks.checkFunctionAddress(function_pointer); int __result = nclWaitForEvents(1, APIUtil.getPointer(event), function_pointer); return __result; } public static int clGetEventInfo(CLEvent event, int param_name, ByteBuffer param_value, PointerBuffer param_value_size_ret) { long function_pointer = CLCapabilities.clGetEventInfo; BufferChecks.checkFunctionAddress(function_pointer); if (param_value != null) BufferChecks.checkDirect(param_value); if (param_value_size_ret != null) BufferChecks.checkBuffer(param_value_size_ret, 1); int __result = nclGetEventInfo(event.getPointer(), param_name, (param_value == null ? 0 : param_value.remaining()), MemoryUtil.getAddressSafe(param_value), MemoryUtil.getAddressSafe(param_value_size_ret), function_pointer); return __result; } static native int nclGetEventInfo(long event, int param_name, long param_value_param_value_size, long param_value, long param_value_size_ret, long function_pointer); public static int clRetainEvent(CLEvent event) { long function_pointer = CLCapabilities.clRetainEvent; BufferChecks.checkFunctionAddress(function_pointer); int __result = nclRetainEvent(event.getPointer(), function_pointer); if ( __result == CL_SUCCESS ) event.retain(); return __result; } static native int nclRetainEvent(long event, long function_pointer); public static int clReleaseEvent(CLEvent event) { long function_pointer = CLCapabilities.clReleaseEvent; BufferChecks.checkFunctionAddress(function_pointer); int __result = nclReleaseEvent(event.getPointer(), function_pointer); if ( __result == CL_SUCCESS ) event.release(); return __result; } static native int nclReleaseEvent(long event, long function_pointer); public static int clEnqueueMarker(CLCommandQueue command_queue, PointerBuffer event) { long function_pointer = CLCapabilities.clEnqueueMarker; BufferChecks.checkFunctionAddress(function_pointer); BufferChecks.checkBuffer(event, 1); int __result = nclEnqueueMarker(command_queue.getPointer(), MemoryUtil.getAddress(event), function_pointer); if ( __result == CL_SUCCESS ) command_queue.registerCLEvent(event); return __result; } static native int nclEnqueueMarker(long command_queue, long event, long function_pointer); public static int clEnqueueBarrier(CLCommandQueue command_queue) { long function_pointer = CLCapabilities.clEnqueueBarrier; BufferChecks.checkFunctionAddress(function_pointer); int __result = nclEnqueueBarrier(command_queue.getPointer(), function_pointer); return __result; } static native int nclEnqueueBarrier(long command_queue, long function_pointer); public static int clEnqueueWaitForEvents(CLCommandQueue command_queue, PointerBuffer event_list) { long function_pointer = CLCapabilities.clEnqueueWaitForEvents; BufferChecks.checkFunctionAddress(function_pointer); BufferChecks.checkBuffer(event_list, 1); int __result = nclEnqueueWaitForEvents(command_queue.getPointer(), event_list.remaining(), MemoryUtil.getAddress(event_list), function_pointer); return __result; } static native int nclEnqueueWaitForEvents(long command_queue, int event_list_num_events, long event_list, long function_pointer); /** Overloads clEnqueueWaitForEvents. */ public static int clEnqueueWaitForEvents(CLCommandQueue command_queue, CLEvent event) { long function_pointer = CLCapabilities.clEnqueueWaitForEvents; BufferChecks.checkFunctionAddress(function_pointer); int __result = nclEnqueueWaitForEvents(command_queue.getPointer(), 1, APIUtil.getPointer(event), function_pointer); return __result; } public static int clGetEventProfilingInfo(CLEvent event, int param_name, ByteBuffer param_value, PointerBuffer param_value_size_ret) { long function_pointer = CLCapabilities.clGetEventProfilingInfo; BufferChecks.checkFunctionAddress(function_pointer); if (param_value != null) BufferChecks.checkDirect(param_value); if (param_value_size_ret != null) BufferChecks.checkBuffer(param_value_size_ret, 1); int __result = nclGetEventProfilingInfo(event.getPointer(), param_name, (param_value == null ? 0 : param_value.remaining()), MemoryUtil.getAddressSafe(param_value), MemoryUtil.getAddressSafe(param_value_size_ret), function_pointer); return __result; } static native int nclGetEventProfilingInfo(long event, int param_name, long param_value_param_value_size, long param_value, long param_value_size_ret, long function_pointer); public static int clFlush(CLCommandQueue command_queue) { long function_pointer = CLCapabilities.clFlush; BufferChecks.checkFunctionAddress(function_pointer); int __result = nclFlush(command_queue.getPointer(), function_pointer); return __result; } static native int nclFlush(long command_queue, long function_pointer); public static int clFinish(CLCommandQueue command_queue) { long function_pointer = CLCapabilities.clFinish; BufferChecks.checkFunctionAddress(function_pointer); int __result = nclFinish(command_queue.getPointer(), function_pointer); return __result; } static native int nclFinish(long command_queue, long function_pointer); static CLFunctionAddress clGetExtensionFunctionAddress(ByteBuffer func_name) { long function_pointer = CLCapabilities.clGetExtensionFunctionAddress; BufferChecks.checkFunctionAddress(function_pointer); BufferChecks.checkDirect(func_name); BufferChecks.checkNullTerminated(func_name); CLFunctionAddress __result = new CLFunctionAddress(nclGetExtensionFunctionAddress(MemoryUtil.getAddress(func_name), function_pointer)); return __result; } static native long nclGetExtensionFunctionAddress(long func_name, long function_pointer); /** Overloads clGetExtensionFunctionAddress. */ static CLFunctionAddress clGetExtensionFunctionAddress(CharSequence func_name) { long function_pointer = CLCapabilities.clGetExtensionFunctionAddress; BufferChecks.checkFunctionAddress(function_pointer); CLFunctionAddress __result = new CLFunctionAddress(nclGetExtensionFunctionAddress(APIUtil.getBufferNT(func_name), function_pointer)); return __result; } }
mit
FauxFaux/jdk9-corba
src/java.corba/share/classes/com/sun/corba/se/impl/io/ValueHandlerImpl.java
35698
/* * Copyright (c) 1998, 2012, 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. */ /* * Licensed Materials - Property of IBM * RMI-IIOP v1.0 * Copyright IBM Corp. 1998 1999 All Rights Reserved * */ package com.sun.corba.se.impl.io; import javax.rmi.CORBA.Util; import java.util.Hashtable; import java.io.IOException; import com.sun.corba.se.impl.util.RepositoryId; import com.sun.corba.se.impl.util.Utility; import org.omg.CORBA.TCKind; import org.omg.CORBA.portable.IndirectionException; import com.sun.org.omg.SendingContext.CodeBase; import com.sun.org.omg.SendingContext.CodeBaseHelper; import java.security.AccessController; import java.security.PrivilegedAction; import java.security.PrivilegedExceptionAction; import com.sun.corba.se.spi.logging.CORBALogDomains; import com.sun.corba.se.impl.logging.OMGSystemException; import com.sun.corba.se.impl.logging.UtilSystemException; public final class ValueHandlerImpl implements javax.rmi.CORBA.ValueHandlerMultiFormat { // Property to override our maximum stream format version public static final String FORMAT_VERSION_PROPERTY = "com.sun.CORBA.MaxStreamFormatVersion"; private static final byte MAX_SUPPORTED_FORMAT_VERSION = (byte)2; private static final byte STREAM_FORMAT_VERSION_1 = (byte)1; // The ValueHandler's maximum stream format version to advertise, // set in a static initializer. private static final byte MAX_STREAM_FORMAT_VERSION; static { MAX_STREAM_FORMAT_VERSION = getMaxStreamFormatVersion(); } // Looks for the FORMAT_VERSION_PROPERTY system property // to allow the user to override our default stream format // version. Note that this still only allows them to pick // a supported version (1 through MAX_STREAM_FORMAT_VERSION). private static byte getMaxStreamFormatVersion() { try { String propValue = (String) AccessController.doPrivileged( new PrivilegedAction() { public java.lang.Object run() { return System.getProperty(ValueHandlerImpl.FORMAT_VERSION_PROPERTY); } }); // The property wasn't set if (propValue == null) return MAX_SUPPORTED_FORMAT_VERSION; byte result = Byte.parseByte(propValue); // REVISIT. Just set to MAX_SUPPORTED_FORMAT_VERSION // or really let the system shutdown with this Error? if (result < 1 || result > MAX_SUPPORTED_FORMAT_VERSION) // XXX I18N, logging needed. throw new ExceptionInInitializerError("Invalid stream format version: " + result + ". Valid range is 1 through " + MAX_SUPPORTED_FORMAT_VERSION); return result; } catch (Exception ex) { // REVISIT. Swallow this or really let // the system shutdown with this Error? Error err = new ExceptionInInitializerError(ex); err.initCause( ex ) ; throw err ; } } public static final short kRemoteType = 0; public static final short kAbstractType = 1; public static final short kValueType = 2; private Hashtable inputStreamPairs = null; private Hashtable outputStreamPairs = null; private CodeBase codeBase = null; private boolean useHashtables = true; private boolean isInputStream = true; private IIOPOutputStream outputStreamBridge = null; private IIOPInputStream inputStreamBridge = null; private OMGSystemException omgWrapper = OMGSystemException.get( CORBALogDomains.RPC_ENCODING ) ; private UtilSystemException utilWrapper = UtilSystemException.get( CORBALogDomains.RPC_ENCODING ) ; // See javax.rmi.CORBA.ValueHandlerMultiFormat public byte getMaximumStreamFormatVersion() { return MAX_STREAM_FORMAT_VERSION; } // See javax.rmi.CORBA.ValueHandlerMultiFormat public void writeValue(org.omg.CORBA.portable.OutputStream out, java.io.Serializable value, byte streamFormatVersion) { if (streamFormatVersion == 2) { if (!(out instanceof org.omg.CORBA.portable.ValueOutputStream)) { throw omgWrapper.notAValueoutputstream() ; } } else if (streamFormatVersion != 1) { throw omgWrapper.invalidStreamFormatVersion( new Integer(streamFormatVersion) ) ; } writeValueWithVersion(out, value, streamFormatVersion); } private ValueHandlerImpl(){} private ValueHandlerImpl(boolean isInputStream) { this(); useHashtables = false; this.isInputStream = isInputStream; } static ValueHandlerImpl getInstance() { return new ValueHandlerImpl(); } static ValueHandlerImpl getInstance(boolean isInputStream) { return new ValueHandlerImpl(isInputStream); } /** * Writes the value to the stream using java semantics. * @param out The stream to write the value to * @param value The value to be written to the stream **/ public void writeValue(org.omg.CORBA.portable.OutputStream out, java.io.Serializable value) { writeValueWithVersion(out, value, STREAM_FORMAT_VERSION_1); } private void writeValueWithVersion(org.omg.CORBA.portable.OutputStream _out, java.io.Serializable value, byte streamFormatVersion) { org.omg.CORBA_2_3.portable.OutputStream out = (org.omg.CORBA_2_3.portable.OutputStream) _out; if (!useHashtables) { if (outputStreamBridge == null) { outputStreamBridge = createOutputStream(); outputStreamBridge.setOrbStream(out); } try { outputStreamBridge.increaseRecursionDepth(); writeValueInternal(outputStreamBridge, out, value, streamFormatVersion); } finally { outputStreamBridge.decreaseRecursionDepth(); } return; } IIOPOutputStream jdkToOrbOutputStreamBridge = null; if (outputStreamPairs == null) outputStreamPairs = new Hashtable(); jdkToOrbOutputStreamBridge = (IIOPOutputStream)outputStreamPairs.get(_out); if (jdkToOrbOutputStreamBridge == null) { jdkToOrbOutputStreamBridge = createOutputStream(); jdkToOrbOutputStreamBridge.setOrbStream(out); outputStreamPairs.put(_out, jdkToOrbOutputStreamBridge); } try { jdkToOrbOutputStreamBridge.increaseRecursionDepth(); writeValueInternal(jdkToOrbOutputStreamBridge, out, value, streamFormatVersion); } finally { if (jdkToOrbOutputStreamBridge.decreaseRecursionDepth() == 0) { outputStreamPairs.remove(_out); } } } private void writeValueInternal(IIOPOutputStream bridge, org.omg.CORBA_2_3.portable.OutputStream out, java.io.Serializable value, byte streamFormatVersion) { Class clazz = value.getClass(); if (clazz.isArray()) write_Array(out, value, clazz.getComponentType()); else bridge.simpleWriteObject(value, streamFormatVersion); } /** * Reads a value from the stream using java semantics. * @param in The stream to read the value from * @param clazz The type of the value to be read in * @param rt The sending context runtime **/ public java.io.Serializable readValue(org.omg.CORBA.portable.InputStream in, int offset, java.lang.Class clazz, String repositoryID, org.omg.SendingContext.RunTime rt) { // Must use narrow rather than a direct cast to a com.sun // class. Fix for bug 4379539. CodeBase sender = CodeBaseHelper.narrow(rt); org.omg.CORBA_2_3.portable.InputStream inStream = (org.omg.CORBA_2_3.portable.InputStream) in; if (!useHashtables) { if (inputStreamBridge == null) { inputStreamBridge = createInputStream(); inputStreamBridge.setOrbStream(inStream); inputStreamBridge.setSender(sender); //d11638 // backward compatability 4365188 inputStreamBridge.setValueHandler(this); } java.io.Serializable result = null; try { inputStreamBridge.increaseRecursionDepth(); result = (java.io.Serializable) readValueInternal(inputStreamBridge, inStream, offset, clazz, repositoryID, sender); } finally { if (inputStreamBridge.decreaseRecursionDepth() == 0) { // Indirections are resolved immediately since // the change to the active recursion manager, // so this will never happen. } } return result; } IIOPInputStream jdkToOrbInputStreamBridge = null; if (inputStreamPairs == null) inputStreamPairs = new Hashtable(); jdkToOrbInputStreamBridge = (IIOPInputStream)inputStreamPairs.get(in); if (jdkToOrbInputStreamBridge == null) { jdkToOrbInputStreamBridge = createInputStream(); jdkToOrbInputStreamBridge.setOrbStream(inStream); jdkToOrbInputStreamBridge.setSender(sender); //d11638 // backward compatability 4365188 jdkToOrbInputStreamBridge.setValueHandler(this); inputStreamPairs.put(in, jdkToOrbInputStreamBridge); } java.io.Serializable result = null; try { jdkToOrbInputStreamBridge.increaseRecursionDepth(); result = (java.io.Serializable) readValueInternal(jdkToOrbInputStreamBridge, inStream, offset, clazz, repositoryID, sender); } finally { if (jdkToOrbInputStreamBridge.decreaseRecursionDepth() == 0) { inputStreamPairs.remove(in); } } return result; } private java.io.Serializable readValueInternal(IIOPInputStream bridge, org.omg.CORBA_2_3.portable.InputStream in, int offset, java.lang.Class clazz, String repositoryID, com.sun.org.omg.SendingContext.CodeBase sender) { java.io.Serializable result = null; if (clazz == null) { // clazz == null indicates an FVD situation for a nonexistant class if (isArray(repositoryID)){ read_Array(bridge, in, null, sender, offset); } else { bridge.simpleSkipObject(repositoryID, sender); } return result; } if (clazz.isArray()) { result = (java.io.Serializable)read_Array(bridge, in, clazz, sender, offset); } else { result = (java.io.Serializable)bridge.simpleReadObject(clazz, repositoryID, sender, offset); } return result; } /** * Returns the repository ID for the given RMI value Class. * @param clz The class to return a repository ID for. * @return the repository ID of the Class. **/ public java.lang.String getRMIRepositoryID(java.lang.Class clz) { return RepositoryId.createForJavaType(clz); } /** * Indicates whether the given Class performs custom or * default marshaling. * @param clz The class to test for custom marshaling. * @return True if the class performs custom marshaling, false * if it does not. **/ public boolean isCustomMarshaled(java.lang.Class clz) { return ObjectStreamClass.lookup(clz).isCustomMarshaled(); } /** * Returns the CodeBase for this ValueHandler. This is used by * the ORB runtime. The server sends the service context containing * the IOR for this CodeBase on the first GIOP reply. The clients * do the same on the first GIOP request. * @return the SendingContext.CodeBase of this ValueHandler. **/ public org.omg.SendingContext.RunTime getRunTimeCodeBase() { if (codeBase != null) return codeBase; else { codeBase = new FVDCodeBaseImpl(); // backward compatability 4365188 // set the valueHandler so that correct/incorrect RepositoryID // calculations can be done based on the ORB version FVDCodeBaseImpl fvdImpl = (FVDCodeBaseImpl) codeBase; fvdImpl.setValueHandler(this); return codeBase; } } // methods supported for backward compatability so that the appropriate // Rep-id calculations take place based on the ORB version /** * Returns a boolean of whether or not RepositoryId indicates * FullValueDescriptor. * used for backward compatability */ public boolean useFullValueDescription(Class clazz, String repositoryID) throws IOException { return RepositoryId.useFullValueDescription(clazz, repositoryID); } public String getClassName(String id) { RepositoryId repID = RepositoryId.cache.getId(id); return repID.getClassName(); } public Class getClassFromType(String id) throws ClassNotFoundException { RepositoryId repId = RepositoryId.cache.getId(id); return repId.getClassFromType(); } public Class getAnyClassFromType(String id) throws ClassNotFoundException { RepositoryId repId = RepositoryId.cache.getId(id); return repId.getAnyClassFromType(); } public String createForAnyType(Class cl) { return RepositoryId.createForAnyType(cl); } public String getDefinedInId(String id) { RepositoryId repId = RepositoryId.cache.getId(id); return repId.getDefinedInId(); } public String getUnqualifiedName(String id) { RepositoryId repId = RepositoryId.cache.getId(id); return repId.getUnqualifiedName(); } public String getSerialVersionUID(String id) { RepositoryId repId = RepositoryId.cache.getId(id); return repId.getSerialVersionUID(); } public boolean isAbstractBase(Class clazz) { return RepositoryId.isAbstractBase(clazz); } public boolean isSequence(String id) { RepositoryId repId = RepositoryId.cache.getId(id); return repId.isSequence(); } /** * If the value contains a writeReplace method then the result * is returned. Otherwise, the value itself is returned. * @return the true value to marshal on the wire. **/ public java.io.Serializable writeReplace(java.io.Serializable value) { return ObjectStreamClass.lookup(value.getClass()).writeReplace(value); } private void writeCharArray(org.omg.CORBA_2_3.portable.OutputStream out, char[] array, int offset, int length) { out.write_wchar_array(array, offset, length); } private void write_Array(org.omg.CORBA_2_3.portable.OutputStream out, java.io.Serializable obj, Class type) { int i, length; if (type.isPrimitive()) { if (type == Integer.TYPE) { int[] array = (int[])((Object)obj); length = array.length; out.write_ulong(length); out.write_long_array(array, 0, length); } else if (type == Byte.TYPE) { byte[] array = (byte[])((Object)obj); length = array.length; out.write_ulong(length); out.write_octet_array(array, 0, length); } else if (type == Long.TYPE) { long[] array = (long[])((Object)obj); length = array.length; out.write_ulong(length); out.write_longlong_array(array, 0, length); } else if (type == Float.TYPE) { float[] array = (float[])((Object)obj); length = array.length; out.write_ulong(length); out.write_float_array(array, 0, length); } else if (type == Double.TYPE) { double[] array = (double[])((Object)obj); length = array.length; out.write_ulong(length); out.write_double_array(array, 0, length); } else if (type == Short.TYPE) { short[] array = (short[])((Object)obj); length = array.length; out.write_ulong(length); out.write_short_array(array, 0, length); } else if (type == Character.TYPE) { char[] array = (char[])((Object)obj); length = array.length; out.write_ulong(length); writeCharArray(out, array, 0, length); } else if (type == Boolean.TYPE) { boolean[] array = (boolean[])((Object)obj); length = array.length; out.write_ulong(length); out.write_boolean_array(array, 0, length); } else { // XXX I18N, logging needed. throw new Error("Invalid primitive type : " + obj.getClass().getName()); } } else if (type == java.lang.Object.class) { Object[] array = (Object[])((Object)obj); length = array.length; out.write_ulong(length); for (i = 0; i < length; i++) { Util.writeAny(out, array[i]); } } else { Object[] array = (Object[])((Object)obj); length = array.length; out.write_ulong(length); int callType = kValueType; if (type.isInterface()) { String className = type.getName(); if (java.rmi.Remote.class.isAssignableFrom(type)) { // RMI Object reference... callType = kRemoteType; } else if (org.omg.CORBA.Object.class.isAssignableFrom(type)){ // IDL Object reference... callType = kRemoteType; } else if (RepositoryId.isAbstractBase(type)) { // IDL Abstract Object reference... callType = kAbstractType; } else if (ObjectStreamClassCorbaExt.isAbstractInterface(type)) { callType = kAbstractType; } } for (i = 0; i < length; i++) { switch (callType) { case kRemoteType: Util.writeRemoteObject(out, array[i]); break; case kAbstractType: Util.writeAbstractObject(out,array[i]); break; case kValueType: try{ out.write_value((java.io.Serializable)array[i]); } catch(ClassCastException cce){ if (array[i] instanceof java.io.Serializable) throw cce; else { Utility.throwNotSerializableForCorba( array[i].getClass().getName()); } } break; } } } } private void readCharArray(org.omg.CORBA_2_3.portable.InputStream in, char[] array, int offset, int length) { in.read_wchar_array(array, offset, length); } private java.lang.Object read_Array(IIOPInputStream bridge, org.omg.CORBA_2_3.portable.InputStream in, Class sequence, com.sun.org.omg.SendingContext.CodeBase sender, int offset) { try { // Read length of coming array int length = in.read_ulong(); int i; if (sequence == null) { for (i = 0; i < length; i++) in.read_value(); return null; } Class componentType = sequence.getComponentType(); Class actualType = componentType; if (componentType.isPrimitive()) { if (componentType == Integer.TYPE) { int[] array = new int[length]; in.read_long_array(array, 0, length); return ((java.io.Serializable)((Object)array)); } else if (componentType == Byte.TYPE) { byte[] array = new byte[length]; in.read_octet_array(array, 0, length); return ((java.io.Serializable)((Object)array)); } else if (componentType == Long.TYPE) { long[] array = new long[length]; in.read_longlong_array(array, 0, length); return ((java.io.Serializable)((Object)array)); } else if (componentType == Float.TYPE) { float[] array = new float[length]; in.read_float_array(array, 0, length); return ((java.io.Serializable)((Object)array)); } else if (componentType == Double.TYPE) { double[] array = new double[length]; in.read_double_array(array, 0, length); return ((java.io.Serializable)((Object)array)); } else if (componentType == Short.TYPE) { short[] array = new short[length]; in.read_short_array(array, 0, length); return ((java.io.Serializable)((Object)array)); } else if (componentType == Character.TYPE) { char[] array = new char[length]; readCharArray(in, array, 0, length); return ((java.io.Serializable)((Object)array)); } else if (componentType == Boolean.TYPE) { boolean[] array = new boolean[length]; in.read_boolean_array(array, 0, length); return ((java.io.Serializable)((Object)array)); } else { // XXX I18N, logging needed. throw new Error("Invalid primitive componentType : " + sequence.getName()); } } else if (componentType == java.lang.Object.class) { Object[] array = (Object[])java.lang.reflect.Array.newInstance( componentType, length); // Store this object and its beginning position // since there might be indirections to it while // it's been unmarshalled. bridge.activeRecursionMgr.addObject(offset, array); for (i = 0; i < length; i++) { Object objectValue = null; try { objectValue = Util.readAny(in); } catch(IndirectionException cdrie) { try { // The CDR stream had never seen the given offset // before, so check the recursion manager (it will // throw an IOException if it doesn't have a // reference, either). objectValue = bridge.activeRecursionMgr.getObject( cdrie.offset); } catch (IOException ie) { // Translate to a MARSHAL exception since // ValueHandlers aren't allowed to throw // IOExceptions throw utilWrapper.invalidIndirection( ie, new Integer( cdrie.offset ) ) ; } } array[i] = objectValue; } return ((java.io.Serializable)((Object)array)); } else { Object[] array = (Object[])java.lang.reflect.Array.newInstance( componentType, length); // Store this object and its beginning position // since there might be indirections to it while // it's been unmarshalled. bridge.activeRecursionMgr.addObject(offset, array); // Decide what method call to make based on the componentType. // If it is a componentType for which we need to load a stub, // convert the componentType to the correct stub type. int callType = kValueType; boolean narrow = false; if (componentType.isInterface()) { boolean loadStubClass = false; // String className = componentType.getName(); if (java.rmi.Remote.class.isAssignableFrom(componentType)) { // RMI Object reference... callType = kRemoteType; // for better performance, load the stub class once // instead of for each element of the array loadStubClass = true; } else if (org.omg.CORBA.Object.class.isAssignableFrom(componentType)){ // IDL Object reference... callType = kRemoteType; loadStubClass = true; } else if (RepositoryId.isAbstractBase(componentType)) { // IDL Abstract Object reference... callType = kAbstractType; loadStubClass = true; } else if (ObjectStreamClassCorbaExt.isAbstractInterface(componentType)) { // RMI Abstract Object reference... // componentType = null; callType = kAbstractType; } if (loadStubClass) { try { String codebase = Util.getCodebase(componentType); String repID = RepositoryId.createForAnyType(componentType); Class stubType = Utility.loadStubClass(repID, codebase, componentType); actualType = stubType; } catch (ClassNotFoundException e) { narrow = true; } } else { narrow = true; } } for (i = 0; i < length; i++) { try { switch (callType) { case kRemoteType: if (!narrow) array[i] = (Object)in.read_Object(actualType); else { array[i] = Utility.readObjectAndNarrow(in, actualType); } break; case kAbstractType: if (!narrow) array[i] = (Object)in.read_abstract_interface(actualType); else { array[i] = Utility.readAbstractAndNarrow(in, actualType); } break; case kValueType: array[i] = (Object)in.read_value(actualType); break; } } catch(IndirectionException cdrie) { // The CDR stream had never seen the given offset before, // so check the recursion manager (it will throw an // IOException if it doesn't have a reference, either). try { array[i] = bridge.activeRecursionMgr.getObject( cdrie.offset); } catch (IOException ioe) { // Translate to a MARSHAL exception since // ValueHandlers aren't allowed to throw // IOExceptions throw utilWrapper.invalidIndirection( ioe, new Integer( cdrie.offset ) ) ; } } } return ((java.io.Serializable)((Object)array)); } } finally { // We've completed deserializing this object. Any // future indirections will be handled correctly at the // CDR level. The ActiveRecursionManager only deals with // objects currently being deserialized. bridge.activeRecursionMgr.removeObject(offset); } } private boolean isArray(String repId){ return RepositoryId.cache.getId(repId).isSequence(); } private String getOutputStreamClassName() { return "com.sun.corba.se.impl.io.IIOPOutputStream"; } private IIOPOutputStream createOutputStream() { final String name = getOutputStreamClassName(); try { IIOPOutputStream stream = createOutputStreamBuiltIn(name); if (stream != null) { return stream; } return createCustom(IIOPOutputStream.class, name); } catch (Throwable t) { // Throw exception under the carpet. InternalError ie = new InternalError( "Error loading " + name ); ie.initCause(t); throw ie; } } /** * Construct a built in implementation with priveleges. * Returning null indicates a non-built is specified. */ private IIOPOutputStream createOutputStreamBuiltIn( final String name ) throws Throwable { try { return AccessController.doPrivileged( new PrivilegedExceptionAction<IIOPOutputStream>() { public IIOPOutputStream run() throws IOException { return createOutputStreamBuiltInNoPriv(name); } } ); } catch (java.security.PrivilegedActionException exc) { throw exc.getCause(); } } /** * Returning null indicates a non-built is specified. */ private IIOPOutputStream createOutputStreamBuiltInNoPriv( final String name ) throws IOException { return name.equals(IIOPOutputStream.class.getName()) ? new IIOPOutputStream() : null; } private String getInputStreamClassName() { return "com.sun.corba.se.impl.io.IIOPInputStream"; } private IIOPInputStream createInputStream() { final String name = getInputStreamClassName(); try { IIOPInputStream stream = createInputStreamBuiltIn(name); if (stream != null) { return stream; } return createCustom(IIOPInputStream.class, name); } catch (Throwable t) { // Throw exception under the carpet. InternalError ie = new InternalError( "Error loading " + name ); ie.initCause(t); throw ie; } } /** * Construct a built in implementation with priveleges. * Returning null indicates a non-built is specified. */ private IIOPInputStream createInputStreamBuiltIn( final String name ) throws Throwable { try { return AccessController.doPrivileged( new PrivilegedExceptionAction<IIOPInputStream>() { public IIOPInputStream run() throws IOException { return createInputStreamBuiltInNoPriv(name); } } ); } catch (java.security.PrivilegedActionException exc) { throw exc.getCause(); } } /** * Returning null indicates a non-built is specified. */ private IIOPInputStream createInputStreamBuiltInNoPriv( final String name ) throws IOException { return name.equals(IIOPInputStream.class.getName()) ? new IIOPInputStream() : null; } /** * Create a custom implementation without privileges. */ private <T> T createCustom( final Class<T> type, final String className ) throws Throwable { // Note: We use the thread context or system ClassLoader here // since we want to load classes outside of the // core JDK when running J2EE Pure ORB and // talking to Kestrel. ClassLoader cl = Thread.currentThread().getContextClassLoader(); if (cl == null) cl = ClassLoader.getSystemClassLoader(); Class<?> clazz = cl.loadClass(className); Class<? extends T> streamClass = clazz.asSubclass(type); // Since the ClassLoader should cache the class, this isn't // as expensive as it looks. return streamClass.newInstance(); } TCKind getJavaCharTCKind() { return TCKind.tk_wchar; } }
gpl-2.0
miraculix0815/jexcelapi
src/jxl/format/Pattern.java
3725
/********************************************************************* * * Copyright (C) 2002 Andrew Khan * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ***************************************************************************/ package jxl.format; /** * Enumeration class which contains the various patterns available within * the standard Excel pattern palette */ public /*final*/ class Pattern { /** * The internal numerical representation of the colour */ private int value; /** * The textual description */ private String string; /** * The list of patterns */ private static Pattern[] patterns = new Pattern[0]; /** * Private constructor * * @param val * @param s */ protected Pattern(int val, String s) { value = val; string = s; Pattern[] oldcols = patterns; patterns = new Pattern[oldcols.length + 1]; System.arraycopy(oldcols, 0, patterns, 0, oldcols.length); patterns[oldcols.length] = this; } /** * Gets the value of this pattern. This is the value that is written to * the generated Excel file * * @return the binary value */ public int getValue() { return value; } /** * Gets the textual description * * @return the string */ public String getDescription() { return string; } /** * Gets the pattern from the value * * @param val * @return the pattern with that value */ public static Pattern getPattern(int val) { for (int i = 0 ; i < patterns.length ; i++) { if (patterns[i].getValue() == val) { return patterns[i]; } } return NONE; } public final static Pattern NONE = new Pattern(0x0, "None"); public final static Pattern SOLID = new Pattern(0x1, "Solid"); public final static Pattern GRAY_50 = new Pattern(0x2, "Gray 50%"); public final static Pattern GRAY_75 = new Pattern(0x3, "Gray 75%"); public final static Pattern GRAY_25 = new Pattern(0x4, "Gray 25%"); public final static Pattern PATTERN1 = new Pattern(0x5, "Pattern 1"); public final static Pattern PATTERN2 = new Pattern(0x6, "Pattern 2"); public final static Pattern PATTERN3 = new Pattern(0x7, "Pattern 3"); public final static Pattern PATTERN4 = new Pattern(0x8, "Pattern 4"); public final static Pattern PATTERN5 = new Pattern(0x9, "Pattern 5"); public final static Pattern PATTERN6 = new Pattern(0xa, "Pattern 6"); public final static Pattern PATTERN7 = new Pattern(0xb, "Pattern 7"); public final static Pattern PATTERN8 = new Pattern(0xc, "Pattern 8"); public final static Pattern PATTERN9 = new Pattern(0xd, "Pattern 9"); public final static Pattern PATTERN10 = new Pattern(0xe, "Pattern 10"); public final static Pattern PATTERN11 = new Pattern(0xf, "Pattern 11"); public final static Pattern PATTERN12 = new Pattern(0x10, "Pattern 12"); public final static Pattern PATTERN13 = new Pattern(0x11, "Pattern 13"); public final static Pattern PATTERN14 = new Pattern(0x12, "Pattern 14"); }
lgpl-3.0
jblievremont/sonarqube
server/sonar-server/src/main/java/org/sonar/server/usergroups/ws/UserGroupsWsAction.java
1043
/* * SonarQube, open source software quality management tool. * Copyright (C) 2008-2014 SonarSource * mailto:contact AT sonarsource DOT com * * SonarQube is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * SonarQube is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.usergroups.ws; import org.sonar.server.ws.WsAction; public interface UserGroupsWsAction extends WsAction { // Marker interface }
lgpl-3.0
siosio/intellij-community
java/java-tests/testData/inspection/textBlockMigration/afterConcatenationWithEscapedQuotesWithoutLineBreaks.java
210
// "Replace with text block" "true" class TextBlockMigration { void concatenationWithEscapedQuotesWithoutLineBreaks() { String div = """ <div lang="{{interpolation?.here}}"></div>"""; } }
apache-2.0
Lekanich/intellij-community
xml/dom-impl/src/com/intellij/util/xml/stubs/builder/DomStubBuilder.java
3675
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.util.xml.stubs.builder; import com.intellij.ide.highlighter.XmlFileType; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Document; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiFile; import com.intellij.psi.stubs.BinaryFileStubBuilder; import com.intellij.psi.stubs.Stub; import com.intellij.psi.xml.XmlFile; import com.intellij.psi.xml.XmlTag; import com.intellij.semantic.SemService; import com.intellij.util.indexing.FileBasedIndexImpl; import com.intellij.util.indexing.FileContent; import com.intellij.util.xml.*; import com.intellij.util.xml.impl.DomApplicationComponent; import com.intellij.util.xml.impl.DomManagerImpl; import com.intellij.util.xml.stubs.FileStub; import com.intellij.xml.util.XmlUtil; /** * @author Dmitry Avdeev * Date: 8/2/12 */ public class DomStubBuilder implements BinaryFileStubBuilder { private static final Logger LOG = Logger.getInstance(DomStubBuilder.class); @Override public boolean acceptsFile(VirtualFile file) { FileType fileType = file.getFileType(); return fileType == XmlFileType.INSTANCE && !FileBasedIndexImpl.isProjectOrWorkspaceFile(file, fileType); } @Override public Stub buildStubTree(FileContent fileContent) { PsiFile psiFile = fileContent.getPsiFile(); if (!(psiFile instanceof XmlFile)) return null; Document document = FileDocumentManager.getInstance().getCachedDocument(fileContent.getFile()); Project project = fileContent.getProject(); if (project == null) { project = psiFile.getProject(); } if (document != null) { PsiFile existingPsi = PsiDocumentManager.getInstance(project).getPsiFile(document); if (existingPsi instanceof XmlFile) { psiFile = existingPsi; } } XmlFile xmlFile = (XmlFile)psiFile; try { XmlUtil.BUILDING_DOM_STUBS.set(Boolean.TRUE); DomFileElement<? extends DomElement> fileElement = DomManager.getDomManager(project).getFileElement(xmlFile); if (fileElement == null || !fileElement.getFileDescription().hasStubs()) return null; XmlFileHeader header = DomService.getInstance().getXmlFileHeader(xmlFile); if (header.getRootTagLocalName() == null) { LOG.error("null root tag for " + fileElement + " for " + fileContent.getFile()); } FileStub fileStub = new FileStub(header); XmlTag rootTag = xmlFile.getRootTag(); if (rootTag != null) { new DomStubBuilderVisitor(DomManagerImpl.getDomManager(project)).visitXmlElement(rootTag, fileStub, 0); } return fileStub; } finally { XmlUtil.BUILDING_DOM_STUBS.set(Boolean.FALSE); SemService.getSemService(project).clearCache(); } } @Override public int getStubVersion() { return 21 + DomApplicationComponent.getInstance().getCumulativeVersion(); } }
apache-2.0
dahlstrom-g/intellij-community
platform/lang-api/src/com/intellij/codeInsight/generation/MemberChooserObject.java
1038
/* * Copyright 2000-2009 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.generation; import com.intellij.openapi.util.NlsContexts; import com.intellij.ui.SimpleColoredComponent; import org.jetbrains.annotations.NotNull; import javax.swing.*; /** * @author peter */ public interface MemberChooserObject { void renderTreeNode(SimpleColoredComponent component, JTree tree); @NlsContexts.Label @NotNull String getText(); boolean equals(Object o); int hashCode(); }
apache-2.0
dahlstrom-g/intellij-community
plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/junit/MakePublicStaticFix.java
2298
/* * Copyright 2000-2016 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.siyeh.ig.junit; import com.intellij.codeInspection.ProblemDescriptor; import com.intellij.codeInspection.util.IntentionName; import com.intellij.openapi.project.Project; import com.intellij.psi.*; import com.siyeh.InspectionGadgetsBundle; import com.siyeh.ig.InspectionGadgetsFix; import org.jetbrains.annotations.NotNull; class MakePublicStaticFix extends InspectionGadgetsFix { private final @IntentionName String myName; private final boolean myMakeStatic; MakePublicStaticFix(final @IntentionName String name, final boolean makeStatic) { myName = name; myMakeStatic = makeStatic; } @Override protected void doFix(Project project, ProblemDescriptor descriptor) { final PsiElement element = descriptor.getPsiElement(); if (element == null) { return; } final PsiElement parent = element.getParent(); if (!(parent instanceof PsiMember)) { return; } final PsiMember member = (PsiMember)parent; final PsiModifierList modifierList = member.getModifierList(); if (modifierList == null) { return; } modifierList.setModifierProperty(PsiModifier.PUBLIC, true); modifierList.setModifierProperty(PsiModifier.STATIC, myMakeStatic); final PsiElement sibling = modifierList.getNextSibling(); if (sibling instanceof PsiWhiteSpace && sibling.getText().contains("\n")) { sibling.replace(PsiParserFacade.SERVICE.getInstance(project).createWhiteSpaceFromText(" ")); } } @NotNull @Override public String getName() { return myName; } @NotNull @Override public String getFamilyName() { return InspectionGadgetsBundle.message("make.public.static.fix.family.name"); } }
apache-2.0
Kreolwolf1/Elastic
src/main/java/org/elasticsearch/index/engine/EngineAlreadyStartedException.java
1086
/* * Licensed to ElasticSearch and Shay Banon under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. ElasticSearch 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.elasticsearch.index.engine; import org.elasticsearch.index.shard.ShardId; /** * */ public class EngineAlreadyStartedException extends EngineException { public EngineAlreadyStartedException(ShardId shardId) { super(shardId, "Already started"); } }
apache-2.0