blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
7
332
content_id
stringlengths
40
40
detected_licenses
listlengths
0
50
license_type
stringclasses
2 values
repo_name
stringlengths
7
115
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
557 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.85k
684M
star_events_count
int64
0
77.7k
fork_events_count
int64
0
48k
gha_license_id
stringclasses
17 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
82 values
src_encoding
stringclasses
28 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
7
5.41M
extension
stringclasses
11 values
content
stringlengths
7
5.41M
authors
listlengths
1
1
author
stringlengths
0
161
95760211f8315d8be3e1168bd50b373e5a9d537f
af4278ccc5669938a1904222f80fa27f62cd05eb
/src/com/frs/pojos/UserProfile.java
9136f35f1a1eecf60693142d09ac894c9ce86713
[]
no_license
muniramPune/CdacProject
c04bbf72b8282e8de8291580ebe4e2e72ff5576d
ea63a303b3edf73a4c8da56cefea6184e198882f
refs/heads/master
2021-01-23T01:00:44.623544
2017-03-22T17:56:09
2017-03-22T17:56:09
85,857,683
0
0
null
null
null
null
UTF-8
Java
false
false
2,646
java
package com.frs.pojos; import java.io.Serializable; import javax.persistence.*; import java.util.Date; /** * The persistent class for the FRS_TBL_USER_PROFILE database table. * */ @Entity @Table(name="FRS_TBL_USER_PROFILE") @NamedQuery(name="UserProfile.findAll", query="SELECT u FROM UserProfile u") public class UserProfile { private static final long serialVersionUID = 1L; private String city; private Date dateofbirth; private String emailid; private String firstname; private String gender; private String lastname; private String location; private String mobileno; private String password; private String pincode; private String state; private String street; private long userid; public UserProfile() { } public String getCity() { return this.city; } public void setCity(String city) { this.city = city; } @Temporal(TemporalType.DATE) public Date getDateofbirth() { return this.dateofbirth; } public void setDateofbirth(Date dateofbirth) { this.dateofbirth = dateofbirth; } @Id public String getEmailid() { return this.emailid; } public void setEmailid(String emailid) { this.emailid = emailid; } public String getFirstname() { return this.firstname; } public void setFirstname(String firstname) { this.firstname = firstname; } public String getGender() { return this.gender; } public void setGender(String gender) { this.gender = gender; } public String getLastname() { return this.lastname; } public void setLastname(String lastname) { this.lastname = lastname; } public String getLocation() { return this.location; } public void setLocation(String location) { this.location = location; } public String getMobileno() { return this.mobileno; } public void setMobileno(String mobileno) { this.mobileno = mobileno; } public String getPassword() { return this.password; } public void setPassword(String password) { this.password = password; } public String getPincode() { return this.pincode; } public void setPincode(String pincode) { this.pincode = pincode; } @Column(name="\"STATE\"") public String getState() { return this.state; } public void setState(String state) { this.state = state; } public String getStreet() { return this.street; } public void setStreet(String street) { this.street = street; } public long getUserid() { return this.userid; } public void setUserid(long userid) { this.userid = userid; } }
76686d18d9bfcce4e4255e6b7659f037d2fe0738
ce8e849e624985033bc89ade92002daa8656733c
/app/src/main/java/com/example/myapplication/DeleteInspection.java
4cb112fa1b03bb4630229287e0380107ded9f8fb
[]
no_license
JD-Mehlenbacher/app
ac1a8ee9204d8bae6637d1d408081bece22affea
eb6a05927c2cdcb5c690990bf1f45f5fc7780471
refs/heads/master
2023-05-31T12:31:09.881049
2021-06-25T17:45:19
2021-06-25T17:45:19
375,773,045
0
0
null
null
null
null
UTF-8
Java
false
false
6,397
java
package com.example.myapplication; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.WindowManager; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.Spinner; import java.sql.Connection; import java.sql.ResultSet; import java.sql.Statement; import java.util.ArrayList; public class DeleteInspection extends AppCompatActivity { private Spinner buildingDropdown; private Spinner typeDropdown; private Button deleteButton; private Button confirmDeleteButton; private String buildingInputVar; private String typeInputVar; Connection connect; String ConnectionResult = ""; private ArrayList<String> buildings; private ArrayList<String> types; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getSupportActionBar().hide(); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.activity_delete_inspection); buildings = new ArrayList<>(); types = new ArrayList<>(); deleteButton=(Button) findViewById(R.id.deleteInspectionButton); deleteButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { confirmDeleteButton.setVisibility(View.VISIBLE); } }); confirmDeleteButton=(Button) findViewById(R.id.confirmInspectionDelete); confirmDeleteButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { deleteInspection(); Intent intent= new Intent(DeleteInspection.this, com.example.myapplication.homePage.class); startActivity(intent); } }); confirmDeleteButton.setVisibility(View.INVISIBLE); getBuildings(); buildingInputVar = buildings.get(0); buildingDropdown=(Spinner) findViewById(R.id.buildingDropDownDelete); ArrayAdapter<String> adapter = new ArrayAdapter<String>(DeleteInspection.this, android.R.layout.simple_spinner_dropdown_item, buildings); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); buildingDropdown.setAdapter(adapter); buildingDropdown.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { buildingInputVar=buildings.get(position); getInspections(); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); getInspections(); typeDropdown=(Spinner) findViewById(R.id.typeDropDownDelete); ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(DeleteInspection.this, android.R.layout.simple_spinner_dropdown_item, types); adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); typeDropdown.setAdapter(adapter2); typeDropdown.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { typeInputVar=types.get(position); errorStateHelper.selectedTypeInspectionError=false; } @Override public void onNothingSelected(AdapterView<?> parent) { errorStateHelper.selectedTypeInspectionError=true; } }); } public void deleteInspection(){ try { ConnectionHelper connectionHelper = new ConnectionHelper(); connect = connectionHelper.connectionClass(); if (connect != null) { Statement st = connect.createStatement(); st.executeUpdate("DELETE FROM BuildingInspectionQuestions WHERE Building_Name = \'" + buildingInputVar + "\' and Inspection_Title = \'" + typeInputVar + "\'"); } else { ConnectionResult = "Check Connection"; } connect.close(); } catch (Exception ex) { System.out.println("Error deleting inspection."); } } public void getBuildings() { try { ConnectionHelper connectionHelper = new ConnectionHelper(); connect = connectionHelper.connectionClass(); if (connect != null) { Statement st = connect.createStatement(); ResultSet rs = st.executeQuery("SELECT * FROM BuildingInfo"); while (rs.next()) { //System.out.println("ADDING A BUILDING!: " + rs.getString("Building_Name")); buildings.add(rs.getString("Building_Name")); } st.close(); } else { ConnectionResult = "Check Connection"; } connect.close(); } catch (Exception ex) { System.out.println("Get buildings error"); } } public void getInspections() { types.clear(); try { ConnectionHelper connectionHelper = new ConnectionHelper(); connect = connectionHelper.connectionClass(); if (connect != null) { Statement st = connect.createStatement(); ResultSet rs = st.executeQuery("SELECT * FROM BuildingInspectionQuestions WHERE Question_Number = 1 and Building_Name = \'" + buildingInputVar + "\'"); while (rs.next()) { types.add(rs.getString("Inspection_Title")); } ArrayAdapter<String> adaps = new ArrayAdapter<String>(DeleteInspection.this, android.R.layout.simple_spinner_dropdown_item, types); typeDropdown.setAdapter(adaps); st.close(); } else { ConnectionResult = "Check Connection"; } connect.close(); } catch (Exception ex) { System.out.println("Get inspections error"); } } }
28e85cd8ec8f8ad2a2b326e9b87468d90d4817ea
d77a9e877a2ab84a75e4ed8f161b5d49c5e65ec6
/com.jaspersoft.studio/src/com/jaspersoft/studio/widgets/framework/WColorsItemProperty.java
dcf8bb1fa59d63d2851a2e2e8cd5a57d0ef49d65
[]
no_license
jasonbrianhall/Jaspersoft-Studio
3b0faa08e4da17c24f2f60531e3a5c2e8d7b6478
33f85aee98402cb9da4ac305eab7f071e2ff1b61
refs/heads/master
2021-01-21T20:28:59.761114
2017-05-24T13:10:37
2017-05-24T13:10:37
92,215,885
2
0
null
null
null
null
UTF-8
Java
false
false
3,630
java
/******************************************************************************* * Copyright (C) 2010 - 2016. TIBCO Software Inc. * All Rights Reserved. Confidential & Proprietary. ******************************************************************************/ package com.jaspersoft.studio.widgets.framework; import org.eclipse.swt.widgets.Composite; import com.jaspersoft.studio.utils.Colors; import com.jaspersoft.studio.widgets.framework.model.WidgetPropertyDescriptor; import com.jaspersoft.studio.widgets.framework.ui.ItemPropertyDescription; import net.sf.jasperreports.engine.JRExpression; import net.sf.jasperreports.engine.design.JRDesignExpression; /** * This custom version of the standard {@link WItemProperty} is meant to be used * with colors palette widgets where it is not possible to rely on the standard value string * for the property value. * <p> * * In this case a custom expression (arrays of string colors) is generated whenever the simple * mode interface is used to set the property value itself. * * @author Massimo Rabbi ([email protected]) * */ public class WColorsItemProperty extends WItemProperty { public WColorsItemProperty(Composite parent, int style, ItemPropertyDescription<?> widgetDescriptor, IPropertyEditor editor) { super(parent, style, widgetDescriptor, editor); } public WColorsItemProperty(Composite parent, int style, WidgetPropertyDescriptor descriptor, ItemPropertyDescription<?> widgetDescriptor, IPropertyEditor editor) { super(parent, style, descriptor, widgetDescriptor, editor); } @Override public boolean isExpressionMode() { if(isCustomSimpleMode()){ return false; } else { return getPropertyEditor().getPropertyValueExpression(getPropertyName()) != null; } } @Override public String getStaticValue() { if(isCustomSimpleMode()){ JRExpression expressionValue = getExpressionValue(); if(expressionValue!=null){ String[] colors = Colors.decodeHexColorsArray(expressionValue.getText()); return Colors.encodeHexColorsAsArray(colors); } return ""; } else { return super.getStaticValue(); } } public void setCustomSimpleModeUsage() { String simpleMode = getPropertyName() + WItemProperty.CUSTOM_SIMPLE_MODE_SUFFIX; getPropertyEditor().createUpdateProperty(simpleMode, "true", null); } public void removeCustomSimpleModeUsage() { getPropertyEditor().removeProperty(getPropertyName() + WItemProperty.CUSTOM_SIMPLE_MODE_SUFFIX); } public boolean isCustomSimpleMode(){ String customSimpleMode = getPropertyEditor().getPropertyValue(getPropertyName()+WItemProperty.CUSTOM_SIMPLE_MODE_SUFFIX); return "true".equals(customSimpleMode); } @Override public void setValue(String staticValue, JRExpression expressionValue) { setRefresh(true); try { if(staticValue!=null){ setCustomSimpleModeUsage(); String[] colors = Colors.decodeHexColorsArray(staticValue); StringBuffer colorsSB = new StringBuffer("Arrays.asList("); for(int i=0;i<colors.length;i++){ colorsSB.append("\""); colorsSB.append(colors[i]); colorsSB.append("\""); if(i!=colors.length-1){ colorsSB.append(","); } } colorsSB.append(")"); staticValue=null; expressionValue=new JRDesignExpression(colorsSB.toString()); } else { removeCustomSimpleModeUsage(); } getPropertyEditor().createUpdateProperty(getPropertyName(), staticValue, expressionValue); updateWidget(); // Notifies the listeners of the new expression fireModifyEvent(staticValue, expressionValue); } finally { setRefresh(false); } } }
[ "mrabbi@6833c83e-4fd0-4c68-a3df-283c6148db30" ]
mrabbi@6833c83e-4fd0-4c68-a3df-283c6148db30
380bce99ecca1608d7e42188e2447416ba1e4ac0
71293f413b3628f3f6d5b47c28f117fa4bd1bc86
/StarbuzzCoffee/src/starbuzzCoffee/Milk.java
387773cf80821e3078dc668cc66b0bb8cc8ddce9
[]
no_license
JohnnyWang1998/DesignPattern
c3481e4405c1308235e6cb433998f464e8c47623
88d7ac0cb39319d471a27aff6518fc016fec27e1
refs/heads/master
2020-12-30T05:53:51.574723
2020-05-14T05:21:30
2020-05-14T05:21:30
238,882,757
0
0
null
2020-02-25T04:16:40
2020-02-07T09:08:43
Java
UTF-8
Java
false
false
307
java
package starbuzzCoffee; public class Milk extends CodimentDecorator { protected Beverage _beverage; public Milk(Beverage beverage) { _beverage = beverage; } public float cost() { return _beverage.cost()+0.10f; } public String getDescription() { return _beverage.getDescription()+", Milk"; } }
a648a5fedf4c9ce7d998bffc57e8b2c93a57c18a
5ff124c03289ff0d89349162b15161b9dd14a2b0
/java-workspace/DesignPatterns/src/com/ericsson/learning/designpatterns/state/State.java
e2a1abfc37198bf84ed1e978577a1db6f5e551a5
[]
no_license
mida87/learning-workspace
26f4c41c5965e36e1d8d2da0370368c9ec402c99
f9bb6fa246c3b2acbaca58d4eabdb7a241ee818d
refs/heads/master
2021-01-16T18:06:23.699767
2014-09-01T13:16:56
2014-09-01T13:16:56
14,470,350
0
0
null
null
null
null
UTF-8
Java
false
false
577
java
package com.ericsson.learning.designpatterns.state; /** * STATE: State <interface>, every state will implement required steps if applicable * */ public abstract class State { public void insertQuarter() { System.err.println("You cannot insert quarter at this point"); } public void ejectQuarter() { System.err.println("You cannot eject quarter at this point"); } public void turnCrank() { System.err.println("You cannot turn crank at this point"); } public void dispense() { } public abstract void refill(); }
f11c7747c47782ff0d1aad7a10eac10349486853
065c1f648e8dd061a20147ff9c0dbb6b5bc8b9be
/eclipsejdt_cluster/66583/tar_1.java
938817a0d62781cb8e06bf802b3ef1b3ab1350d0
[]
no_license
martinezmatias/GenPat-data-C3
63cfe27efee2946831139747e6c20cf952f1d6f6
b360265a6aa3bb21bd1d64f1fc43c3b37d0da2a4
refs/heads/master
2022-04-25T17:59:03.905613
2020-04-15T14:41:34
2020-04-15T14:41:34
null
0
0
null
null
null
null
UTF-8
Java
false
false
89,347
java
/******************************************************************************* * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.core.tests.compiler.regression; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.StringTokenizer; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.Path; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.ToolFactory; import org.eclipse.jdt.core.compiler.batch.BatchCompiler; import org.eclipse.jdt.core.search.SearchDocument; import org.eclipse.jdt.core.search.SearchParticipant; import org.eclipse.jdt.core.tests.junit.extension.StopableTestCase; import org.eclipse.jdt.core.tests.util.AbstractCompilerTest; import org.eclipse.jdt.core.tests.util.CompilerTestSetup; import org.eclipse.jdt.core.tests.util.TestVerifier; import org.eclipse.jdt.core.tests.util.Util; import org.eclipse.jdt.core.util.ClassFileBytesDisassembler; import org.eclipse.jdt.core.util.ClassFormatException; import org.eclipse.jdt.internal.compiler.Compiler; import org.eclipse.jdt.internal.compiler.ICompilerRequestor; import org.eclipse.jdt.internal.compiler.IErrorHandlingPolicy; import org.eclipse.jdt.internal.compiler.IProblemFactory; import org.eclipse.jdt.internal.compiler.batch.FileSystem; import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants; import org.eclipse.jdt.internal.compiler.classfmt.ClassFileReader; import org.eclipse.jdt.internal.compiler.env.INameEnvironment; import org.eclipse.jdt.internal.compiler.impl.CompilerOptions; import org.eclipse.jdt.internal.compiler.lookup.TypeConstants; import org.eclipse.jdt.internal.compiler.problem.DefaultProblemFactory; import org.eclipse.jdt.internal.core.search.JavaSearchParticipant; import org.eclipse.jdt.internal.core.search.indexing.BinaryIndexer; public abstract class AbstractRegressionTest extends AbstractCompilerTest implements StopableTestCase { // javac comparison related types, fields and methods - see runJavac for // details static class JavacCompiler { String rootDirectoryPath; String javacPathName; String version; // not intended to be modified - one of JavaCore.VERSION_1_* int minor; String rawVersion; // not intended to be modified - more complete version name long compliance; public static final long EXIT_VALUE_MASK = 0x00000000FFFFFFFFL; public static final long ERROR_LOG_MASK = 0xFFFFFFFF00000000L; private static final String[] jarsNames = new String[] { "/lib/vm.jar", "/lib/rt.jar", "/lib/core.jar", "/lib/security.jar", "/lib/xml.jar", "/lib/graphics.jar" }; private String classpath; JavacCompiler(String rootDirectoryPath) throws IOException, InterruptedException { this(rootDirectoryPath, null); } JavacCompiler(String rootDirectoryPath, String rawVersion) throws IOException, InterruptedException { this.rootDirectoryPath = rootDirectoryPath; this.javacPathName = new File(rootDirectoryPath + File.separator + "bin" + File.separator + JAVAC_NAME).getCanonicalPath(); // WORK don't need JAVAC_NAME any more; suppress this as we work towards code cleanup if (rawVersion == null) { Process fetchVersionProcess = null; try { fetchVersionProcess = Runtime.getRuntime().exec(this.javacPathName + " -version", null, null); Logger versionLogger = new Logger(fetchVersionProcess.getErrorStream(), ""); versionLogger.start(); fetchVersionProcess.waitFor(); versionLogger.join(); // make sure we get the whole output rawVersion = versionLogger.buffer.toString(); int eol = rawVersion.indexOf('\n'); if (eol != -1) { rawVersion = rawVersion.substring(0, eol); } if (rawVersion.startsWith("javac ")) { rawVersion = rawVersion.substring(6, rawVersion.length()); } } finally { if (fetchVersionProcess != null) { fetchVersionProcess.destroy(); // closes process streams } } } if (rawVersion.indexOf("1.4") != -1 || this.javacPathName.indexOf("1.4") != -1 /* in fact, SUN javac 1.4 does not support the -version option; * this is a imperfect heuristic to catch the case */) { this.version = JavaCore.VERSION_1_4; } else if (rawVersion.indexOf("1.5") != -1) { this.version = JavaCore.VERSION_1_5; } else if (rawVersion.indexOf("1.6") != -1) { this.version = JavaCore.VERSION_1_6; } else if (rawVersion.indexOf("1.7") != -1) { this.version = JavaCore.VERSION_1_7; } else { throw new RuntimeException("unknown javac version: " + rawVersion); } this.compliance = CompilerOptions.versionToJdkLevel(this.version); this.minor = minorFromRawVersion(version, rawVersion); this.rawVersion = rawVersion; StringBuffer classpathBuffer = new StringBuffer(" -classpath "); for (int i = 0, l = jarsNames.length; i < l; i++) { classpathBuffer.append(rootDirectoryPath); classpathBuffer.append(jarsNames[i]); classpathBuffer.append(File.pathSeparator); } this.classpath = classpathBuffer.toString(); } // projects known raw versions to minors; minors should grow with time, so // that before and after relationships be easy to implement upon compilers // of the same version; two latest digits are used for variants into levels // denoted by the two first digits static int minorFromRawVersion (String version, String rawVersion) { if (version == JavaCore.VERSION_1_5) { if ("1.5.0_15-ea".equals(rawVersion)) { return 1500; } } if (version == JavaCore.VERSION_1_6) { if ("1.6.0_10-ea".equals(rawVersion)) { return 1000; } } if (version == JavaCore.VERSION_1_7) { if ("1.7.0-ea".equals(rawVersion)) { // b23 at the time of writing return 0000; } } throw new RuntimeException("unknown raw javac version: " + rawVersion); } // returns 0L if everything went fine; else the lower word contains the // exit value and the upper word is non-zero iff the error log has contents long compile(File directory, String options, String[] sourceFileNames, StringBuffer log) throws IOException, InterruptedException { Process compileProcess = null; long result = 0L; // WORK classpath should depend on the compiler, not on the default runtime try { StringBuffer cmdLine = new StringBuffer(this.javacPathName); cmdLine.append(this.classpath); cmdLine.append(". "); cmdLine.append(options); for (int i = 0; i < sourceFileNames.length; i ++) { cmdLine.append(' '); cmdLine.append(sourceFileNames[i]); } compileProcess = Runtime.getRuntime().exec(cmdLine.toString(), null, directory); Logger errorLogger = new Logger(compileProcess.getErrorStream(), "ERROR", log == null ? new StringBuffer() : log); errorLogger.start(); int compilerResult = compileProcess.waitFor(); result |= compilerResult; // caveat: may never terminate under specific conditions errorLogger.join(); // make sure we get the whole output if (errorLogger.buffer.length() > 0) { System.err.println("--- javac err: ---"); System.err.println(errorLogger.buffer.toString()); result |= ERROR_LOG_MASK; } } finally { if (compileProcess != null) { compileProcess.destroy(); } } return result; } } static class JavaRuntime { private String rootDirectoryPath; private String javaPathName; String version; // not intended to be modified - one of JavaCore.VERSION_1_* String rawVersion; // not intended to be modified - more complete version name int minor; private static HashMap runtimes = new HashMap(); static JavaRuntime runtimeFor(JavacCompiler compiler) throws IOException, InterruptedException { JavaRuntime cached = (JavaRuntime) runtimes.get(compiler.rawVersion); if (cached == null) { cached = new JavaRuntime(compiler.rootDirectoryPath, compiler.version, compiler.rawVersion, compiler.minor); runtimes.put(compiler.rawVersion, cached); } return cached; } private JavaRuntime(String rootDirectoryPath, String version, String rawVersion, int minor) throws IOException, InterruptedException { this.rootDirectoryPath = rootDirectoryPath; this.javaPathName = new File(this.rootDirectoryPath + File.separator + "bin" + File.separator + JAVA_NAME).getCanonicalPath(); this.version = version; this.rawVersion = rawVersion; this.minor = minor; } // returns 0 if everything went fine int execute(File directory, String options, String className, StringBuffer stdout, StringBuffer stderr) throws IOException, InterruptedException { Process executionProcess = null; try { StringBuffer cmdLine = new StringBuffer(this.javaPathName); cmdLine.append(" -classpath . "); // default classpath cmdLine.append(options); cmdLine.append(' '); cmdLine.append(className); executionProcess = Runtime.getRuntime().exec(cmdLine.toString(), null, directory); Logger outputLogger = new Logger(executionProcess.getInputStream(), "RUNTIME OUTPUT", stdout == null ? new StringBuffer() : stdout); outputLogger.start(); Logger errorLogger = new Logger(executionProcess.getErrorStream(), "RUNTIME ERROR", stderr == null ? new StringBuffer() : stderr); errorLogger.start(); int result = executionProcess.waitFor(); // caveat: may never terminate under specific conditions outputLogger.join(); // make sure we get the whole output errorLogger.join(); // make sure we get the whole output return result; } finally { if (executionProcess != null) { executionProcess.destroy(); } } } } static class JavacTestOptions { static final JavacTestOptions DEFAULT = new JavacTestOptions(); static final JavacTestOptions SKIP = new JavacTestOptions() { boolean skip(JavacCompiler compiler) { return true; } }; private String compilerOptions = ""; public JavacTestOptions() { } public JavacTestOptions(String compilerOptions) { this.compilerOptions = compilerOptions; } String getCompilerOptions() { return this.compilerOptions; } boolean skip(JavacCompiler compiler) { return false; } static class MismatchType { static final int EclipseErrorsJavacNone = 0x0001; static final int EclipseErrorsJavacWarnings = 0x0002; static final int JavacErrorsEclipseNone = 0x0004; static final int JavacErrorsEclipseWarnings = 0x0008; static final int EclipseWarningsJavacNone = 0x0010; static final int JavacWarningsEclipseNone = 0x0020; static final int StandardOutputMismatch = 0x0040; static final int ErrorOutputMismatch = 0x0080; static final int JavacAborted = 0x0100; static final int JavacNotLaunched = 0x0200; static final int JavaAborted = 0x0400; static final int JavaNotLaunched = 0x0800; } static class Excuse extends JavacTestOptions { protected int mismatchType; Excuse(int mismatchType) { this.mismatchType = mismatchType; } Excuse excuseFor(JavacCompiler compiler) { return this; } public boolean clears(int mismatch) { return this.mismatchType == 0 || (this.mismatchType & mismatch) == mismatch; // one excuse can clear multiple mismatches } public static Excuse EclipseHasSomeMoreWarnings = RUN_JAVAC ? new Excuse(MismatchType.EclipseWarningsJavacNone) : null, EclipseWarningConfiguredAsError = RUN_JAVAC ? new Excuse(MismatchType.EclipseErrorsJavacWarnings | MismatchType.EclipseErrorsJavacNone) : null; } Excuse excuseFor(JavacCompiler compiler) { return null; } static class EclipseHasABug extends Excuse { private EclipseHasABug(int mismatchType) { super(mismatchType); } public static EclipseHasABug EclipseBug166355 = RUN_JAVAC ? // https://bugs.eclipse.org/bugs/show_bug.cgi?id=166355 new EclipseHasABug(MismatchType.JavacErrorsEclipseWarnings) : null, EclipseBug177715 = RUN_JAVAC ? // https://bugs.eclipse.org/bugs/show_bug.cgi?id=177715 new EclipseHasABug(MismatchType.JavacErrorsEclipseNone) : null, EclipseBug216558 = RUN_JAVAC ? // https://bugs.eclipse.org/bugs/show_bug.cgi?id=216558 new EclipseHasABug(MismatchType.JavacErrorsEclipseNone) : null; } // Eclipse bugs opened to investigate differences and closed as INVALID // on grounds other than an identified javac bug or Eclipse bugs that // discuss the topic in depth and explain why we made a given choice static class EclipseJustification extends Excuse { private EclipseJustification(int mismatchType) { super(mismatchType); } public static EclipseJustification EclipseBug40839 = RUN_JAVAC ? // https://bugs.eclipse.org/bugs/show_bug.cgi?id=40839 new EclipseJustification(MismatchType.JavacWarningsEclipseNone) : null, EclipseBug185422 = RUN_JAVAC ? // https://bugs.eclipse.org/bugs/show_bug.cgi?id=185422 new EclipseJustification(MismatchType.JavacErrorsEclipseNone) : null, EclipseBug234815 = RUN_JAVAC ? // https://bugs.eclipse.org/bugs/show_bug.cgi?id=234815 new EclipseJustification(MismatchType.JavacErrorsEclipseNone) : null; } static class JavacHasABug extends Excuse { long pivotCompliance; int pivotMinor; int[] minorsFixed; static final int NO_FIX = -1; static final int IRRELEVANT = -2; private JavacHasABug(int mismatchType) { super(mismatchType); } private JavacHasABug(int mismatchType, int[] minorsFixed) { super(mismatchType); this.minorsFixed = minorsFixed; } private JavacHasABug(int mismatchType, long pivotCompliance, int pivotMinor) { super(mismatchType); this.pivotCompliance = pivotCompliance; this.pivotMinor = pivotMinor; } Excuse excuseFor(JavacCompiler compiler) { if (this.minorsFixed != null) { if (compiler.compliance == ClassFileConstants.JDK1_7) { return this.minorsFixed[4] > compiler.minor || this.minorsFixed[4] < 0 ? this : null; } else if (compiler.compliance == ClassFileConstants.JDK1_6) { return this.minorsFixed[3] > compiler.minor || this.minorsFixed[3] < 0 ? this : null; } else if (compiler.compliance == ClassFileConstants.JDK1_5) { return this.minorsFixed[2] > compiler.minor || this.minorsFixed[2] < 0 ? this : null; } else if (compiler.compliance == ClassFileConstants.JDK1_4) { return this.minorsFixed[1] > compiler.minor || this.minorsFixed[1] < 0 ? this : null; } else if (compiler.compliance == ClassFileConstants.JDK1_3) { return this.minorsFixed[0] > compiler.minor || this.minorsFixed[0] < 0 ? this : null; } throw new RuntimeException(); // should not get there } else if (this.pivotCompliance != 0) { if (this.pivotCompliance < compiler.compliance) { return null; } else if (this.pivotCompliance > compiler.compliance) { return this; } else { return this.pivotMinor > compiler.minor ? this : null; } } return this; } // bugs that we know precisely of public static JavacHasABug JavacBug5042462 = RUN_JAVAC ? // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=5042462 & https://bugs.eclipse.org/bugs/show_bug.cgi?id=208873 new JavacHasABug( MismatchType.JavacErrorsEclipseNone, ClassFileConstants.JDK1_7, 0 /* 1.7.0 b17 */) : null, JavacBug5061359 = RUN_JAVAC ? // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=5061359 new JavacHasABug( MismatchType.EclipseErrorsJavacNone, ClassFileConstants.JDK1_7, 0 /* 1.7.0 b03 */) : null, JavacBug6294779 = RUN_JAVAC ? // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6294779 new JavacHasABug( MismatchType.JavacErrorsEclipseNone) : null, JavacBug6302954 = RUN_JAVAC ? // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6302954 & https://bugs.eclipse.org/bugs/show_bug.cgi?id=98379 new JavacHasABug( MismatchType.JavacErrorsEclipseNone, ClassFileConstants.JDK1_7, 0 /* 1.7.0 b03 */) : null, JavacBug6400189 = RUN_JAVAC ? // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6400189 & https://bugs.eclipse.org/bugs/show_bug.cgi?id=106744 & https://bugs.eclipse.org/bugs/show_bug.cgi?id=167952 new JavacHasABug( MismatchType.EclipseErrorsJavacNone) : null, JavacBug6500701 = RUN_JAVAC ? // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6500701 & https://bugs.eclipse.org/bugs/show_bug.cgi?id=209779 new JavacHasABug( MismatchType.StandardOutputMismatch) : null, JavacBug6573446 = RUN_JAVAC ? // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6573446 & https://bugs.eclipse.org/bugs/show_bug.cgi?id=190945 new JavacHasABug( MismatchType.EclipseErrorsJavacNone) : null, JavacBug6557661 = RUN_JAVAC ? // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6557661 & https://bugs.eclipse.org/bugs/show_bug.cgi?id=129261 new JavacHasABug( MismatchType.EclipseErrorsJavacNone) : null; // bugs that have been fixed but that we've not identified public static JavacHasABug JavacBugFixed_6_10 = RUN_JAVAC ? new JavacHasABug( 0 /* all */, ClassFileConstants.JDK1_6, 10 /* 1.6.0_10_b08 or better - maybe before */) : null, JavacBugFixed_7 = RUN_JAVAC ? new JavacHasABug( 0 /* all */, ClassFileConstants.JDK1_7, 0 /* 1.7.0_b24 or better - maybe before */) : null; // bugs that have neither been fixed nor formally identified but which outcomes are obvious enough to clear any doubts public static JavacHasABug JavacGeneratesByteCodeUponWhichJavaThrowsAnException = RUN_JAVAC ? new JavacHasABug( MismatchType.StandardOutputMismatch) : null; } } // PREMATURE: Logger helps us monitor processes outputs (standard and error); // some asynchronous mechanism is needed here since not consuming // the streams fast enough can result into bad behaviors (as // documented in Process); however, we could have a single worker // take care of this static class Logger extends Thread { StringBuffer buffer; InputStream inputStream; String type; Logger(InputStream inputStream, String type) { this.inputStream = inputStream; this.type = type; this.buffer = new StringBuffer(); } Logger(InputStream inputStream, String type, StringBuffer buffer) { this.inputStream = inputStream; this.type = type; this.buffer = buffer; } public void run() { try { BufferedReader reader = new BufferedReader(new InputStreamReader(this.inputStream)); String line = null; while ((line = reader.readLine()) != null) { this.buffer./*append(this.type).append("->").*/append(line).append("\n"); } reader.close(); } catch (IOException e) { e.printStackTrace(); } } } protected static int[] DIFF_COUNTERS = new int[3]; protected static final String EVAL_DIRECTORY = Util.getOutputDirectory() + File.separator + "eval"; public static int INDENT = 2; protected static final String JAVA_NAME = File.pathSeparatorChar == ':' ? "java" : "java.exe"; protected static final String JAVAC_NAME = File.pathSeparatorChar == ':' ? "javac" : "javac.exe"; protected static String JAVAC_OUTPUT_DIR_NAME = Util.getOutputDirectory() + File.separator + "javac"; static File JAVAC_OUTPUT_DIR; protected static String javacCommandLineHeader; protected static PrintWriter javacFullLog; // flags errors so that any error in a test case prevents // java execution private static String javacFullLogFileName; protected static String javaCommandLineHeader; // needed for multiple test calls within a single test method protected static boolean javacTestErrorFlag; protected static String javacTestName; protected static IPath jdkRootDirPath; // list of available javac compilers, as defined by the jdk.roots // variable, which should hold a File.pathSeparatorChar separated // list of paths for to-be-tested JDK root directories protected static List javacCompilers = null; public static final String OUTPUT_DIR = Util.getOutputDirectory() + File.separator + "regression"; public static final String LIB_DIR = Util.getOutputDirectory() + File.separator + "lib"; public final static String PACKAGE_INFO_NAME = new String(TypeConstants.PACKAGE_INFO_NAME); public static boolean SHIFT = false; protected static final String SOURCE_DIRECTORY = Util.getOutputDirectory() + File.separator + "source"; protected String[] classpaths; protected boolean createdVerifier; protected INameEnvironment javaClassLib; protected TestVerifier verifier; public AbstractRegressionTest(String name) { super(name); } protected void checkClassFile(String className, String source, String expectedOutput) throws ClassFormatException, IOException { this.checkClassFile("", className, source, expectedOutput, ClassFileBytesDisassembler.SYSTEM); } protected void checkClassFile(String className, String source, String expectedOutput, int mode) throws ClassFormatException, IOException { this.checkClassFile("", className, source, expectedOutput, mode); } protected void checkClassFile(String directoryName, String className, String disassembledClassName, String source, String expectedOutput, int mode) throws ClassFormatException, IOException { compileAndDeploy(source, directoryName, className); try { File directory = new File(EVAL_DIRECTORY, directoryName); if (!directory.exists()) { assertTrue(".class file not generated properly in " + directory, false); } File f = new File(directory, disassembledClassName + ".class"); byte[] classFileBytes = org.eclipse.jdt.internal.compiler.util.Util.getFileByteContent(f); ClassFileBytesDisassembler disassembler = ToolFactory.createDefaultClassFileBytesDisassembler(); String result = disassembler.disassemble(classFileBytes, "\n", mode); int index = result.indexOf(expectedOutput); if (index == -1 || expectedOutput.length() == 0) { System.out.println(Util.displayString(result, 3)); } if (index == -1) { assertEquals("Wrong contents", expectedOutput, result); } FileInputStream stream = null; try { stream = new FileInputStream(f); ClassFileReader.read(stream, className + ".class", true); } catch (org.eclipse.jdt.internal.compiler.classfmt.ClassFormatException e) { e.printStackTrace(); assertTrue("ClassFormatException", false); } catch (IOException e) { e.printStackTrace(); assertTrue("IOException", false); } finally { if (stream != null) { try { stream.close(); } catch (IOException e) { /* ignore */ } } } } finally { removeTempClass(className); } } protected void checkClassFile(String directoryName, String className, String source, String expectedOutput, int mode) throws ClassFormatException, IOException { this.checkClassFile(directoryName, className, className, source, expectedOutput, mode); } protected ClassFileReader getInternalClassFile(String directoryName, String className, String disassembledClassName, String source) throws ClassFormatException, IOException { compileAndDeploy(source, directoryName, className); try { File directory = new File(EVAL_DIRECTORY, directoryName); if (!directory.exists()) { assertTrue(".class file not generated properly in " + directory, false); } File f = new File(directory, disassembledClassName + ".class"); ClassFileReader classFileReader = null; FileInputStream stream = null; try { stream = new FileInputStream(f); classFileReader = ClassFileReader.read(stream, className + ".class", true); } catch (org.eclipse.jdt.internal.compiler.classfmt.ClassFormatException e) { e.printStackTrace(); assertTrue("ClassFormatException", false); } catch (IOException e) { e.printStackTrace(); assertTrue("IOException", false); } finally { if (stream != null) { try { stream.close(); } catch (IOException e) { /* ignore */ } } } return classFileReader; } finally { removeTempClass(className); } } protected void checkDisassembledClassFile(String fileName, String className, String expectedOutput) throws Exception { this.checkDisassembledClassFile(fileName, className, expectedOutput, ClassFileBytesDisassembler.DETAILED); } protected void checkDisassembledClassFile(String fileName, String className, String expectedOutput, int mode) throws Exception { File classFile = new File(fileName); if (!classFile.exists()) { assertTrue(".class file doesn't exist", false); } byte[] classFileBytes = org.eclipse.jdt.internal.compiler.util.Util.getFileByteContent(classFile); ClassFileBytesDisassembler disassembler = ToolFactory.createDefaultClassFileBytesDisassembler(); String result = disassembler.disassemble(classFileBytes, "\n", mode); int index = result.indexOf(expectedOutput); if (index == -1 || expectedOutput.length() == 0) { System.out.println(Util.displayString(result, 2)); } if (index == -1) { assertEquals("Wrong contents", expectedOutput, result); } FileInputStream stream = null; try { stream = new FileInputStream(classFile); ClassFileReader.read(stream, className + ".class", true); } finally { if (stream != null) { try { stream.close(); } catch (IOException e) { /* ignore */ } } } } protected void compileAndDeploy(String source, String directoryName, String className) { File directory = new File(SOURCE_DIRECTORY); if (!directory.exists()) { if (!directory.mkdirs()) { System.out.println("Could not create " + SOURCE_DIRECTORY); return; } } if (directoryName != null && directoryName.length() != 0) { directory = new File(SOURCE_DIRECTORY, directoryName); if (!directory.exists()) { if (!directory.mkdirs()) { System.out.println("Could not create " + directory); return; } } } String fileName = directory.getAbsolutePath() + File.separator + className + ".java"; try { BufferedWriter writer = new BufferedWriter(new FileWriter(fileName)); writer.write(source); writer.flush(); writer.close(); } catch (IOException e) { e.printStackTrace(); return; } StringBuffer buffer = new StringBuffer() .append("\"") .append(fileName) .append("\" -d \"") .append(EVAL_DIRECTORY); if (this.complianceLevel < ClassFileConstants.JDK1_5) { buffer.append("\" -1.4 -source 1.3 -target 1.2"); } else if (this.complianceLevel == ClassFileConstants.JDK1_5) { buffer.append("\" -1.5"); } else if (this.complianceLevel == ClassFileConstants.JDK1_6) { buffer.append("\" -1.6"); } else if (this.complianceLevel == ClassFileConstants.JDK1_7) { buffer.append("\" -1.7"); } buffer .append(" -preserveAllLocals -nowarn -g -classpath \"") .append(Util.getJavaClassLibsAsString()) .append(SOURCE_DIRECTORY) .append("\""); BatchCompiler.compile(buffer.toString(), new PrintWriter(System.out), new PrintWriter(System.err), null/*progress*/); } /* * Compute the problem log from given requestor and compare the result to * the expected one. * When there's a difference, display the expected output in the console as * code string to allow easy copy/paste in the test to fix the failure. * Also write test files to the console output. * Fail if exception is non null. */ protected void checkCompilerLog(String[] testFiles, Requestor requestor, String platformIndependantExpectedLog, Throwable exception) { String computedProblemLog = Util.convertToIndependantLineDelimiter(requestor.problemLog.toString()); if (!platformIndependantExpectedLog.equals(computedProblemLog)) { System.out.println(getClass().getName() + '#' + getName()); System.out.println(Util.displayString(computedProblemLog, INDENT, SHIFT)); for (int i = 0; i < testFiles.length; i += 2) { System.out.print(testFiles[i]); System.out.println(" ["); //$NON-NLS-1$ System.out.println(testFiles[i + 1]); System.out.println("]"); //$NON-NLS-1$ } } if (exception == null) { assertEquals("Invalid problem log ", platformIndependantExpectedLog, computedProblemLog); } } protected void dualPrintln(String message) { System.out.println(message); javacFullLog.println(message); } protected void executeClass( String sourceFile, String expectedSuccessOutputString, String[] classLib, boolean shouldFlushOutputDirectory, String[] vmArguments, Map customOptions, ICompilerRequestor clientRequestor) { // Compute class name by removing ".java" and replacing slashes with dots String className = sourceFile.substring(0, sourceFile.length() - 5).replace('/', '.').replace('\\', '.'); if (className.endsWith(PACKAGE_INFO_NAME)) return; if (vmArguments != null) { if (this.verifier != null) { this.verifier.shutDown(); } this.verifier = new TestVerifier(false); this.createdVerifier = true; } boolean passed = this.verifier.verifyClassFiles( sourceFile, className, expectedSuccessOutputString, this.classpaths, null, vmArguments); assertTrue(this.verifier.failureReason, // computed by verifyClassFiles(...) action passed); if (vmArguments != null) { if (this.verifier != null) { this.verifier.shutDown(); } this.verifier = new TestVerifier(false); this.createdVerifier = true; } } /* * Returns the references in the given .class file. */ protected String findReferences(String classFilePath) { // check that "new Z().init()" is bound to "AbstractB.init()" final StringBuffer references = new StringBuffer(10); final SearchParticipant participant = new JavaSearchParticipant() { final SearchParticipant searchParticipant = this; public SearchDocument getDocument(final String documentPath) { return new SearchDocument(documentPath, this.searchParticipant) { public byte[] getByteContents() { try { return org.eclipse.jdt.internal.compiler.util.Util.getFileByteContent(new File(getPath())); } catch (IOException e) { e.printStackTrace(); return null; } } public char[] getCharContents() { // not used return null; } public String getEncoding() { // not used return null; } }; } }; SearchDocument document = participant.getDocument(new File(classFilePath).getPath()); BinaryIndexer indexer = new BinaryIndexer(document) { protected void addIndexEntry(char[] category, char[] key) { references.append(category); references.append('/'); references.append(key); references.append('\n'); } }; indexer.indexDocument(); String computedReferences = references.toString(); return computedReferences; } protected ClassFileReader getClassFileReader(String fileName, String className) { File classFile = new File(fileName); if (!classFile.exists()) { assertTrue(".class file doesn't exist", false); } FileInputStream stream = null; try { stream = new FileInputStream(classFile); ClassFileReader reader = ClassFileReader.read(stream, className + ".class", true); return reader; } catch (org.eclipse.jdt.internal.compiler.classfmt.ClassFormatException e) { e.printStackTrace(); assertTrue("ClassFormatException", false); } catch (IOException e) { e.printStackTrace(); assertTrue("IOException", false); } finally { if (stream != null) { try { stream.close(); } catch (IOException e) { /* ignore */ } } } return null; } protected INameEnvironment[] getClassLibs() { String encoding = (String)getCompilerOptions().get(CompilerOptions.OPTION_Encoding); if ("".equals(encoding)) encoding = null; INameEnvironment[] classLibs = new INameEnvironment[1]; classLibs[0] = new FileSystem(this.classpaths, new String[]{}, // ignore initial file names encoding // default encoding ); return classLibs; } protected Map getCompilerOptions() { Map defaultOptions = super.getCompilerOptions(); defaultOptions.put(CompilerOptions.OPTION_LocalVariableAttribute, CompilerOptions.GENERATE); defaultOptions.put(CompilerOptions.OPTION_ReportUnusedPrivateMember, CompilerOptions.WARNING); defaultOptions.put(CompilerOptions.OPTION_ReportUnusedImport, CompilerOptions.WARNING); defaultOptions.put(CompilerOptions.OPTION_ReportLocalVariableHiding, CompilerOptions.WARNING); defaultOptions.put(CompilerOptions.OPTION_ReportFieldHiding, CompilerOptions.WARNING); defaultOptions.put(CompilerOptions.OPTION_ReportPossibleAccidentalBooleanAssignment, CompilerOptions.WARNING); defaultOptions.put(CompilerOptions.OPTION_ReportSyntheticAccessEmulation, CompilerOptions.WARNING); defaultOptions.put(CompilerOptions.OPTION_PreserveUnusedLocal, CompilerOptions.PRESERVE); defaultOptions.put(CompilerOptions.OPTION_ReportUnnecessaryElse, CompilerOptions.WARNING ); return defaultOptions; } protected String[] getDefaultClassPaths() { return Util.concatWithClassLibs(OUTPUT_DIR, false); } protected IErrorHandlingPolicy getErrorHandlingPolicy() { return new IErrorHandlingPolicy() { public boolean stopOnFirstError() { return false; } public boolean proceedOnErrors() { return true; } }; } /* * Will consider first the source units passed as arguments, then investigate the classpath: jdklib + output dir */ protected INameEnvironment getNameEnvironment(final String[] testFiles, String[] classPaths) { this.classpaths = classPaths == null ? getDefaultClassPaths() : classPaths; return new InMemoryNameEnvironment(testFiles, getClassLibs()); } protected IProblemFactory getProblemFactory() { return new DefaultProblemFactory(Locale.getDefault()); } public void initialize(CompilerTestSetup setUp) { super.initialize(setUp); if (setUp instanceof RegressionTestSetup) { RegressionTestSetup regressionTestSetUp = (RegressionTestSetup)setUp; this.javaClassLib = regressionTestSetUp.javaClassLib; this.verifier = regressionTestSetUp.verifier; } } /* * Write given source test files in current output sub-directory. * Use test name for this sub-directory name (ie. test001, test002, etc...) */ protected void printFiles(String[] testFiles) { for (int i=0, length=testFiles.length; i<length; i++) { System.out.println(testFiles[i++]); System.out.println(testFiles[i]); } System.out.println(""); } protected void printJavacResultsSummary() { if (RUN_JAVAC) { Integer count = (Integer)TESTS_COUNTERS.get(CURRENT_CLASS_NAME); if (count != null) { int newCount = count.intValue()-1; TESTS_COUNTERS.put(CURRENT_CLASS_NAME, new Integer(newCount)); if (newCount == 0) { if (DIFF_COUNTERS[0]!=0 || DIFF_COUNTERS[1]!=0 || DIFF_COUNTERS[2]!=0) { dualPrintln("==========================================================================="); dualPrintln("Results summary:"); } if (DIFF_COUNTERS[0]!=0) dualPrintln(" - "+DIFF_COUNTERS[0]+" test(s) where Javac found errors/warnings but Eclipse did not"); if (DIFF_COUNTERS[1]!=0) dualPrintln(" - "+DIFF_COUNTERS[1]+" test(s) where Eclipse found errors/warnings but Javac did not"); if (DIFF_COUNTERS[2]!=0) dualPrintln(" - "+DIFF_COUNTERS[2]+" test(s) where Eclipse and Javac did not have same output"); System.out.println("\n"); } } dualPrintln("\n\nFull results sent to " + javacFullLogFileName); javacFullLog.flush(); } } protected void removeTempClass(String className) { File dir = new File(SOURCE_DIRECTORY); String[] fileNames = dir.list(); if (fileNames != null) { for (int i = 0, max = fileNames.length; i < max; i++) { if (fileNames[i].indexOf(className) != -1) { Util.delete(SOURCE_DIRECTORY + File.separator + fileNames[i]); } } } dir = new File(EVAL_DIRECTORY); fileNames = dir.list(); if (fileNames != null) { for (int i = 0, max = fileNames.length; i < max; i++) { if (fileNames[i].indexOf(className) != -1) { Util.delete(EVAL_DIRECTORY + File.separator + fileNames[i]); } } } } // WORK replace null logs (no test) by empty string in most situations (more // complete coverage) and see what happens protected void runConformTest(String[] testFiles) { runTest( // test directory preparation true /* flush output directory */, testFiles /* test files */, // compiler options null /* no class libraries */, null /* no custom options */, false /* do not perform statements recovery */, null /* no custom requestor */, // compiler results false /* expecting no compiler errors */, null /* do not check compiler log */, // runtime options false /* do not force execution */, null /* no vm arguments */, // runtime results null /* do not check output string */, null /* do not check error string */, // javac options JavacTestOptions.DEFAULT /* default javac test options */); } protected void runConformTest(String[] testFiles, String expectedOutputString) { runTest( // test directory preparation true /* flush output directory */, testFiles /* test files */, // compiler options null /* no class libraries */, null /* no custom options */, false /* do not perform statements recovery */, null /* no custom requestor */, // compiler results false /* expecting no compiler errors */, null /* do not check compiler log */, // runtime options false /* do not force execution */, null /* no vm arguments */, // runtime results expectedOutputString /* expected output string */, null /* do not check error string */, // javac options JavacTestOptions.DEFAULT /* default javac test options */); } // WORK good candidate for elimination (3 uses) protected void runConformTest( String[] testFiles, String expectedSuccessOutputString, String[] vmArguments) { runTest( testFiles /* test files */, false /* expecting no compiler errors */, null /* do not check compiler log */, expectedSuccessOutputString /* expected output string */, null /* do not check error string */, false /* do not force execution */, null /* no class libraries */, true /* flush output directory */, vmArguments /* vm arguments */, null /* no custom options */, null /* no custom requestor */, JavacTestOptions.DEFAULT /* default javac test options */); } protected void runConformTest( String[] testFiles, String expectedOutputString, String[] classLibraries, boolean shouldFlushOutputDirectory, String[] vmArguments) { runTest( // test directory preparation shouldFlushOutputDirectory /* should flush output directory */, testFiles /* test files */, // compiler options classLibraries /* class libraries */, null /* no custom options */, false /* do not perform statements recovery */, null /* no custom requestor */, // compiler results false /* expecting no compiler errors */, null /* do not check compiler log */, // runtime options false /* do not force execution */, vmArguments /* vm arguments */, // runtime results expectedOutputString /* expected output string */, null /* do not check error string */, // javac options JavacTestOptions.DEFAULT /* default javac test options */); } protected void runConformTest( String[] testFiles, String expectedOutputString, String[] classLibraries, boolean shouldFlushOutputDirectory, String[] vmArguments, Map customOptions, ICompilerRequestor customRequestor) { runTest( // test directory preparation shouldFlushOutputDirectory /* should flush output directory */, testFiles /* test files */, // compiler options classLibraries /* class libraries */, customOptions /* custom options */, false /* do not perform statements recovery */, customRequestor /* custom requestor */, // compiler results false /* expecting no compiler errors */, null /* do not check compiler log */, // runtime options false /* do not force execution */, vmArguments /* vm arguments */, // runtime results expectedOutputString /* expected output string */, null /* do not check error string */, // javac options JavacTestOptions.DEFAULT /* default javac test options */); } // WORK good candidate for elimination (8 instances) protected void runConformTest( String[] testFiles, String expectedSuccessOutputString, String[] classLib, boolean shouldFlushOutputDirectory, String[] vmArguments, Map customOptions, ICompilerRequestor clientRequestor, boolean skipJavac) { runTest( shouldFlushOutputDirectory, testFiles, classLib, customOptions, false /* do not perform statements recovery */, clientRequestor, false, null, false, vmArguments, expectedSuccessOutputString, null, (skipJavac ? JavacTestOptions.SKIP : JavacTestOptions.DEFAULT)); } /* * Run Sun compilation using javac. * Launch compilation in a thread and verify that it does not take more than 5s * to perform it. Otherwise abort the process and log in console. * TODO (maxime) not sure we really do that 5s cap any more. * A semi verbose output is sent to the console that analyzes differences * of behaviors between javac and Eclipse on a per test basis. A more * verbose output is produced into a file which name is printed on the * console. Such files can be compared between various javac releases * to check potential changes. * To enable such tests, specify the following VM properies in the launch * configuration: * -Drun.javac=enabled * mandatory - tells the test suite to run javac tests * -Djdk.root=<the root directory of the tested javac> * optional - enables to find the javac that will be run by the tests * suite; the root directory must be specified as an absolute path and * should point to the JDK root, aka /opt/jdk1.5.0_05 for Linux or * c:/JDK_50 for Windows; in case this property is not specified, the * tests suite will use the runtime JRE of the launching configuration. * Note that enabling javac tests implies running into 1.5 compliance level * (or higher). */ protected void runJavac( String[] testFiles, final String expectedProblemLog, final String expectedSuccessOutputString, boolean shouldFlushOutputDirectory) { String testName = null; Process compileProcess = null; Process execProcess = null; try { // Init test name testName = testName(); // Cleanup javac output dir if needed File javacOutputDirectory = new File(JAVAC_OUTPUT_DIR_NAME); if (shouldFlushOutputDirectory) { Util.delete(javacOutputDirectory); } // Write files in dir writeFiles(testFiles); // Prepare command line StringBuffer cmdLine = new StringBuffer(javacCommandLineHeader); // compute extra classpath String[] classpath = Util.concatWithClassLibs(JAVAC_OUTPUT_DIR_NAME, false); StringBuffer cp = new StringBuffer(" -classpath "); int length = classpath.length; for (int i = 0; i < length; i++) { if (i > 0) cp.append(File.pathSeparatorChar); if (classpath[i].indexOf(" ") != -1) { cp.append("\"" + classpath[i] + "\""); } else { cp.append(classpath[i]); } } cmdLine.append(cp); // add source files for (int i = 0; i < testFiles.length; i += 2) { // *.java is not enough (p1/X.java, p2/Y.java) cmdLine.append(' '); cmdLine.append(testFiles[i]); } // Launch process compileProcess = Runtime.getRuntime().exec( cmdLine.toString(), null, this.outputTestDirectory); // Log errors Logger errorLogger = new Logger(compileProcess.getErrorStream(), "ERROR"); // Log output Logger outputLogger = new Logger(compileProcess.getInputStream(), "OUTPUT"); // start the threads to run outputs (standard/error) errorLogger.start(); outputLogger.start(); // Wait for end of process int exitValue = compileProcess.waitFor(); errorLogger.join(); // make sure we get the whole output outputLogger.join(); // Report raw javac results if (! testName.equals(javacTestName)) { javacTestName = testName; javacTestErrorFlag = false; javacFullLog.println("-----------------------------------------------------------------"); javacFullLog.println(CURRENT_CLASS_NAME + " " + testName); } if (exitValue != 0) { javacTestErrorFlag = true; } if (errorLogger.buffer.length() > 0) { javacFullLog.println("--- javac err: ---"); javacFullLog.println(errorLogger.buffer.toString()); } if (outputLogger.buffer.length() > 0) { javacFullLog.println("--- javac out: ---"); javacFullLog.println(outputLogger.buffer.toString()); } // Compare compilation results if (expectedProblemLog == null || expectedProblemLog.length() == 0) { // Eclipse found no error and no warning if (exitValue != 0) { // Javac found errors System.out.println("----------------------------------------"); System.out.println(testName + " - Javac has found error(s) but Eclipse expects conform result:\n"); javacFullLog.println("JAVAC_MISMATCH: Javac has found error(s) but Eclipse expects conform result"); System.out.println(errorLogger.buffer.toString()); printFiles(testFiles); DIFF_COUNTERS[0]++; } else { // Javac found no error - may have found warnings if (errorLogger.buffer.length() > 0) { System.out.println("----------------------------------------"); System.out.println(testName + " - Javac has found warning(s) but Eclipse expects conform result:\n"); javacFullLog.println("JAVAC_MISMATCH: Javac has found warning(s) but Eclipse expects conform result"); System.out.println(errorLogger.buffer.toString()); printFiles(testFiles); DIFF_COUNTERS[0]++; } if (expectedSuccessOutputString != null && !javacTestErrorFlag) { // Neither Eclipse nor Javac found errors, and we have a runtime // bench value StringBuffer javaCmdLine = new StringBuffer(javaCommandLineHeader); javaCmdLine.append(cp); javaCmdLine.append(' ').append(testFiles[0].substring(0, testFiles[0].indexOf('.'))); // assume executable class is name of first test file - PREMATURE check if this is also the case in other test fwk classes execProcess = Runtime.getRuntime().exec(javaCmdLine.toString(), null, this.outputTestDirectory); Logger logger = new Logger(execProcess.getInputStream(), ""); // PREMATURE implement consistent error policy logger.start(); exitValue = execProcess.waitFor(); logger.join(); // make sure we get the whole output String javaOutput = logger.buffer.toString().trim(); if (!expectedSuccessOutputString.equals(javaOutput)) { System.out.println("----------------------------------------"); System.out.println(testName + " - Javac and Eclipse runtime output is not the same:"); javacFullLog.println("JAVAC_MISMATCH: Javac and Eclipse runtime output is not the same"); dualPrintln("eclipse:"); dualPrintln(expectedSuccessOutputString); dualPrintln("javac:"); dualPrintln(javaOutput); System.out.println("\n"); printFiles(testFiles); // PREMATURE consider printing files to the log as well DIFF_COUNTERS[2]++; } } } } else { // Eclipse found errors or warnings if (errorLogger.buffer.length() == 0) { System.out.println("----------------------------------------"); System.out.println(testName + " - Eclipse has found error(s)/warning(s) but Javac did not find any:"); javacFullLog.println("JAVAC_MISMATCH: Eclipse has found error(s)/warning(s) but Javac did not find any"); dualPrintln("eclipse:"); dualPrintln(expectedProblemLog); printFiles(testFiles); DIFF_COUNTERS[1]++; } else if (expectedProblemLog.indexOf("ERROR") > 0 && exitValue == 0){ System.out.println("----------------------------------------"); System.out.println(testName + " - Eclipse has found error(s) but Javac only found warning(s):"); javacFullLog.println("JAVAC_MISMATCH: Eclipse has found error(s) but Javac only found warning(s)"); dualPrintln("eclipse:"); dualPrintln(expectedProblemLog); System.out.println("javac:"); System.out.println(errorLogger.buffer.toString()); printFiles(testFiles); DIFF_COUNTERS[1]++; } else { // PREMATURE refine comparison // TODO (frederic) compare warnings in each result and verify they are similar... // System.out.println(testName+": javac has found warnings :"); // System.out.print(errorLogger.buffer.toString()); // System.out.println(testName+": we're expecting warning results:"); // System.out.println(expectedProblemLog); } } } catch (InterruptedException e1) { if (compileProcess != null) compileProcess.destroy(); if (execProcess != null) execProcess.destroy(); System.out.println(testName+": Sun javac compilation was aborted!"); javacFullLog.println("JAVAC_WARNING: Sun javac compilation was aborted!"); e1.printStackTrace(javacFullLog); } catch (Throwable e) { System.out.println(testName+": could not launch Sun javac compilation!"); e.printStackTrace(); javacFullLog.println("JAVAC_ERROR: could not launch Sun javac compilation!"); e.printStackTrace(javacFullLog); // PREMATURE failing the javac pass or comparison could also fail // the test itself } finally { // Clean up written file(s) Util.delete(outputTestDirectory); } } protected boolean runJavac(String options, String[] testFileNames, String currentDirectoryPath) { Process compileProcess = null; try { // Prepare command line StringBuffer cmdLine = new StringBuffer(javacCommandLineHeader); cmdLine.append(' '); cmdLine.append(options); // add source files for (int i = 0; i < testFileNames.length; i ++) { // *.java is not enough (p1/X.java, p2/Y.java) cmdLine.append(' '); cmdLine.append(testFileNames[i]); } // Launch process File currentDirectory = new File(currentDirectoryPath); compileProcess = Runtime.getRuntime().exec( cmdLine.toString(), null, currentDirectory); // Log errors Logger errorLogger = new Logger(compileProcess.getErrorStream(), "ERROR"); errorLogger.start(); // Wait for end of process int exitValue = compileProcess.waitFor(); errorLogger.join(); // make sure we get the whole output // Check results if (exitValue != 0) { return false; } if (errorLogger.buffer.length() > 0) { System.err.println("--- javac err: ---"); System.err.println(errorLogger.buffer.toString()); return false; } } catch (Throwable e) { e.printStackTrace(System.err); } finally { if (compileProcess != null) { compileProcess.destroy(); // closes process streams } } return true; } /* * Run Sun compilation using one or more versions of javac. Compare the * results to expected ones, raising mismatches as needed. * To enable such tests, specify the following VM properies in the launch * configuration: * -Drun.javac=enabled * mandatory - tells the test suite to run javac tests * -Djdk.roots=<the root directories of the tested javac(s)> * optional - enables to find the versions of javac that will be run by * the tests suite; the root directories must be specified as a * File.pathSeparator separated list of absolute paths which should * point each to a JDK root, aka /opt/jdk1.5.0_05 for Linux or * c:/JDK_50 for Windows; in case this property is not specified, the * tests suite will use the runtime JRE of the launching configuration. * Note that enabling javac tests implies running into 1.5 compliance level * (or higher). */ // WORK unify use of output, error, log, etc... protected void runJavac( String[] testFiles, boolean expectingCompilerErrors, String expectedCompilerLog, String expectedOutputString, String expectedErrorString, boolean shouldFlushOutputDirectory, JavacTestOptions options, String[] vmArguments) { // WORK we're probably doing too much around class libraries in general - java should be able to fetch its own runtime libs // WORK reorder parameters if (options == JavacTestOptions.SKIP) { return; } String testName = testName(); Iterator compilers = javacCompilers.iterator(); while (compilers.hasNext()) { JavacCompiler compiler = (JavacCompiler) compilers.next(); if (!options.skip(compiler) && compiler.compliance == complianceLevel) { JavacTestOptions.Excuse excuse = options.excuseFor(compiler); StringBuffer compilerLog = new StringBuffer(); File javacOutputDirectory = null; int mismatch = 0; String sourceFileNames[] = null; try { // cleanup javac output dir if needed javacOutputDirectory = new File(JAVAC_OUTPUT_DIR_NAME + File.separator + compiler.rawVersion); // need to change output directory per javac version if (shouldFlushOutputDirectory) { Util.delete(javacOutputDirectory); } javacOutputDirectory.mkdirs(); // write test files for (int i = 0, length = testFiles.length; i < length; ) { String fileName = testFiles[i++]; String contents = testFiles[i++]; File file = new File(javacOutputDirectory, fileName); if (fileName.lastIndexOf('/') >= 0) { File dir = file.getParentFile(); if (!dir.exists()) { dir.mkdirs(); } } Util.writeToFile(contents, file.getPath()); } // compute source file names int testFilesLength = testFiles.length; sourceFileNames = new String[testFilesLength / 2]; for (int i = 0, j = 0; i < testFilesLength; i += 2, j++) { sourceFileNames[j] = testFiles[i]; } // compile long compilerResult = compiler.compile(javacOutputDirectory, options.getCompilerOptions() /* options */, sourceFileNames, compilerLog); // check cumulative javac results // WORK need to use a per compiler approach if (! testName.equals(javacTestName)) { javacTestName = testName; javacTestErrorFlag = false; } if ((compilerResult & JavacCompiler.EXIT_VALUE_MASK) != 0) { javacTestErrorFlag = true; } // compare compilation results if (expectingCompilerErrors) { if ((compilerResult & JavacCompiler.EXIT_VALUE_MASK) == 0) { if ((compilerResult & JavacCompiler.ERROR_LOG_MASK) == 0) { mismatch = JavacTestOptions.MismatchType.EclipseErrorsJavacNone; } else { mismatch = JavacTestOptions.MismatchType.EclipseErrorsJavacWarnings; } } } else { if ((compilerResult & JavacCompiler.EXIT_VALUE_MASK) != 0) { if (expectedCompilerLog != null /* null skips warnings test */ && expectedCompilerLog.length() > 0) { mismatch = JavacTestOptions.MismatchType.JavacErrorsEclipseWarnings; } else { mismatch = JavacTestOptions.MismatchType.JavacErrorsEclipseNone; } } else if (expectedCompilerLog != null /* null skips warnings test */) { if (expectedCompilerLog.length() > 0 && (compilerResult & JavacCompiler.ERROR_LOG_MASK) == 0) { mismatch = JavacTestOptions.MismatchType.EclipseWarningsJavacNone; } else if (expectedCompilerLog.length() == 0 && (compilerResult & JavacCompiler.ERROR_LOG_MASK) != 0) { mismatch = JavacTestOptions.MismatchType.JavacWarningsEclipseNone; } } } } catch (InterruptedException e1) { e1.printStackTrace(); mismatch = JavacTestOptions.MismatchType.JavacAborted; } catch (Throwable e) { e.printStackTrace(); mismatch = JavacTestOptions.MismatchType.JavacNotLaunched; } String output = null; String err = null; try { if ((expectedOutputString != null || expectedErrorString != null) && !javacTestErrorFlag && mismatch == 0 && sourceFileNames != null) { JavaRuntime runtime = JavaRuntime.runtimeFor(compiler); StringBuffer stderr = new StringBuffer(); StringBuffer stdout = new StringBuffer(); String vmOptions = ""; if (vmArguments != null) { int l = vmArguments.length; if (l > 0) { StringBuffer buffer = new StringBuffer(vmArguments[0]); for (int i = 1; i < l; i++) { buffer.append(' '); buffer.append(vmArguments[i]); } vmOptions = buffer.toString(); } } runtime.execute(javacOutputDirectory, vmOptions, testFiles[0].substring(0, testFiles[0].length() - 5), stdout, stderr); if (expectedOutputString != null /* null skips output test */) { output = stdout.toString().trim(); if (!expectedOutputString.equals(output)) { mismatch = JavacTestOptions.MismatchType.StandardOutputMismatch; } } // WORK move to a logic in which if stdout is empty whereas // it should have had contents, stderr is leveraged as // potentially holding indications regarding the failure if (expectedErrorString != null /* null skips error test */ && mismatch == 0) { err = stderr.toString().trim(); if (!expectedErrorString.equals(err) && // special case: command-line java does not like missing main methods !(expectedErrorString.length() == 0 && err.indexOf("java.lang.NoSuchMethodError: main") != -1)) { mismatch = JavacTestOptions.MismatchType.ErrorOutputMismatch; } } } } catch (InterruptedException e1) { e1.printStackTrace(); mismatch = JavacTestOptions.MismatchType.JavaAborted; } catch (Throwable e) { e.printStackTrace(); mismatch = JavacTestOptions.MismatchType.JavaNotLaunched; } if (mismatch != 0) { if (excuse != null && excuse.clears(mismatch)) { excuse = null; } else { System.out.println("----------------------------------------"); switch (mismatch) { case JavacTestOptions.MismatchType.EclipseErrorsJavacNone: assertEquals(testName + " - Eclipse found error(s) but Javac did not find any", "", expectedCompilerLog.toString()); break; case JavacTestOptions.MismatchType.EclipseErrorsJavacWarnings: assertEquals(testName + " - Eclipse found error(s) but Javac only found warning(s)", expectedCompilerLog.toString(), compilerLog.toString()); break; case JavacTestOptions.MismatchType.JavacErrorsEclipseNone: assertEquals(testName + " - Javac found error(s) but Eclipse did not find any", "", compilerLog.toString()); break; case JavacTestOptions.MismatchType.JavacErrorsEclipseWarnings: assertEquals(testName + " - Javac found error(s) but Eclipse only found warning(s)", expectedCompilerLog.toString(), compilerLog.toString()); break; case JavacTestOptions.MismatchType.EclipseWarningsJavacNone: assertEquals(testName + " - Eclipse found warning(s) but Javac did not find any", "", expectedCompilerLog.toString()); break; case JavacTestOptions.MismatchType.JavacWarningsEclipseNone: assertEquals(testName + " - Javac found warning(s) but Eclipse did not find any", "", compilerLog.toString()); break; case JavacTestOptions.MismatchType.StandardOutputMismatch: assertEquals(testName + " - Eclipse/Javac standard output mismatch", expectedOutputString, output); break; case JavacTestOptions.MismatchType.ErrorOutputMismatch: assertEquals(testName + " - Eclipse/Javac standard error mismatch", expectedErrorString, err); break; case JavacTestOptions.MismatchType.JavacAborted: case JavacTestOptions.MismatchType.JavacNotLaunched: fail(testName + " - Javac failure"); break; case JavacTestOptions.MismatchType.JavaAborted: case JavacTestOptions.MismatchType.JavaNotLaunched: fail(testName + " - Java failure"); break; default: throw new RuntimeException("unexpected mismatch value: " + mismatch); } } } if (excuse != null) { fail(testName + ": unused excuse " + excuse + " for compiler " + compiler); } } } } protected void runNegativeTest(String[] testFiles, String expectedCompilerLog) { runTest( // test directory preparation true /* flush output directory */, testFiles /* test files */, // compiler options null /* no class libraries */, null /* no custom options */, false /* do not perform statements recovery */, new Requestor( /* custom requestor */ false, null /* no custom requestor */, false, false), // compiler results expectedCompilerLog == null || /* expecting compiler errors */ expectedCompilerLog.indexOf("ERROR") != -1, expectedCompilerLog /* expected compiler log */, // runtime options false /* do not force execution */, null /* no vm arguments */, // runtime results null /* do not check output string */, null /* do not check error string */, // javac options JavacTestOptions.DEFAULT /* default javac test options */); } // WORK potential elimination candidate (24 calls) - else clean up inline protected void runNegativeTest( String[] testFiles, String expectedProblemLog, String[] classLib, boolean shouldFlushOutputDirectory) { runTest( shouldFlushOutputDirectory, testFiles, classLib, null, false, new Requestor( /* custom requestor */ false, null /* no custom requestor */, false, false), // compiler results expectedProblemLog == null || /* expecting compiler errors */ expectedProblemLog.indexOf("ERROR") != -1, expectedProblemLog, // runtime options false /* do not force execution */, null /* no vm arguments */, // runtime results null /* do not check output string */, null /* do not check error string */, // javac options false ? JavacTestOptions.SKIP : JavacTestOptions.DEFAULT /* javac test options */); } protected void runNegativeTest( String[] testFiles, String expectedCompilerLog, String[] classLibraries, boolean shouldFlushOutputDirectory, Map customOptions) { runTest( // test directory preparation shouldFlushOutputDirectory /* should flush output directory */, testFiles /* test files */, // compiler options classLibraries /* class libraries */, customOptions /* custom options */, false /* do not perform statements recovery */, new Requestor( /* custom requestor */ false, null /* no custom requestor */, false, false), // compiler results expectedCompilerLog == null || /* expecting compiler errors */ expectedCompilerLog.indexOf("ERROR") != -1, expectedCompilerLog /* expected compiler log */, // runtime options false /* do not force execution */, null /* no vm arguments */, // runtime results null /* do not check output string */, null /* do not check error string */, // javac options JavacTestOptions.DEFAULT /* default javac test options */); } protected void runNegativeTest( String[] testFiles, String expectedProblemLog, String[] classLibraries, boolean shouldFlushOutputDirectory, Map customOptions, boolean generateOutput, boolean showCategory, boolean showWarningToken) { runTest( // test directory preparation shouldFlushOutputDirectory /* should flush output directory */, testFiles /* test files */, // compiler options classLibraries /* class libraries */, customOptions /* custom options */, false, new Requestor( /* custom requestor */ generateOutput, null /* no custom requestor */, showCategory, showWarningToken), // compiler results expectedProblemLog == null || /* expecting compiler errors */ expectedProblemLog.indexOf("ERROR") != -1, expectedProblemLog, // runtime options false /* do not force execution */, null /* no vm arguments */, // runtime results null /* do not check output string */, null /* do not check error string */, // javac options JavacTestOptions.DEFAULT /* javac test options */); } /** * Log contains all problems (warnings+errors) */ // WORK potential candidate for elimination (19 calls) protected void runNegativeTest( String[] testFiles, String expectedCompilerLog, String[] classLibraries, boolean shouldFlushOutputDirectory, Map customOptions, boolean generateOutput, boolean showCategory, boolean showWarningToken, boolean skipJavac, boolean performStatementsRecovery) { runTest( // test directory preparation shouldFlushOutputDirectory /* should flush output directory */, testFiles /* test files */, // compiler options classLibraries /* class libraries */, customOptions /* custom options */, performStatementsRecovery /* perform statements recovery */, new Requestor( /* custom requestor */ generateOutput, null /* no custom requestor */, showCategory, showWarningToken), // compiler results expectedCompilerLog == null || /* expecting compiler errors */ expectedCompilerLog.indexOf("ERROR") != -1, expectedCompilerLog /* expected compiler log */, // runtime options false /* do not force execution */, null /* no vm arguments */, // runtime results null /* do not check output string */, null /* do not check error string */, // javac options skipJavac ? JavacTestOptions.SKIP : JavacTestOptions.DEFAULT /* javac test options */); } // WORK candidate for elimination (5 calls) protected void runNegativeTestWithExecution( String[] testFiles, String expectedCompilerLog, String expectedOutputString, String expectedErrorString, String[] classLibraries, boolean shouldFlushOutputDirectory, String[] vmArguments, Map customOptions, ICompilerRequestor clientRequestor) { runTest( // test directory preparation shouldFlushOutputDirectory /* should flush output directory */, testFiles /* test files */, // compiler options classLibraries /* class libraries */, customOptions /* custom options */, false /* do not perform statements recovery */, null /* no custom requestor */, // compiler results expectedCompilerLog == null || /* expecting compiler errors */ expectedCompilerLog.indexOf("ERROR") != -1, expectedCompilerLog /* expected compiler log */, // runtime options true /* force execution */, vmArguments /* vm arguments */, // runtime results expectedOutputString /* expected output string */, expectedErrorString /* expected error string */, // javac options JavacTestOptions.DEFAULT /* default javac test options */); // WORK javac tests did not exist in the original } protected void runTest( String[] testFiles, boolean expectingCompilerErrors, String expectedCompilerLog, String expectedOutputString, String expectedErrorString, boolean forceExecution, String[] classLibraries, boolean shouldFlushOutputDirectory, String[] vmArguments, Map customOptions, ICompilerRequestor customRequestor, boolean skipJavac) { runTest( // test directory preparation shouldFlushOutputDirectory /* should flush output directory */, testFiles /* test files */, // compiler options classLibraries /* class libraries */, customOptions /* custom options */, false /* do not perform statements recovery */, customRequestor /* custom requestor */, // compiler results expectingCompilerErrors /* expecting compiler errors */, expectedCompilerLog /* expected compiler log */, // runtime options forceExecution /* force execution */, vmArguments /* vm arguments */, // runtime results expectedOutputString /* expected output string */, expectedErrorString /* expected error string */, // javac options skipJavac ? JavacTestOptions.SKIP : JavacTestOptions.DEFAULT /* javac test options */); } // WORK get this out protected void runTest( String[] testFiles, boolean expectingCompilerErrors, String expectedCompilerLog, String expectedOutputString, String expectedErrorString, boolean forceExecution, String[] classLibraries, boolean shouldFlushOutputDirectory, String[] vmArguments, Map customOptions, ICompilerRequestor clientRequestor, JavacTestOptions javacTestOptions) { runTest( // test directory preparation shouldFlushOutputDirectory /* should flush output directory */, testFiles /* test files */, // compiler options classLibraries /* class libraries */, customOptions /* custom options */, false /* do not perform statements recovery */, clientRequestor /* custom requestor */, // compiler results expectingCompilerErrors /* expecting compiler errors */, expectedCompilerLog /* expected compiler log */, // runtime options forceExecution /* force execution */, vmArguments /* vm arguments */, // runtime results expectedOutputString /* expected output string */, expectedErrorString /* expected error string */, // javac options javacTestOptions /* javac test options */); } // This is a worker method to support regression tests. To ease policy changes, // it should not be called directly, but through the runConformTest and // runNegativeTest series. // calling templates: // runTest( // // test directory preparation // true /* flush output directory */, // false /* do not flush output directory */, // shouldFlushOutputDirectory /* should flush output directory */, // // new String[] { /* test files */ // }, // null /* no test files */, // testFiles /* test files */, // // // compiler options // null /* no class libraries */, // new String[] { /* class libraries */ // }, // classLibraries /* class libraries */, // // null /* no custom options */, // customOptions /* custom options */, // // true /* perform statements recovery */, // false /* do not perform statements recovery */, // performStatementsRecovery /* perform statements recovery */, // // null /* no custom requestor */, // customRequestor /* custom requestor */, // // // compiler results // false /* expecting no compiler errors */, // true /* expecting compiler errors */, // expectingCompilerErrors /* expecting compiler errors */, // // null /* do not check compiler log */, // "" /* expected compiler log */, // expectedCompilerLog /* expected compiler log */, // // // runtime options // false /* do not force execution */, // true /* force execution */, // forceExecution /* force execution */, // // null /* no vm arguments */, // new String[] { /* vm arguments */ // }, // vmArguments /* vm arguments */, // // // runtime results // null /* do not check output string */, // "" /* expected output string */, // expectedOutputString /* expected output string */, // // null /* do not check error string */, // "" /* expected error string */, // expectedErrorString /* expected error string */, // // // javac options // JavacTestOptions.SKIP /* skip javac tests */); // JavacTestOptions.DEFAULT /* default javac test options */); // javacTestOptions /* javac test options */); // TODO Maxime future work: // - reduce the number of tests that implicitly skip parts like logs // comparisons; while this is due to eat up more time, we will gain in // coverage (and detection of unwanted changes); of course, this will tend // to 'over constrain' some tests, but a reasonable approach would be to // unable the comparison for tests which just happen to be fine; // - check the callees statistics for wrapper methods and tune them accordingly // (aka, suppress low profile ones). private void runTest( // test directory preparation boolean shouldFlushOutputDirectory, String[] testFiles, // compiler options String[] classLibraries, Map customOptions, boolean performStatementsRecovery, ICompilerRequestor customRequestor, // compiler results boolean expectingCompilerErrors, String expectedCompilerLog, // runtime options boolean forceExecution, String[] vmArguments, // runtime results String expectedOutputString, String expectedErrorString, // javac options JavacTestOptions javacTestOptions) { // non-javac part if (shouldFlushOutputDirectory) Util.flushDirectoryContent(new File(OUTPUT_DIR)); Requestor requestor = customRequestor instanceof Requestor ? (Requestor) customRequestor : new Requestor( forceExecution, customRequestor, false, /* show category */ false /* show warning token*/); requestor.outputPath = OUTPUT_DIR.endsWith(File.separator) ? OUTPUT_DIR : OUTPUT_DIR + File.separator; // WORK should not have to test a constant? Map options = getCompilerOptions(); if (customOptions != null) { options.putAll(customOptions); } CompilerOptions compilerOptions = new CompilerOptions(options); compilerOptions.performMethodsFullRecovery = performStatementsRecovery; compilerOptions.performStatementsRecovery = performStatementsRecovery; Compiler batchCompiler = new Compiler( getNameEnvironment(new String[]{}, classLibraries), getErrorHandlingPolicy(), compilerOptions, requestor, getProblemFactory()); compilerOptions.produceReferenceInfo = true; Throwable exception = null; try { batchCompiler.compile(Util.compilationUnits(testFiles)); // compile all files together } catch(RuntimeException e){ exception = e; throw e; } catch(Error e) { exception = e; throw e; } finally { if (exception == null) { if (expectingCompilerErrors) { assertTrue("Unexpected success", requestor.hasErrors); } else if (requestor.hasErrors) { assertEquals("Unexpected failure", "", requestor.problemLog); } } if (expectedCompilerLog != null) { checkCompilerLog(testFiles, requestor, Util.convertToIndependantLineDelimiter(expectedCompilerLog), exception); } } if (!requestor.hasErrors || forceExecution) { String sourceFile = testFiles[0]; // Compute class name by removing ".java" and replacing slashes with dots String className = sourceFile.substring(0, sourceFile.length() - 5).replace('/', '.').replace('\\', '.'); if (className.endsWith(PACKAGE_INFO_NAME)) return; if (vmArguments != null) { if (this.verifier != null) { this.verifier.shutDown(); } this.verifier = new TestVerifier(false); this.createdVerifier = true; } boolean passed = this.verifier.verifyClassFiles( sourceFile, className, expectedOutputString, expectedErrorString, this.classpaths, null, vmArguments); if (!passed) { System.out.println(getClass().getName() + '#' + getName()); for (int i = 0; i < testFiles.length; i += 2) { System.out.print(testFiles[i]); System.out.println(" ["); //$NON-NLS-1$ System.out.println(testFiles[i + 1]); System.out.println("]"); //$NON-NLS-1$ } } assertTrue(this.verifier.failureReason, // computed by verifyClassFiles(...) action passed); if (vmArguments != null) { if (this.verifier != null) { this.verifier.shutDown(); } this.verifier = new TestVerifier(false); this.createdVerifier = true; } } // javac part if (RUN_JAVAC && javacTestOptions != JavacTestOptions.SKIP) { runJavac(testFiles, expectingCompilerErrors, expectedCompilerLog, expectedOutputString, expectedErrorString, shouldFlushOutputDirectory, javacTestOptions, vmArguments); } } // runConformTest( // // test directory preparation // new String[] { /* test files */ // }, // // javac options // JavacTestOptions.SKIP /* skip javac tests */); // JavacTestOptions.DEFAULT /* default javac test options */); // javacTestOptions /* javac test options */); public void runConformTest( // test directory preparation String[] testFiles, // javac options JavacTestOptions javacTestOptions) { runTest( // test directory preparation true /* flush output directory */, testFiles /* test files */, // compiler options null /* no class libraries */, null /* no custom options */, false /* do not perform statements recovery */, null /* no custom requestor */, // compiler results false /* expecting no compiler errors */, "" /* expected compiler log */, // runtime options false /* do not force execution */, null /* no vm arguments */, // runtime results "" /* expected output string */, "" /* expected error string */, // javac options javacTestOptions /* javac test options */); } // runConformTest( // // test directory preparation // true /* flush output directory */, // false /* do not flush output directory */, // shouldFlushOutputDirectory /* should flush output directory */, // // new String[] { /* test files */ // }, // null /* no test files */, // testFiles /* test files */, // // // compiler results // null /* do not check compiler log */, // "" /* expected compiler log */, // expectedCompilerLog /* expected compiler log */, // // // runtime results // null /* do not check output string */, // "" /* expected output string */, // expectedOutputString /* expected output string */, // // null /* do not check error string */, // "" /* expected error string */, // expectedErrorString /* expected error string */, // // // javac options // JavacTestOptions.SKIP /* skip javac tests */); // JavacTestOptions.DEFAULT /* default javac test options */); // javacTestOptions /* javac test options */); void runConformTest( // test directory preparation boolean shouldFlushOutputDirectory, String[] testFiles, // compiler results String expectedCompilerLog, // runtime results String expectedOutputString, String expectedErrorString, // javac options JavacTestOptions javacTestOptions) { runTest( // test directory preparation shouldFlushOutputDirectory /* should flush output directory */, testFiles /* test files */, // compiler options null /* no class libraries */, null /* no custom options */, false /* do not perform statements recovery */, null /* no custom requestor */, // compiler results false /* expecting no compiler errors */, expectedCompilerLog /* expected compiler log */, // runtime options false /* do not force execution */, null /* no vm arguments */, // runtime results expectedOutputString /* expected output string */, expectedErrorString /* expected error string */, // javac options javacTestOptions /* javac test options */); } // runConformTest( // // test directory preparation // true /* flush output directory */, // false /* do not flush output directory */, // // new String[] { /* test files */ // }, // null /* no test files */, // // // compiler options // null /* no class libraries */, // new String[] { /* class libraries */ // }, // // null /* no custom options */, // customOptions /* custom options */, // // // compiler results // null /* do not check compiler log */, // "" /* expected compiler log */, // // // runtime results // null /* do not check output string */, // "" /* expected output string */, // expectedOutputString /* expected output string */, // // null /* do not check error string */, // "" /* expected error string */, // expectedErrorString /* expected error string */, // // // javac options // JavacTestOptions.SKIP /* skip javac tests */); // JavacTestOptions.DEFAULT /* default javac test options */); // javacTestOptions /* javac test options */); void runConformTest( // test directory preparation boolean shouldFlushOutputDirectory, String[] testFiles, //compiler options String[] classLibraries /* class libraries */, Map customOptions /* custom options */, // compiler results String expectedCompilerLog, // runtime results String expectedOutputString, String expectedErrorString, // javac options JavacTestOptions javacTestOptions) { runTest( // test directory preparation shouldFlushOutputDirectory /* should flush output directory */, testFiles /* test files */, // compiler options classLibraries /* class libraries */, customOptions /* custom options */, false /* do not perform statements recovery */, null /* no custom requestor */, // compiler results false /* expecting no compiler errors */, expectedCompilerLog /* expected compiler log */, // runtime options false /* do not force execution */, null /* no vm arguments */, // runtime results expectedOutputString /* expected output string */, expectedErrorString /* expected error string */, // javac options javacTestOptions /* javac test options */); } // runNegativeTest( // // test directory preparation // new String[] { /* test files */ // }, // null /* no test files */, // // // compiler results // null /* do not check compiler log */, // "" /* expected compiler log */, // // // javac options // JavacTestOptions.SKIP /* skip javac tests */); // JavacTestOptions.DEFAULT /* default javac test options */); // javacTestOptions /* javac test options */); void runNegativeTest( // test directory preparation String[] testFiles, // compiler results String expectedCompilerLog, // javac options JavacTestOptions javacTestOptions) { runTest( // test directory preparation true /* flush output directory */, testFiles /* test files */, // compiler options null /* no class libraries */, null /* no custom options */, false /* do not perform statements recovery */, null /* no custom requestor */, // compiler results true /* expecting compiler errors */, expectedCompilerLog /* expected compiler log */, // runtime options false /* do not force execution */, null /* no vm arguments */, // runtime results null /* do not check output string */, null /* do not check error string */, // javac options javacTestOptions /* javac test options */); } // runNegativeTest( // // test directory preparation // true /* flush output directory */, // false /* do not flush output directory */, // shouldFlushOutputDirectory /* should flush output directory */, // // new String[] { /* test files */ // }, // null /* no test files */, // // // compiler options // null /* no class libraries */, // new String[] { /* class libraries */ // }, // classLibraries /* class libraries */, // // null /* no custom options */, // customOptions /* custom options */, // // // compiler results // null /* do not check compiler log */, // "" /* expected compiler log */, // // // javac options // JavacTestOptions.SKIP /* skip javac tests */); // JavacTestOptions.DEFAULT /* default javac test options */); // javacTestOptions /* javac test options */); void runNegativeTest( // test directory preparation boolean shouldFlushOutputDirectory, String[] testFiles, // compiler options String[] classLibraries, Map customOptions, // compiler results String expectedCompilerLog, // javac options JavacTestOptions javacTestOptions) { runTest( // test directory preparation shouldFlushOutputDirectory /* should flush output directory */, testFiles /* test files */, // compiler options classLibraries /* class libraries */, customOptions /* custom options */, false /* do not perform statements recovery */, null /* no custom requestor */, // compiler results true /* expecting compiler errors */, expectedCompilerLog /* expected compiler log */, // runtime options false /* do not force execution */, null /* no vm arguments */, // runtime results null /* do not check output string */, null /* do not check error string */, // javac options javacTestOptions /* javac test options */); } protected void setUp() throws Exception { super.setUp(); if (this.verifier == null) { this.verifier = new TestVerifier(true); this.createdVerifier = true; } if (RUN_JAVAC) { // WORK make all needed inits once and for all if (isFirst()) { if (javacFullLog == null) { // One time initialization of javac related concerns // compute command lines and extract javac version JAVAC_OUTPUT_DIR = new File(JAVAC_OUTPUT_DIR_NAME); // WORK simplify jdk.root out String jdkRootDirectory = System.getProperty("jdk.root"); if (jdkRootDirectory == null) jdkRootDirPath = (new Path(Util.getJREDirectory())).removeLastSegments(1); else jdkRootDirPath = new Path(jdkRootDirectory); StringBuffer cmdLineHeader = new StringBuffer(jdkRootDirPath. append("bin").append(JAVA_NAME).toString()); // PREMATURE replace JAVA_NAME and JAVAC_NAME with locals? depends on potential reuse javaCommandLineHeader = cmdLineHeader.toString(); cmdLineHeader = new StringBuffer(jdkRootDirPath. append("bin").append(JAVAC_NAME).toString()); cmdLineHeader.append(" -classpath . "); // start with the current directory which contains the source files Process compileProcess = Runtime.getRuntime().exec( cmdLineHeader.toString() + " -version", null, null); Logger versionLogger = new Logger(compileProcess.getErrorStream(), ""); // PREMATURE implement consistent error policy versionLogger.start(); compileProcess.waitFor(); versionLogger.join(); // make sure we get the whole output String version = versionLogger.buffer.toString(); int eol = version.indexOf('\n'); version = version.substring(0, eol); cmdLineHeader.append(" -d "); cmdLineHeader.append(JAVAC_OUTPUT_DIR_NAME.indexOf(" ") != -1 ? "\"" + JAVAC_OUTPUT_DIR_NAME + "\"" : JAVAC_OUTPUT_DIR_NAME); cmdLineHeader.append(" -source 1.5 -deprecation -Xlint:unchecked "); // enable recommended warnings // WORK new javac system does not do that... reconsider // REVIEW consider enabling all warnings instead? Philippe does not see // this as ez to use (too many changes in logs) javacCommandLineHeader = cmdLineHeader.toString(); new File(Util.getOutputDirectory()).mkdirs(); // TODO maxime check why this happens to miss in some cases // WORK if we keep a full log, it should not mix javac versions... javacFullLogFileName = Util.getOutputDirectory() + File.separatorChar + version.replace(' ', '_') + "_" + (new SimpleDateFormat("yyyyMMdd_HHmmss")).format(new Date()) + ".txt"; javacFullLog = new PrintWriter(new FileOutputStream(javacFullLogFileName)); // static that is initialized once, closed at process end javacFullLog.println(version); // so that the contents is self sufficient System.out.println("***************************************************************************"); System.out.println("* Sun Javac compiler output archived into file:"); System.out.println("* " + javacFullLogFileName); System.out.println("***************************************************************************"); javacCompilers = new ArrayList(); String jdkRoots = System.getProperty("jdk.roots"); if (jdkRoots == null) { javacCompilers.add(new JavacCompiler(jdkRootDirPath.toString())); } else { StringTokenizer tokenizer = new StringTokenizer(jdkRoots, File.pathSeparator); while (tokenizer.hasMoreTokens()) { javacCompilers.add(new JavacCompiler(tokenizer.nextToken())); } } } // per class initialization CURRENT_CLASS_NAME = getClass().getName(); dualPrintln("***************************************************************************"); System.out.print("* Comparison with Sun Javac compiler for class "); dualPrintln(CURRENT_CLASS_NAME.substring(CURRENT_CLASS_NAME.lastIndexOf('.')+1) + " (" + TESTS_COUNTERS.get(CURRENT_CLASS_NAME) + " tests)"); System.out.println("***************************************************************************"); DIFF_COUNTERS[0] = 0; DIFF_COUNTERS[1] = 0; DIFF_COUNTERS[2] = 0; } } } public void stop() { this.verifier.shutDown(); } protected void tearDown() throws Exception { if (this.createdVerifier) { this.stop(); } // clean up output dir File outputDir = new File(OUTPUT_DIR); if (outputDir.exists()) { Util.flushDirectoryContent(outputDir); } super.tearDown(); if (RUN_JAVAC) { if (JAVAC_OUTPUT_DIR.exists()) { Util.flushDirectoryContent(JAVAC_OUTPUT_DIR); } printJavacResultsSummary(); } } }
e51bab3137feb87d320127885c68960ddeb04e80
e7ffc81ad06a842645527cf81a5fc2659f86e21f
/app/src/test/java/com/mohsenafana/BakingApp/ExampleUnitTest.java
7acaef6251f3add16fac2ec6115ac54b3272aa51
[]
no_license
MohsenAfana/BakingApp
14d4a7ffb0cd7eebd724297828151eec57460ea2
2286b8a62b662a14808b17f08679e733037c6cf2
refs/heads/master
2020-04-13T05:41:58.280406
2018-12-24T15:55:50
2018-12-24T15:55:50
163,000,014
0
0
null
null
null
null
UTF-8
Java
false
false
414
java
package com.mohsenafana.BakingApp; import org.junit.Test; import static org.junit.Assert.assertEquals; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
f63d2949ca7f57725aeb9fbf170f6ad81929e353
07136cff3669f908e320edd8a643a08fd822a56d
/lore-material/material-core/src/main/java/im/heart/material/service/impl/MaterialPeriodicalServiceImpl.java
d80645898d8fc65320fd7fd7c9dad35078efee5f
[]
no_license
LKG/lore_1
68b82bd0f2bc57d9de4cd9a5d40bad37189f53ad
3c72ef40f5f631d9196a0ad29fe9b4f4fb338917
refs/heads/master
2020-04-07T15:44:46.764269
2018-12-16T15:43:48
2018-12-16T15:43:48
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,285
java
package im.heart.material.service.impl; import java.math.BigInteger; import java.util.Collection; import java.util.HashSet; import java.util.List; import com.google.common.collect.Sets; import im.heart.core.CommonConst; import im.heart.core.enums.Status; import im.heart.core.service.impl.CommonServiceImpl; import im.heart.material.entity.MaterialPeriodicalImg; import im.heart.material.repository.MaterialPeriodicalImgRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.domain.Specification; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import im.heart.material.entity.MaterialPeriodical; import im.heart.material.entity.MaterialPeriodical.PeriodicalType; import im.heart.material.repository.MaterialPeriodicalRepository; import im.heart.material.service.MaterialPeriodicalService; import im.heart.core.service.ServiceException; import im.heart.core.plugins.persistence.DynamicSpecifications; import im.heart.core.plugins.persistence.SearchFilter; import im.heart.core.plugins.persistence.SearchFilter.Operator; @Service(value = MaterialPeriodicalService.BEAN_NAME) @Transactional(propagation = Propagation.SUPPORTS,rollbackFor = Exception.class) public class MaterialPeriodicalServiceImpl extends CommonServiceImpl<MaterialPeriodical, BigInteger> implements MaterialPeriodicalService { @Autowired private MaterialPeriodicalRepository materialPeriodicalRepository; @Autowired private MaterialPeriodicalImgRepository materialPeriodicalImgRepository; @Override public List<MaterialPeriodical> findAllById(Iterable<BigInteger> ids ) { return this.materialPeriodicalRepository.findAllById(ids); } @Override public void deleteById(BigInteger id) throws ServiceException{ this.materialPeriodicalRepository.deleteById(id); this.materialPeriodicalImgRepository.deleteByPeriodicalId(id); } @Override public List<MaterialPeriodical> findByStatusAndType(Status status, PeriodicalType type) { final Collection<SearchFilter> filters = Sets.newHashSet(); filters.add(new SearchFilter("status", Operator.EQ, status)); filters.add(new SearchFilter("periodicalType", Operator.EQ, type.value+"")); Specification<MaterialPeriodical> spec = DynamicSpecifications.bySearchFilter(filters, MaterialPeriodical.class); return this.materialPeriodicalRepository.findAll(spec); } @Override public Page<MaterialPeriodical> findInitPeriodicalByType(PeriodicalType type,Pageable pageable) { final Collection<SearchFilter> filters = Sets.newHashSet(); filters.add(new SearchFilter("status", Operator.EQ, CommonConst.FlowStatus.INITIAL)); filters.add(new SearchFilter("periodicalType", Operator.EQ, type.value+"")); Specification<MaterialPeriodical> spec = DynamicSpecifications.bySearchFilter(filters, MaterialPeriodical.class); return this.materialPeriodicalRepository.findAll(spec,pageable); } @Override public void updateStatusByPeriodicalId(BigInteger periodicalId,Status status){ this.materialPeriodicalRepository.updateStatusByPeriodicalId(periodicalId,status); }; }
51e1df8ff0f08556d31f9ed168984ef74b57c06a
e93e71f22156447c120209f2da8b8a91fbe1495f
/src/com/metier/Usager.java
d0616867029841a782f8c1b80b4283a8d4773fa6
[]
no_license
bavencoff-a/triselVersionHibernet
f7b6eae72291bff378632b70ff48f1a4d6c2ada6
3c191647ab36ab8772ce3f63e7c5b05d81965cbd
refs/heads/master
2016-08-11T21:50:46.644538
2016-03-31T16:31:25
2016-03-31T16:31:25
55,166,044
0
0
null
null
null
null
UTF-8
Java
false
false
4,702
java
package com.metier; import java.util.List; import javax.persistence.*; @Entity @Table (name="usager") @Inheritance (strategy=InheritanceType.JOINED) public class Usager { @Id @Column (name = "idUsager") private String idUsager; @Column (name = "nom") private String nom; @Column (name = "prenom") private String prenom; @Column (name="adresse_Rue") private String adresseRueUsager; @Column (name="adresse_Ville") private String adresseVilleUsager; @Column (name="code_Postal") private String cpUsager; @Column (name="nomUser") private String nomUser; @Column (name="motDePasse") private String motDePasse; @OneToMany @JoinColumn(name="idUsager") private List<HabitationIndividuelle> lesHabitationsIndividuelles; @OneToMany @JoinColumn(name="idUsager") private List<Foyer> lesFoyers; /** * Constructeur de Usager * @param idUsager * @param nom * @param prenom * @param adresseRueUsager * @param adresseVilleUsager * @param cpUsager * @param nomUser * @param motDePasse */ public Usager(String idUsager, String nom, String prenom, String adresseRueUsager, String adresseVilleUsager, String cpUsager, String nomUser, String motDePasse) { super(); this.idUsager = idUsager; this.nom = nom; this.prenom = prenom; this.adresseRueUsager = adresseRueUsager; this.adresseVilleUsager = adresseVilleUsager; this.cpUsager = cpUsager; this.nomUser = nomUser; this.motDePasse = motDePasse; } /** * Constructeur de Usager */ public Usager() { super(); } /** * getNom * @return String nom */ public String getNom() { return nom; } /** * setNom * @param nom modifier le nom */ public void setNom(String nom) { this.nom = nom; } /** * getPrenom * @return String prenom */ public String getPrenom() { return prenom; } /** * setPrenom * @param prenom : modifile prenom */ public void setPrenom(String prenom) { this.prenom = prenom; } /** * getAdresseRueUsager * @return String adresseRueUsager */ public String getAdresseRueUsager() { return adresseRueUsager; } /** * setAdresseRueUsager * @param adresseRueUsager : modifi l'adresse rue de l'usager */ public void setAdresseRueUsager(String adresseRueUsager) { this.adresseRueUsager = adresseRueUsager; } /** * getAdresseVilleUsager * @return String adresseVilleUsager */ public String getAdresseVilleUsager() { return adresseVilleUsager; } /** * setAdresseVilleUsager * @param adresseVilleUsager modifi l'adresse de la ville de l'usager */ public void setAdresseVilleUsager(String adresseVilleUsager) { this.adresseVilleUsager = adresseVilleUsager; } /** * getCpUsager * @return String le code postale de l'Usager */ public String getCpUsager() { return cpUsager; } /** * setCpUsager * @param cpUsager : modifi le code postal de l'usager */ public void setCpUsager(String cpUsager) { this.cpUsager = cpUsager; } /** * getNomUser * @return String nomUser */ public String getNomUser() { return nomUser; } /** * setNomUser * @param nomUser modifie le nomUser */ public void setNomUser(String nomUser) { this.nomUser = nomUser; } /** * getMotDePasse * @return String motDePasse */ public String getMotDePasse() { return motDePasse; } /** * setMotDePasse * @param motDePasse : modifi le mot de passe de l'usager */ public void setMotDePasse(String motDePasse) { this.motDePasse = motDePasse; } /** * getIdUsager * @return String idUsager */ public String getIdUsager() { return idUsager; } /** * ToString */ @Override public String toString() { return "Usager [idUsager=" + idUsager + ", nom=" + nom + ", prenom=" + prenom + ", adresseRueUsager=" + adresseRueUsager + ", adresseVilleUsager=" + adresseVilleUsager + ", cpUsager=" + cpUsager + ", nomUser=" + nomUser + ", motDePasse=" + motDePasse + "]"; } public List<HabitationIndividuelle> getLesHabitationsIndividuelles() { return lesHabitationsIndividuelles; } public void setLesHabitationsIndividuelles(List<HabitationIndividuelle> lesHabitationsIndividuelles) { this.lesHabitationsIndividuelles = lesHabitationsIndividuelles; } public void addLesHabitationsIndividuelles(HabitationIndividuelle habitationIndividuelle) { this.lesHabitationsIndividuelles.add(habitationIndividuelle); } public List<Foyer> getLesFoyers() { return lesFoyers; } public void setLesFoyers(List<Foyer> lesFoyers) { this.lesFoyers = lesFoyers; } public void addLesFoyers(Foyer foyers) { this.lesFoyers.add(foyers); } }
5bcac3ef635fb674bf219ef7bc7f144b89fdc3b8
36a3ca40b4deaaca91d233371f8779191d745a9e
/src/graphs/KruskalMST.java
3c2bc06397663aa78584de3cb7ad08c48059690f
[]
no_license
bhasVankam/AlgoDS
4a67f9aec912ed06014ba42beaf050de358c5792
136b9835b182f6bd7e27d9f5a2cf6aa503e61fd2
refs/heads/master
2023-03-17T20:06:14.232419
2020-08-13T01:45:36
2020-08-13T01:45:36
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,535
java
package graphs; import java.util.ArrayList; import java.util.Comparator; import java.util.List; public class KruskalMST { public List<Edge<Integer>> getMST(Graph<Integer> graph) { List<Edge<Integer>> allEdges = graph.getAllEdges(); allEdges.sort(Comparator.comparingInt(Edge::getWeight)); List<Vertex<Integer>> allVertex = graph.getAllVertex(); DisjointSet disjointSet = new DisjointSet(); allVertex.forEach(a -> disjointSet.makeSet(a.getId())); List<Edge<Integer>> results = new ArrayList<>(); for(Edge e: allEdges) { Vertex vertex1 = e.getVertex1(); Vertex vertex2 = e.getVertex2(); Node left = disjointSet.find(vertex1.getId()); Node right = disjointSet.find(vertex2.getId()); if (!(left.getValue() == right.getValue())) { results.add(e); disjointSet.union(left.getValue(), right.getValue()); } } return results; } public static void main(String[] args) { Graph<Integer> graph = new Graph<>(false); graph.addEdges(1, 2, 1); graph.addEdges(1, 5, 4); graph.addEdges(1, 6, 8); graph.addEdges(5, 6, 5); graph.addEdges(6, 2, 6); graph.addEdges(2, 3, 2); graph.addEdges(7, 2, 6); graph.addEdges(6, 7, 1); graph.addEdges(7, 3, 2); graph.addEdges(3, 4, 3); graph.addEdges(3, 8, 1); graph.addEdges(7, 8, 1); graph.addEdges(4, 8, 4); KruskalMST kruskalMST = new KruskalMST(); List<Edge<Integer>> mst = kruskalMST.getMST(graph); mst.forEach(System.out::println); } }
d81a6f1bb0b7b2917eae4a5f08ef1e29f6d924dd
37b38dc2dc8148bb1dbee5a7e0da804ee3242c92
/app/src/main/java/com/feicui/mygitdroid/github/hotrepo/HotRepoAdapter.java
1d122e293d5520c2255831d9102e3998cc3f0886
[]
no_license
ccyy30/MyGitDroid
5a3769e5898d41146db56c0e7c66465c7d7bc85b
9f0c4cea6216972b819fea99bd1a3eb08d01b91e
refs/heads/master
2021-01-17T08:37:53.654507
2016-08-05T14:22:58
2016-08-05T14:22:58
64,199,101
1
0
null
null
null
null
UTF-8
Java
false
false
987
java
package com.feicui.mygitdroid.github.hotrepo; import android.content.Context; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import com.feicui.mygitdroid.github.hotrepo.repolist.RepoListFragment; import java.util.List; /** * Created by Administrator on 2016/7/27 0027. */ public class HotRepoAdapter extends FragmentPagerAdapter{ private List<Language> languages; public HotRepoAdapter(FragmentManager fm,Context context) { super(fm); languages = Language.getDefaultLanguages(context); } @Override public Fragment getItem(int position) { return RepoListFragment.getInstance(languages.get(position)); } @Override public int getCount() { return languages.size(); } //返回标题栏数据 @Override public CharSequence getPageTitle(int position) { return languages.get(position).getName(); } }
6711aef0dcbc7e34f13e704ebee5eaae33286679
fd76d488c5057e4829b2d83f01370ea260d9912b
/lib/jspf-d7e879684cc6/tests/src/net/xeoh/plugins/sandbox/PrintClasspath.java
f1cbff2618b259c3177702eec5a777c3f45a104f
[]
no_license
Energy0124/EnergyDominion
680f4931445e8eee9cca319010e5026422f8c285
263ab07e750dd6609f332f897f7fb98b48fa1326
refs/heads/master
2020-05-19T10:19:14.207419
2015-10-11T19:59:08
2015-10-11T19:59:08
13,497,109
0
0
null
null
null
null
UTF-8
Java
false
false
779
java
package net.xeoh.plugins.sandbox; import net.xeoh.plugins.base.Plugin; import net.xeoh.plugins.base.util.PluginManagerUtil; import java.net.URL; import java.net.URLClassLoader; public class PrintClasspath { public static void main(String[] args) { // Get the System Classloader ClassLoader sysClassLoader = ClassLoader.getSystemClassLoader(); // Get the URLs URL[] urls = ((URLClassLoader) sysClassLoader.getParent()).getURLs(); for (int i = 0; i < urls.length; i++) { System.out.println(urls[i].getFile()); } PluginManagerUtil util = new PluginManagerUtil(null); util.getPlugin(Plugin.class, "a", "b"); util.getPlugin(Plugin.class, "a"); util.getPlugin(Plugin.class); } }
1f93c7ca562be2d6e0cd686318bb4d2f48b8ad22
cd2a299c704b3877ba43b8bb39f42f91ae72d774
/src/test/java/com/cucumber/framework/runner/IMDb/Question_2.java
d4a65597e88a3fd75ecb93d53475fa1b46eb1dbb
[]
no_license
manivannanpannerselvam/TODOS
4ae328bda9a0c05b9c1fa0318971bcc956cf3b41
5c2330f05a5a47ae35e08b5db2ca639b2c8f3d41
refs/heads/master
2023-06-06T20:59:22.533049
2021-07-14T03:04:07
2021-07-14T03:04:07
385,789,550
0
0
null
null
null
null
UTF-8
Java
false
false
489
java
package com.cucumber.framework.runner.IMDb; import cucumber.api.CucumberOptions; import cucumber.api.testng.AbstractTestNGCucumberTests; @CucumberOptions(features = { "classpath:featurefile/todos/OfficialResource.feature"}, glue = { "classpath:com.cucumber.framework.stepdefinition", "classpath:com.cucumber.framework.helper" }, plugin = {"pretty:STDOUT","html:C:\\cucumber-pretty", "rerun:target/rerun1.txt"} ) public class Question_2 extends AbstractTestNGCucumberTests { }
8eb1474468e0806b66eda310bfbba318a4c352fe
0b7b7bf7b7d8998e02945bb0f80b53963f7e0f26
/BattleShip_Game/BattleShip_Web/src/servlets/LoginServlet.java
50e614d0b3c0edc913ea6d314c9b047d7d60e8e2
[]
no_license
amitdror/BattleShip-Game
88c898ec965292cf49b0a66c8eb3bc74ecc27649
bb9cdefb2cc8450fe658b2f5b8b876bc661c579c
refs/heads/master
2020-04-13T01:31:25.335488
2018-12-23T09:04:04
2018-12-23T09:04:04
162,876,734
0
0
null
null
null
null
UTF-8
Java
false
false
4,249
java
package servlets; import managers.UserManager; import utils.ServletUtils; import utils.SessionUtils; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class LoginServlet extends HttpServlet { public static final String USERNAME = "username"; public static final String USER_NAME_ERROR = "username_error"; private final String MAIN_ROOM = "pages/MainPage/MainPage.jsp"; private final String SIGN_UP_URL = "/index.jsp"; private final String LOGIN_ERROR_URL = "/index.jsp"; protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); String usernameFromSession = SessionUtils.getUsername(request); UserManager userManager = ServletUtils.getUserManager(getServletContext()); if (usernameFromSession == null) { //user is not logged in yet String usernameFromParameter = request.getParameter(USERNAME); if (usernameFromParameter == "") { //no username in session and no username in parameter - //redirect back to the index page //this return an HTTP code back to the browser telling it to load response.sendRedirect(SIGN_UP_URL); } else { //normalize the username value usernameFromParameter = usernameFromParameter.trim(); if(usernameFromParameter == "") { String errorMessage = "You have to put a your name in the text area"; request.setAttribute(USER_NAME_ERROR, errorMessage); getServletContext().getRequestDispatcher(LOGIN_ERROR_URL).forward(request, response); } else if (userManager.isUserExists(usernameFromParameter)) { String errorMessage = "Username " + usernameFromParameter + " already exists. Please enter a different username."; // username already exists, forward the request back to index.jsp // with a parameter that indicates that an error should be displayed // the request dispatcher obtained from the servlet context is one that MUST get an absolute path (starting with'/') // and is relative to the web app root // see this link for more details: // http://timjansen.github.io/jarfiller/guide/servlet25/requestdispatcher.xhtml request.setAttribute(USER_NAME_ERROR, errorMessage); getServletContext().getRequestDispatcher(LOGIN_ERROR_URL).forward(request, response); } else { //add the new user to the users list userManager.addUser(usernameFromParameter); //set the username in a session so it will be available on each request //the true parameter means that if a session object does not exists yet //create a new one request.getSession(true).setAttribute(USERNAME, usernameFromParameter); //redirect the request to the chat room - in order to actually change the URL System.out.println("On login, request URI is: " + request.getRequestURI()); response.sendRedirect(MAIN_ROOM); } } } else { //user is already logged in response.sendRedirect(MAIN_ROOM); } } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } @Override public String getServletInfo() { return "Login Servlet"; }// </editor-fold> }
2def282f53984a5599fdf264205c7f449e0d38ff
4108ea0acb11ca0f43b6daf961862f7a927c94d0
/petclinic-data/src/main/java/guru/springframework/sfgpetclinic/model/PetType.java
ba988ac8ceb1e2770afa1538f087eaf595b7c739
[]
no_license
Digitanalogik/spring-petclinic
aa41ed128b23736c629fde65722374357e060768
325589c55e6c67b2d877dbf4b1e88c5dcf269f4f
refs/heads/master
2020-04-07T23:55:18.953672
2019-02-13T08:47:45
2019-02-13T08:47:45
158,829,939
0
0
null
null
null
null
UTF-8
Java
false
false
361
java
package guru.springframework.sfgpetclinic.model; import lombok.*; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Table; @Setter @Getter @NoArgsConstructor @AllArgsConstructor @Builder @Entity @Table(name = "types") public class PetType extends BaseEntity { @Column(name = "name") private String name; }
98871c4b6755be3d355e30cfa1ee09f2df4f08e4
02be66fe088f3748617164d7414d0ccfff2bbc75
/core/src/main/java/eu/okaeri/configs/configurer/Configurer.java
3dc7893567a91d5b2dea6acd39f86f9f6b01825e
[ "MIT" ]
permissive
CDFN/okaeri-configs
0cc9099da83ac3b1e9610641005066bfedee7103
a5dab4c8a18978ba27dfa92bbfa5b378707642be
refs/heads/master
2023-03-30T07:47:18.039586
2021-03-31T12:44:36
2021-03-31T12:44:36
353,368,450
0
0
null
null
null
null
UTF-8
Java
false
false
12,171
java
package eu.okaeri.configs.configurer; import eu.okaeri.configs.ConfigManager; import eu.okaeri.configs.OkaeriConfig; import eu.okaeri.configs.exception.OkaeriException; import eu.okaeri.configs.schema.ConfigDeclaration; import eu.okaeri.configs.schema.FieldDeclaration; import eu.okaeri.configs.schema.GenericsDeclaration; import eu.okaeri.configs.serdes.*; import lombok.Getter; import lombok.Setter; import java.io.File; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.*; import java.util.stream.Collectors; public abstract class Configurer { @Getter @Setter private OkaeriConfig parent; private TransformerRegistry registry = new TransformerRegistry(); { this.registry.register(new DefaultSerdes()); } public void setRegistry(TransformerRegistry registry) { this.registry = registry; } public TransformerRegistry getRegistry() { return this.registry; } public void register(OkaeriSerdesPack pack) { this.registry.register(pack); } public abstract void setValue(String key, Object value, GenericsDeclaration genericType, FieldDeclaration field); public abstract Object getValue(String key); public boolean isToStringObject(Object object) { if (object instanceof Class) { Class<?> clazzObject = (Class<?>) object; return clazzObject.isEnum() || this.registry.canTransform(clazzObject, String.class); } return object.getClass().isEnum() || this.isToStringObject(object.getClass()); } @SuppressWarnings("unchecked") public Object simplifyCollection(Collection<?> value, GenericsDeclaration genericType) throws OkaeriException { List collection = new ArrayList(); GenericsDeclaration collectionSubtype = (genericType == null) ? null : genericType.getSubtype().get(0); for (Object collectionElement : value) { collection.add(this.simplify(collectionElement, collectionSubtype)); } return collection; } @SuppressWarnings("unchecked") public Object simplifyMap(Map<Object, Object> value, GenericsDeclaration genericType) throws OkaeriException { Map<Object, Object> map = new LinkedHashMap<>(); GenericsDeclaration keyDeclaration = (genericType == null) ? null : genericType.getSubtype().get(0); GenericsDeclaration valueDeclaration = (genericType == null) ? null : genericType.getSubtype().get(1); for (Map.Entry<Object, Object> entry : value.entrySet()) { Object key = this.simplify(entry.getKey(), keyDeclaration); Object kValue = this.simplify(entry.getValue(), valueDeclaration); map.put(key, kValue); } return map; } @SuppressWarnings("unchecked") public Object simplify(Object value, GenericsDeclaration genericType) throws OkaeriException { if (value == null) { return null; } if (OkaeriConfig.class.isAssignableFrom(value.getClass())) { OkaeriConfig config = (OkaeriConfig) value; return config.asMap(this); } Class<?> serializerType = (genericType != null) ? genericType.getType() : value.getClass(); ObjectSerializer serializer = this.registry.getSerializer(serializerType); if (serializer == null) { if (serializerType.isPrimitive()) { Class<?> wrappedPrimitive = GenericsDeclaration.of(serializerType).wrap(); return this.simplify(wrappedPrimitive.cast(value), GenericsDeclaration.of(wrappedPrimitive)); } if (this.isToStringObject(serializerType)) { return this.resolveType(value, genericType, String.class, null); } if (value instanceof Collection) { return this.simplifyCollection((Collection<?>) value, genericType); } if (value instanceof Map) { return this.simplifyMap((Map<Object, Object>) value, genericType); } throw new OkaeriException("cannot simplify type " + serializerType + " (" + genericType + "): '" + value + "' [" + value.getClass() + "]"); } SerializationData serializationData = new SerializationData(this); serializer.serialize(value, serializationData); return serializationData.asMap(); } public <T> T getValue(String key, Class<T> clazz, GenericsDeclaration genericType) { Object value = this.getValue(key); if (value == null) return null; return this.resolveType(value, GenericsDeclaration.of(value), clazz, genericType); } @SuppressWarnings("unchecked") public <T> T resolveType(Object object, GenericsDeclaration genericSource, Class<T> targetClazz, GenericsDeclaration genericTarget) throws OkaeriException { if (object == null) { return null; } GenericsDeclaration source = (genericSource == null) ? GenericsDeclaration.of(object) : genericSource; GenericsDeclaration target = (genericTarget == null) ? GenericsDeclaration.of(targetClazz) : genericTarget; // primitives if (target.isPrimitive()) { target = GenericsDeclaration.of(target.wrap()); } // enums Class<?> objectClazz = object.getClass(); try { if ((object instanceof String) && targetClazz.isEnum()) { String strObject = (String) object; // 1:1 match ONE=ONE try { Method enumMethod = targetClazz.getMethod("valueOf", String.class); Object enumValue = enumMethod.invoke(null, strObject); if (enumValue != null) { return targetClazz.cast(enumValue); } } // match first case-insensitive catch (InvocationTargetException ignored) { Enum[] enumValues = (Enum[]) targetClazz.getEnumConstants(); for (Enum value : enumValues) { if (!strObject.equalsIgnoreCase(value.name())) { continue; } return targetClazz.cast(value); } } // match fail String enumValuesStr = Arrays.stream(targetClazz.getEnumConstants()).map(item -> ((Enum) item).name()).collect(Collectors.joining(", ")); throw new IllegalArgumentException("no enum value for name " + strObject + " (available: " + enumValuesStr + ")"); } if (objectClazz.isEnum() && (targetClazz == String.class)) { Method enumMethod = objectClazz.getMethod("name"); return targetClazz.cast(enumMethod.invoke(object)); } } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException exception) { throw new OkaeriException("failed to resolve enum " + object.getClass() + " <> " + targetClazz, exception); } // subconfig if (OkaeriConfig.class.isAssignableFrom(targetClazz)) { OkaeriConfig config = ConfigManager.create((Class<? extends OkaeriConfig>) targetClazz); Map configMap = this.resolveType(object, source, Map.class, GenericsDeclaration.of(Map.class, Arrays.asList(String.class, Object.class))); config.setConfigurer(new InMemoryWrappedConfigurer(this, configMap)); return (T) config.update(); } // deserialization ObjectSerializer objectSerializer = this.registry.getSerializer(targetClazz); if ((object instanceof Map) && (objectSerializer != null)) { DeserializationData deserializationData = new DeserializationData((Map<String, Object>) object, this); Object deserialized = objectSerializer.deserialize(deserializationData, genericTarget); return targetClazz.cast(deserialized); } // generics if (genericTarget != null) { // collections if ((object instanceof Collection) && Collection.class.isAssignableFrom(targetClazz)) { Collection<?> sourceList = (Collection<?>) object; Collection<Object> targetList = (Collection<Object>) this.createInstance(targetClazz); GenericsDeclaration listDeclaration = genericTarget.getSubtype().get(0); for (Object item : sourceList) { Object converted = this.resolveType(item, GenericsDeclaration.of(item), listDeclaration.getType(), listDeclaration); targetList.add(converted); } return targetClazz.cast(targetList); } // maps if ((object instanceof Map) && Map.class.isAssignableFrom(targetClazz)) { Map<Object, Object> values = ((Map<Object, Object>) object); GenericsDeclaration keyDeclaration = genericTarget.getSubtype().get(0); GenericsDeclaration valueDeclaration = genericTarget.getSubtype().get(1); Map<Object, Object> map = (Map<Object, Object>) this.createInstance(targetClazz); for (Map.Entry<Object, Object> entry : values.entrySet()) { Object key = this.resolveType(entry.getKey(), GenericsDeclaration.of(entry.getKey()), keyDeclaration.getType(), keyDeclaration); Object value = this.resolveType(entry.getValue(), GenericsDeclaration.of(entry.getValue()), valueDeclaration.getType(), valueDeclaration); map.put(key, value); } return targetClazz.cast(map); } } // basic transformer ObjectTransformer transformer = this.registry.getTransformer(source, target); if (transformer == null) { // unbox primitive (Integer -> int) if (targetClazz.isPrimitive() && GenericsDeclaration.doBoxTypesMatch(targetClazz, objectClazz)) { GenericsDeclaration primitiveDeclaration = GenericsDeclaration.of(object); return (T) primitiveDeclaration.unwrapValue(object); } // transform primitives through String (int -> long) if (targetClazz.isPrimitive()) { Object simplified = this.simplify(object, GenericsDeclaration.of(objectClazz)); return this.resolveType(simplified, GenericsDeclaration.of(simplified), targetClazz, GenericsDeclaration.of(targetClazz)); } return targetClazz.cast(object); } // primitives transformer if (targetClazz.isPrimitive()) { Object transformed = transformer.transform(object); return (T) GenericsDeclaration.of(targetClazz).unwrapValue(transformed); } return targetClazz.cast(transformer.transform(object)); } public Object createInstance(Class<?> clazz) throws OkaeriException { try { if (Collection.class.isAssignableFrom(clazz)) { if (clazz == Set.class) return new HashSet<>(); if (clazz == List.class) return new ArrayList<>(); return clazz.newInstance(); } if (Map.class.isAssignableFrom(clazz)) { if (clazz == Map.class) return new LinkedHashMap<>(); return clazz.newInstance(); } throw new OkaeriException("cannot create instance of " + clazz); } catch (Exception exception) { throw new OkaeriException("failed to create instance of " + clazz, exception); } } public boolean keyExists(String key) { return this.getValue(key) != null; } public boolean isValid(FieldDeclaration declaration, Object value) { return true; } public abstract void writeToFile(File file, ConfigDeclaration declaration) throws Exception; public abstract void loadFromFile(File file, ConfigDeclaration declaration) throws Exception; }
91ef603573208d77d8460df21ee3124a38336f03
233c60d1601f5b55e6fbf0e0b894a56067499406
/src/main/java/com/schoolofnet/LearningSpark/App.java
331822cb19765d7100dc822dbb88349b4acb5c8f
[]
no_license
pedrodib/LearningSpark
137595351a487c3c0c7f7f28b17b5859d9382fa3
602115f2eefce967a5015bac5361446680c3fd60
refs/heads/master
2020-03-16T23:51:58.232001
2018-05-11T22:27:42
2018-05-11T22:27:42
133,094,168
0
0
null
null
null
null
UTF-8
Java
false
false
1,997
java
package com.schoolofnet.LearningSpark; import static spark.Spark.*; import com.google.gson.Gson; import com.schoolofnet.LearningSpark.beans.MyBean; import com.schoolofnet.LearningSpark.utils.JsonResponse; public class App { /*public static void main( String[] args ) { port(8080); ipAddress("127.0.0.1"); path("/api", () -> { get("/", (req, res) -> "Hello World from SparkJava"); post("/hello", (request, response) -> { return "Hello World"; }); post("/hello/:name", (request, response) -> { System.out.println(request.body()); System.out.println(request.queryParams("height")); response.header("CUSTOM_HEADER", "foo"); // response.redirect("/api"); response.status(200); //response.type("application/json"); return "Hello " + request.params(); }); }); }*/ /* public static void main(String[] args) { port(8080); ipAddress("127.0.0.1"); before((request, response) -> { System.out.println("Passing by Before filter"); }); path("/api", () -> { post("/:name", "application/json", (request, response) -> { System.out.println(request.body()); MyBean bean = new Gson().fromJson(request.body(), MyBean.class); System.out.println(bean.getName()); System.out.println(bean.getAge()); return new MyBean(request.params(":name")); }, new JsonResponse()); }); after((request, response) -> { response.type("application/json"); }); afterAfter((request, response) -> System.out.println("Passing by After After filter")); }*/ public static void main(String[] args) { new Config().setConfig(); new Routes().setRoutes(); } }
9b271be5b9192edad1092acb2e5d08d0133b98d1
0d505f64db6b6eac4a33a57ca6c66c507eebc535
/productservice/src/main/java/com/springcloud/product/repos/ProductRepo.java
830366de9a147ea09a40a38e65837be0266a5561
[]
no_license
avishekhsinhaRepo/Spring_Micro_Services
a231a84544cb79e37edc4e946ba29c1827f8baf4
2abc82a00e2ce9d960d2e1549f42fe8d7e5582a1
refs/heads/main
2023-08-01T06:22:43.008637
2021-09-06T01:26:54
2021-09-06T01:26:54
402,349,057
0
0
null
null
null
null
UTF-8
Java
false
false
221
java
package com.springcloud.product.repos; import org.springframework.data.jpa.repository.JpaRepository; import com.springcloud.product.model.Product; public interface ProductRepo extends JpaRepository<Product, Long> { }
64b16461734f9a15b2203abf983ab49b6233d28c
c645b47c73b3ece77b4b0f7b080008b57db001d3
/workspace/Training/src/edu/adaptive/database/client/StudentCourseDelete.java
9ac44e24919f1328527b5790fc7576fb3282805d
[]
no_license
mabruli0990/DasarJava
888c32d1437481b25b8cf908be6f1fa8364e238d
19a020ba580613947fd11cd9d29cc012a56270d8
refs/heads/master
2020-03-29T21:02:35.946765
2018-09-26T01:35:15
2018-09-26T01:35:15
150,345,746
0
0
null
null
null
null
UTF-8
Java
false
false
1,219
java
package edu.adaptive.database.client; import java.util.Scanner; import edu.adaptive.database.model.StudentCourse; import edu.adaptive.database.services.StudentCourseService; import edu.adaptive.database.services.StudentCourseServiceImpl; public class StudentCourseDelete { public void Delete() { Scanner scan = new Scanner(System.in); String strInput1 = ""; String strInput2 = ""; String strInput3 = ""; StudentCourse studentCourse = null; StudentCourseService studentCourseService = new StudentCourseServiceImpl(); System.out.println("Student_NO : "); strInput1 = scan.nextLine(); System.out.println("Course_Code : "); strInput2 = scan.nextLine(); System.out.println("Semester : "); strInput3 = scan.nextLine(); studentCourse = studentCourseService.findByUk(strInput1, strInput2, strInput3); if(studentCourse != null) { studentCourseService.delete(studentCourse.getStudentNo(), studentCourse.getCourseCode(), studentCourse.getSemester()); System.out.println("Data Mata Kuliah " + strInput1 + strInput2 + strInput3 +"Berhasil dihapus !"); } else { System.out.print("Data mata Kuliah " + strInput1 + strInput2 + strInput3 + "tidak ditemukan !"); } } }
6ee160a64fdc76bf389eccd8ece4a59191d515da
12bba6843eaaeed7e629ab3c39e80eb9650b49f6
/app/src/main/java/com/android/line/server/ParseMessage.java
230cabc8fd58b744e6a1b577817f3cf6c7141c40
[]
no_license
wconker/Line
7c7b3e694602f8e92c31d0ff3c33109464f21b24
fd10f349916e42fbce48585f4cf7a35f3db25d94
refs/heads/master
2021-01-13T16:44:57.179899
2016-12-20T14:36:57
2016-12-20T14:36:57
76,962,857
0
0
null
null
null
null
UTF-8
Java
false
false
2,400
java
package com.android.line.server; import static com.android.line.utils.Constants.CMD_LOGIN; import java.util.ArrayList; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.content.Context; import android.content.SharedPreferences.Editor; import android.os.Bundle; import android.util.Log; import com.android.line.model.PersonBean; import com.android.line.model.User; import com.android.line.utils.Constants; import com.android.line.utils.JSONUtils; import com.android.line.utils.SharedPreferencesUtils; /** * 解析来自网络、客户端的消息 * * @author by 崔明强 at 2014年9月25日 * */ public class ParseMessage { private static final String TAG = "ParseMessage"; public static int parse(String msg, Bundle outMessage, Context context) throws JSONException { JSONObject object = new JSONObject(msg); String strCmd = JSONUtils.getString(object, "cmd", "client"); int code = JSONUtils.getInt(object, "code", -1); String message = JSONUtils.getString(object, "message", "未知错误"); int cmd = toInt(strCmd);// 将字符串命令转换成Int类型 outMessage.putInt("cmd", cmd); outMessage.putInt("code", code); outMessage.putString("message", message); JSONArray jsondata = JSONUtils.getJSONArray(object, "data"); Bundle data = new Bundle(); try { switch (cmd) { case CMD_LOGIN: if (code == 0) { loginData(jsondata,outMessage); } break; default: break; } } catch (Exception e) { e.printStackTrace(); } outMessage.putBundle("data", data); return cmd; } // /** * 把字符串转成int类型的命令 * * @param cmd * @return */ public static int toInt(String cmd) { int result = 0; switch (cmd) { case "Comm.User.login": result = CMD_LOGIN; break; default: break; } return result; } /** * 解析登录返回的数据 * * @param array * @param bundle * @throws JSONException */ private static void loginData(JSONArray array, Bundle bundle) throws JSONException { if (array == null) { throw new RuntimeException("loginData中Data不能为NULL!"); } JSONObject object = array.getJSONObject(0); User user = User.createFromJSON(object); bundle.putParcelable("data", user); } }
6e3741d29dec5b02229039199e4fab95b393492f
81772c781435489f66ff07af0565bde7bbcdb097
/deltaforge-client-starter/src/main/java/net/brutus5000/deltaforge/client/DeltaforgeClientProperties.java
1cd3f21aac6b0845259e14782cdedea4ab3e5d2e
[ "MIT" ]
permissive
Brutus5000/deltaforge
6a2ff4a1a837ac2a087cf16d640eeee0ddd31f73
53d51654e06716b570c2f4d6d90833f40da6fe98
refs/heads/master
2021-07-02T20:00:00.280889
2020-08-29T13:51:53
2020-08-29T13:51:53
153,530,557
1
1
null
null
null
null
UTF-8
Java
false
false
674
java
package net.brutus5000.deltaforge.client; import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.validation.annotation.Validated; import javax.validation.constraints.NotBlank; @ConfigurationProperties(prefix = "deltaforge") @Validated @Data public class DeltaforgeClientProperties { /** * The url to the Deltaforge server. */ @NotBlank private String serverApiUrl; /** * The url to the content server serving the Deltaforge server files. */ @NotBlank private String serverContentUrl; /** * */ @NotBlank private String rootDirectory; }
8e5775725f29609ea3d0433a51ba9dd3b6ec2adb
26da0aea2ab0a2266bbee962d94a96d98a770e5f
/nam/nam-engine/src/main/java/nam/service/src/test/java/ServiceClassMainBuilder.java
c077fe001ece31e5e659b59d68b69ce1cba72e80
[ "Apache-2.0" ]
permissive
tfisher1226/ARIES
1de2bc076cf83488703cf18f7e3f6e3c5ef1b40b
814e3a4b4b48396bcd6d082e78f6519679ccaa01
refs/heads/master
2021-01-10T02:28:07.807313
2015-12-10T20:30:00
2015-12-10T20:30:00
44,076,313
2
0
null
null
null
null
UTF-8
Java
false
false
5,182
java
package nam.service.src.test.java; import java.lang.reflect.Modifier; import java.util.Iterator; import java.util.List; import nam.model.Operation; import nam.model.Service; import nam.model.util.ServiceUtil; import nam.model.util.TypeUtil; import nam.service.ServiceLayerHelper; import org.aries.util.NameUtil; import aries.codegen.AbstractBeanBuilder; import aries.generation.engine.GenerationContext; import aries.generation.model.ModelAttribute; import aries.generation.model.ModelClass; import aries.generation.model.ModelOperation; /** * Builds a simple, standalone Java application to launch a server-side * service implementation object {@link ModelClass} given a {@link Service} * Specification as input; * * Model construction properties: * <ul> * <li>generateJavadoc</li> * </ul> * * @author tfisher */ public class ServiceClassMainBuilder extends AbstractBeanBuilder { private ServiceClassMainProvider serviceClassMainProvider; public ServiceClassMainBuilder(GenerationContext context) { serviceClassMainProvider = new ServiceClassMainProvider(context); this.context = context; } public ModelClass build(Service service) throws Exception { String namespace = ServiceUtil.getNamespace(service); String packageName = ServiceLayerHelper.getServicePackageName(service); String interfaceName = ServiceLayerHelper.getServiceInterfaceName(service); String className = ServiceLayerHelper.getServiceInterfaceName(service) + "Main"; String rootName = ServiceUtil.getRootName(service); String serviceName = NameUtil.capName(interfaceName); String beanName = NameUtil.capName(className); setRootName(rootName); setBeanName(beanName); setPackageName(packageName); setClassName(className); ModelClass modelClass = new ModelClass(); modelClass.setType(org.aries.util.TypeUtil.getTypeFromNamespaceAndLocalPart(namespace, beanName)); modelClass.setPackageName(packageName); modelClass.setClassName(className); modelClass.setName(beanName); modelClass.setNamespace(namespace); ModelAttribute fileNameAttribute = new ModelAttribute(); fileNameAttribute.setModifiers(Modifier.PUBLIC+Modifier.STATIC+Modifier.FINAL); fileNameAttribute.setName("FILE_NAME"); fileNameAttribute.setClassName("String"); fileNameAttribute.setDefault("\""+NameUtil.uncapName(serviceName)+".aries\""); fileNameAttribute.setGenerateGetter(false); fileNameAttribute.setGenerateSetter(false); modelClass.addStaticAttribute(fileNameAttribute); ModelAttribute runtimeHomeAttribute = new ModelAttribute(); runtimeHomeAttribute.setModifiers(Modifier.PUBLIC+Modifier.STATIC+Modifier.FINAL); runtimeHomeAttribute.setName("RUNTIME_HOME"); runtimeHomeAttribute.setClassName("String"); runtimeHomeAttribute.setDefault("\"../"+context.getProjectName()+"\""); runtimeHomeAttribute.setGenerateGetter(false); runtimeHomeAttribute.setGenerateSetter(false); modelClass.addStaticAttribute(runtimeHomeAttribute); ModelAttribute hostNameAttribute = new ModelAttribute(); hostNameAttribute.setModifiers(Modifier.PUBLIC+Modifier.STATIC+Modifier.FINAL); hostNameAttribute.setName("HOST"); hostNameAttribute.setClassName("String"); hostNameAttribute.setDefault("\"localhost\""); hostNameAttribute.setGenerateGetter(false); hostNameAttribute.setGenerateSetter(false); modelClass.addStaticAttribute(hostNameAttribute); ModelAttribute portNumberAttribute = new ModelAttribute(); portNumberAttribute.setModifiers(Modifier.PUBLIC+Modifier.STATIC+Modifier.FINAL); portNumberAttribute.setName("PORT"); portNumberAttribute.setClassName("int"); portNumberAttribute.setDefault("9082"); portNumberAttribute.setGenerateGetter(false); portNumberAttribute.setGenerateSetter(false); modelClass.addStaticAttribute(portNumberAttribute); initializeClass(modelClass, service); return modelClass; } protected void initializeClass(ModelClass modelClass, Service service) throws Exception { //modelClass.setParentClassName("org.aries.action.AbstractAction"); initializeImportedClasses(modelClass, service); initializeInstanceFields(modelClass, service); initializeInstanceOperations(modelClass, service); } protected void initializeImportedClasses(ModelClass modelClass, Service service) throws Exception { initializeImportedClasses(modelClass, ServiceUtil.getOperations(service)); } protected void initializeImportedClasses(ModelClass modelClass, List<Operation> operations) throws Exception { Iterator<Operation> iterator = operations.iterator(); while (iterator.hasNext()) { Operation operation = iterator.next(); initializeImportedClasses(modelClass, operation); } } protected void initializeImportedClasses(ModelClass modelClass, Operation operation) throws Exception { } protected void initializeInstanceFields(ModelClass modelClass, Service service) throws Exception { } protected void initializeInstanceOperations(ModelClass modelClass, Service service) throws Exception { ModelOperation modelOperation = createMainOperation(); modelOperation.addInitialSource(serviceClassMainProvider.generate(modelClass)); modelClass.addStaticOperation(modelOperation); } }
8366ef1e0bf82db3a753b6d586703455310c20f9
2a4c9deaa1dffbda3c677902fdec798d3389332f
/src/uk/ac/ebi/age/service/impl/IdGeneratorImpl.java
744d057d78d557a0be50422bc182396221c3f02c
[]
no_license
EBIBioSamples/AGE
7583767d1b2977def6e512a545eee0883c3b1941
5f1ada98f2ef1a6ed46a928915664bad0979012e
refs/heads/master
2020-03-26T17:07:00.138863
2011-08-10T12:52:54
2011-08-10T12:52:54
2,591,007
0
0
null
null
null
null
UTF-8
Java
false
false
440
java
package uk.ac.ebi.age.service.impl; import uk.ac.ebi.age.service.IdGenerator; public class IdGeneratorImpl extends IdGenerator { private long init=(System.currentTimeMillis() - 1270000000L*1000L)*100; @Override public String getStringId() { return String.valueOf(init++); } @Override public String getStringId( String theme ) { return getStringId(); } @Override public void shutdown() { } }
ad2a144af1e3acdaabeca1b621c3c6736c1c3bcf
c9dc4dc47ef12c0ddef366ed589d7ce2a7c6d42b
/src/Cos.java
3058f78a47b3ab3cddb60d81b4c5ec850e0682fe
[]
no_license
M-Elmaghraby/MagicMathematics
16715c7ea7bb234e677ebb4bbfd1a53bf9d6d404
3056e87288b5751405f8d0254eeecc154a47fc38
refs/heads/master
2021-01-10T21:14:56.829853
2014-05-14T19:46:25
2014-05-14T19:46:25
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,123
java
/** * The implementation of the Cosine Class * * @author Hatem Moustafa & Mahmoud El-Maghraby */ public class Cos { private Polynomial angle; /** * The Constructor * * @param p * : the angle */ public Cos(Polynomial p) { angle = p; } /** * Method to evaluate the function * * @param x * : the X value * @return the value of the evaluation */ public double evaluate(double x) { double result = this.angle.evaluate(x); return Math.cos(result); } /** * Method to print the function */ public String toString() { return " Cos(" + this.angle.toString() + ")"; } /** * Method to differentiate the Cosine * * @return the derivative of the Cosine */ public Object[] differentiate() { Object[] derivative = new Object[2]; double[] coeffTerms = angle.differentiate().getCoefficients(); for (int i = 0; i < coeffTerms.length; i++) { coeffTerms[i]= (-1*coeffTerms[i]); } Polynomial coefficient = new Polynomial(coeffTerms); derivative[0] = coefficient ; derivative[1] = new Sin(angle); return derivative; } }
3e54388b7ef6c34346fbdb8b51e28fcdbe88ef63
c11e30afd6b5e6c37ac7c96a951b6117e0fa2e57
/app/src/main/java/Model/Address.java
7927b4302373c77e605ca4ef26077d04857a92bc
[]
no_license
AmeRaino/Mobile
5751a1e314787cd06006a24032582cbf29fb9759
a9a32d8e51eab704e8b1abe6a8c7df4ea78d2501
refs/heads/main
2023-06-07T14:07:03.159021
2021-06-27T03:28:20
2021-06-27T03:28:20
380,641,342
0
0
null
null
null
null
UTF-8
Java
false
false
1,821
java
package Model; public class Address { private String fullName; private String phone; private String City; private String ward; private String province; private String addressDetail; public Address() {} public Address(String fullName, String phone, String city, String ward, String province, String addressDetail) { this.fullName = fullName; this.phone = phone; City = city; this.ward = ward; this.province = province; this.addressDetail = addressDetail; } public String getFullName() { return fullName; } public void setFullName(String fullName) { this.fullName = fullName; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getCity() { return City; } public void setCity(String city) { City = city; } public String getWard() { return ward; } public void setWard(String ward) { this.ward = ward; } public String getProvince() { return province; } public void setProvince(String province) { this.province = province; } public String getAddressDetail() { return addressDetail; } public void setAddressDetail(String addressDetail) { this.addressDetail = addressDetail; } @Override public String toString() { return "Address{" + "fullName='" + fullName + '\'' + ", phone='" + phone + '\'' + ", City='" + City + '\'' + ", ward='" + ward + '\'' + ", province='" + province + '\'' + ", addressDetail='" + addressDetail + '\'' + '}'; } }
0a9e589158936df61723b4509a1aef700a99e38a
df58f4946bcdbcbd9c653733809b298ec82e20ce
/app/src/main/java/com/MAVLink/enums/AIS_TYPE.java
5b11b2470b35f11b19b50c3b4cedeb75cedd2893
[ "Apache-2.0", "MIT", "BSD-3-Clause" ]
permissive
sunny-2446/rosettadrone
d8cecc9c63e511ed9de19ec98e953405b180ac2e
9fca2776d0f51da308617aa99eb0d87e589a6b24
refs/heads/master
2022-12-19T12:53:00.482137
2020-08-29T16:30:29
2020-08-29T16:30:29
297,603,851
1
0
BSD-3-Clause
2020-09-22T09:42:51
2020-09-22T09:42:50
null
UTF-8
Java
false
false
7,163
java
/* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * java mavlink generator tool. It should not be modified by hand. */ package com.MAVLink.enums; /** * Type of AIS vessel, enum duplicated from AIS standard, https://gpsd.gitlab.io/gpsd/AIVDM.html */ public class AIS_TYPE { public static final int AIS_TYPE_UNKNOWN = 0; /* Not available (default). | */ public static final int AIS_TYPE_RESERVED_1 = 1; /* | */ public static final int AIS_TYPE_RESERVED_2 = 2; /* | */ public static final int AIS_TYPE_RESERVED_3 = 3; /* | */ public static final int AIS_TYPE_RESERVED_4 = 4; /* | */ public static final int AIS_TYPE_RESERVED_5 = 5; /* | */ public static final int AIS_TYPE_RESERVED_6 = 6; /* | */ public static final int AIS_TYPE_RESERVED_7 = 7; /* | */ public static final int AIS_TYPE_RESERVED_8 = 8; /* | */ public static final int AIS_TYPE_RESERVED_9 = 9; /* | */ public static final int AIS_TYPE_RESERVED_10 = 10; /* | */ public static final int AIS_TYPE_RESERVED_11 = 11; /* | */ public static final int AIS_TYPE_RESERVED_12 = 12; /* | */ public static final int AIS_TYPE_RESERVED_13 = 13; /* | */ public static final int AIS_TYPE_RESERVED_14 = 14; /* | */ public static final int AIS_TYPE_RESERVED_15 = 15; /* | */ public static final int AIS_TYPE_RESERVED_16 = 16; /* | */ public static final int AIS_TYPE_RESERVED_17 = 17; /* | */ public static final int AIS_TYPE_RESERVED_18 = 18; /* | */ public static final int AIS_TYPE_RESERVED_19 = 19; /* | */ public static final int AIS_TYPE_WIG = 20; /* Wing In Ground effect. | */ public static final int AIS_TYPE_WIG_HAZARDOUS_A = 21; /* | */ public static final int AIS_TYPE_WIG_HAZARDOUS_B = 22; /* | */ public static final int AIS_TYPE_WIG_HAZARDOUS_C = 23; /* | */ public static final int AIS_TYPE_WIG_HAZARDOUS_D = 24; /* | */ public static final int AIS_TYPE_WIG_RESERVED_1 = 25; /* | */ public static final int AIS_TYPE_WIG_RESERVED_2 = 26; /* | */ public static final int AIS_TYPE_WIG_RESERVED_3 = 27; /* | */ public static final int AIS_TYPE_WIG_RESERVED_4 = 28; /* | */ public static final int AIS_TYPE_WIG_RESERVED_5 = 29; /* | */ public static final int AIS_TYPE_FISHING = 30; /* | */ public static final int AIS_TYPE_TOWING = 31; /* | */ public static final int AIS_TYPE_TOWING_LARGE = 32; /* Towing: length exceeds 200m or breadth exceeds 25m. | */ public static final int AIS_TYPE_DREDGING = 33; /* Dredging or other underwater ops. | */ public static final int AIS_TYPE_DIVING = 34; /* | */ public static final int AIS_TYPE_MILITARY = 35; /* | */ public static final int AIS_TYPE_SAILING = 36; /* | */ public static final int AIS_TYPE_PLEASURE = 37; /* | */ public static final int AIS_TYPE_RESERVED_20 = 38; /* | */ public static final int AIS_TYPE_RESERVED_21 = 39; /* | */ public static final int AIS_TYPE_HSC = 40; /* High Speed Craft. | */ public static final int AIS_TYPE_HSC_HAZARDOUS_A = 41; /* | */ public static final int AIS_TYPE_HSC_HAZARDOUS_B = 42; /* | */ public static final int AIS_TYPE_HSC_HAZARDOUS_C = 43; /* | */ public static final int AIS_TYPE_HSC_HAZARDOUS_D = 44; /* | */ public static final int AIS_TYPE_HSC_RESERVED_1 = 45; /* | */ public static final int AIS_TYPE_HSC_RESERVED_2 = 46; /* | */ public static final int AIS_TYPE_HSC_RESERVED_3 = 47; /* | */ public static final int AIS_TYPE_HSC_RESERVED_4 = 48; /* | */ public static final int AIS_TYPE_HSC_UNKNOWN = 49; /* | */ public static final int AIS_TYPE_PILOT = 50; /* | */ public static final int AIS_TYPE_SAR = 51; /* Search And Rescue vessel. | */ public static final int AIS_TYPE_TUG = 52; /* | */ public static final int AIS_TYPE_PORT_TENDER = 53; /* | */ public static final int AIS_TYPE_ANTI_POLLUTION = 54; /* Anti-pollution equipment. | */ public static final int AIS_TYPE_LAW_ENFORCEMENT = 55; /* | */ public static final int AIS_TYPE_SPARE_LOCAL_1 = 56; /* | */ public static final int AIS_TYPE_SPARE_LOCAL_2 = 57; /* | */ public static final int AIS_TYPE_MEDICAL_TRANSPORT = 58; /* | */ public static final int AIS_TYPE_NONECOMBATANT = 59; /* Noncombatant ship according to RR Resolution No. 18. | */ public static final int AIS_TYPE_PASSENGER = 60; /* | */ public static final int AIS_TYPE_PASSENGER_HAZARDOUS_A = 61; /* | */ public static final int AIS_TYPE_PASSENGER_HAZARDOUS_B = 62; /* | */ public static final int AIS_TYPE_AIS_TYPE_PASSENGER_HAZARDOUS_C = 63; /* | */ public static final int AIS_TYPE_PASSENGER_HAZARDOUS_D = 64; /* | */ public static final int AIS_TYPE_PASSENGER_RESERVED_1 = 65; /* | */ public static final int AIS_TYPE_PASSENGER_RESERVED_2 = 66; /* | */ public static final int AIS_TYPE_PASSENGER_RESERVED_3 = 67; /* | */ public static final int AIS_TYPE_AIS_TYPE_PASSENGER_RESERVED_4 = 68; /* | */ public static final int AIS_TYPE_PASSENGER_UNKNOWN = 69; /* | */ public static final int AIS_TYPE_CARGO = 70; /* | */ public static final int AIS_TYPE_CARGO_HAZARDOUS_A = 71; /* | */ public static final int AIS_TYPE_CARGO_HAZARDOUS_B = 72; /* | */ public static final int AIS_TYPE_CARGO_HAZARDOUS_C = 73; /* | */ public static final int AIS_TYPE_CARGO_HAZARDOUS_D = 74; /* | */ public static final int AIS_TYPE_CARGO_RESERVED_1 = 75; /* | */ public static final int AIS_TYPE_CARGO_RESERVED_2 = 76; /* | */ public static final int AIS_TYPE_CARGO_RESERVED_3 = 77; /* | */ public static final int AIS_TYPE_CARGO_RESERVED_4 = 78; /* | */ public static final int AIS_TYPE_CARGO_UNKNOWN = 79; /* | */ public static final int AIS_TYPE_TANKER = 80; /* | */ public static final int AIS_TYPE_TANKER_HAZARDOUS_A = 81; /* | */ public static final int AIS_TYPE_TANKER_HAZARDOUS_B = 82; /* | */ public static final int AIS_TYPE_TANKER_HAZARDOUS_C = 83; /* | */ public static final int AIS_TYPE_TANKER_HAZARDOUS_D = 84; /* | */ public static final int AIS_TYPE_TANKER_RESERVED_1 = 85; /* | */ public static final int AIS_TYPE_TANKER_RESERVED_2 = 86; /* | */ public static final int AIS_TYPE_TANKER_RESERVED_3 = 87; /* | */ public static final int AIS_TYPE_TANKER_RESERVED_4 = 88; /* | */ public static final int AIS_TYPE_TANKER_UNKNOWN = 89; /* | */ public static final int AIS_TYPE_OTHER = 90; /* | */ public static final int AIS_TYPE_OTHER_HAZARDOUS_A = 91; /* | */ public static final int AIS_TYPE_OTHER_HAZARDOUS_B = 92; /* | */ public static final int AIS_TYPE_OTHER_HAZARDOUS_C = 93; /* | */ public static final int AIS_TYPE_OTHER_HAZARDOUS_D = 94; /* | */ public static final int AIS_TYPE_OTHER_RESERVED_1 = 95; /* | */ public static final int AIS_TYPE_OTHER_RESERVED_2 = 96; /* | */ public static final int AIS_TYPE_OTHER_RESERVED_3 = 97; /* | */ public static final int AIS_TYPE_OTHER_RESERVED_4 = 98; /* | */ public static final int AIS_TYPE_OTHER_UNKNOWN = 99; /* | */ public static final int AIS_TYPE_ENUM_END = 100; /* | */ }
cf0f3d7d877f417ee8185d21d7527bb03a8b2146
e6459a810063dcd7c54329928040f350e341b112
/src/main/Algorithms/ManhattanDistanceHeuristic.java
8327f3c5589e5ad6106e35310ffd1518048f06da
[]
no_license
Nir-Shmuel/The-X-Puzzle
6168b392d5edbaebaa839fb912c495e1fc225a6c
b74e9afa5f55cf4e9224d59bd2e550b24ab6b547
refs/heads/master
2022-12-27T19:03:05.727490
2020-10-15T13:42:56
2020-10-15T13:42:56
258,867,446
0
0
null
null
null
null
UTF-8
Java
false
false
1,395
java
package main.Algorithms; import main.States.BoardState; import java.util.HashMap; import java.util.Map; public class ManhattanDistanceHeuristic implements HeuristicFunction<BoardState> { private Map<Integer, int[]> indexMap; @Override public void setGoalState(BoardState goalState) { indexMap = new HashMap<>(); int n = goalState.getBoard().length; int[][] board = goalState.getBoard(); // Scan & keep goal state board on Hash Map to improve heuristic time-complexity. for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { indexMap.put(board[i][j], new int[]{i, j}); } } } /* * Calculate Manhattan distance from current state to goal state. */ @Override public int apply(BoardState boardState) { int n = boardState.getBoard().length; int[][] board = boardState.getBoard(); int totalManDist = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { int cellVal = board[i][j]; int[] gXY = indexMap.get(cellVal); int gX = gXY[0]; int gY = gXY[1]; // Calculate Manhattan distance for specific cell. totalManDist += Math.abs(i - gX) + Math.abs(j - gY); } } return totalManDist; } }
9e9fcae6afede89253520d4f713996495560721b
c6c1a124eb1ff2fc561213d43d093f84d1ab2c43
/games/jigsaw/android/src/cn/javaplus/jigsaw/android/UmengConfigs.java
e20307700788c4dea2a4f19782c1bdd14e358d1b
[]
no_license
fantasylincen/javaplus
69201dba21af0973dfb224c53b749a3c0440317e
36fc370b03afe952a96776927452b6d430b55efd
refs/heads/master
2016-09-06T01:55:33.244591
2015-08-15T12:15:51
2015-08-15T12:15:51
15,601,930
3
1
null
null
null
null
UTF-8
Java
false
false
685
java
package cn.javaplus.jigsaw.android; import org.javaplus.game.common.Configs; import android.app.Activity; import com.umeng.analytics.MobclickAgent; public class UmengConfigs implements Configs { private Activity activity; public UmengConfigs(final Activity activity) { this.activity = activity; MobclickAgent.updateOnlineConfig(activity); } @Override public String getConfig(String key, String defaultValue) { try { String value = MobclickAgent.getConfigParams(activity, key); if (value == null) { return defaultValue; } return value; } catch (Throwable e) { e.printStackTrace(); return defaultValue; } } }
[ "12-2" ]
12-2
3c44d1db039178bbbe61cb71526f76be90aaf3ef
a1826c2ed9c12cfc395fb1a14c1a2e1f097155cb
/dt-oc-info-20220829/src/main/java/com/aliyun/dt_oc_info20220829/models/GetOcNegativeQualityPunishmentResponse.java
4644911431d3fc1fe85c3d7799014938e36a7b16
[ "Apache-2.0" ]
permissive
aliyun/alibabacloud-java-sdk
83a6036a33c7278bca6f1bafccb0180940d58b0b
008923f156adf2e4f4785a0419f60640273854ec
refs/heads/master
2023-09-01T04:10:33.640756
2023-09-01T02:40:45
2023-09-01T02:40:45
288,968,318
40
45
null
2023-06-13T02:47:13
2020-08-20T09:51:08
Java
UTF-8
Java
false
false
1,524
java
// This file is auto-generated, don't edit it. Thanks. package com.aliyun.dt_oc_info20220829.models; import com.aliyun.tea.*; public class GetOcNegativeQualityPunishmentResponse extends TeaModel { @NameInMap("headers") @Validation(required = true) public java.util.Map<String, String> headers; @NameInMap("statusCode") @Validation(required = true) public Integer statusCode; @NameInMap("body") @Validation(required = true) public GetOcNegativeQualityPunishmentResponseBody body; public static GetOcNegativeQualityPunishmentResponse build(java.util.Map<String, ?> map) throws Exception { GetOcNegativeQualityPunishmentResponse self = new GetOcNegativeQualityPunishmentResponse(); return TeaModel.build(map, self); } public GetOcNegativeQualityPunishmentResponse setHeaders(java.util.Map<String, String> headers) { this.headers = headers; return this; } public java.util.Map<String, String> getHeaders() { return this.headers; } public GetOcNegativeQualityPunishmentResponse setStatusCode(Integer statusCode) { this.statusCode = statusCode; return this; } public Integer getStatusCode() { return this.statusCode; } public GetOcNegativeQualityPunishmentResponse setBody(GetOcNegativeQualityPunishmentResponseBody body) { this.body = body; return this; } public GetOcNegativeQualityPunishmentResponseBody getBody() { return this.body; } }
fd6e8f08501e3f1e1f1855432f2e9d340ab71ede
8c730c8e57d6ec89923e0f0e94b78af8a5eb4745
/src/com/arogya/filereader/dao/ArogyaConnectionFactory.java
1d4b770ea1f4b381bbb158d3ac3466f1bb0d4a5e
[]
no_license
Truein/ArogyaFilePolling
e1ec983bc8cf080fa515a320862baf1f5b3dae33
861407c1996047c9bdc92c49079bb9e1686dea6d
refs/heads/master
2021-08-26T09:45:15.725098
2017-11-23T03:52:00
2017-11-23T03:52:00
111,761,181
0
0
null
null
null
null
UTF-8
Java
false
false
1,196
java
package com.arogya.filereader.dao; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; //import com.arogya.stage.db.ArogyaConnectionFactory; public class ArogyaConnectionFactory { //static reference to itself private static ArogyaConnectionFactory instance = new ArogyaConnectionFactory(); public static final String URL = "jdbc:mysql://localhost/ArogyaStagingDB"; public static final String USER = "root"; public static final String PASSWORD = "root"; public static final String DRIVER_CLASS = "com.mysql.jdbc.Driver"; private ArogyaConnectionFactory() { try { Class.forName(DRIVER_CLASS); } catch (ClassNotFoundException e) { e.printStackTrace(); } } private Connection createConnection() { Connection connection = null; try { connection = DriverManager.getConnection(URL, USER, PASSWORD); } catch (SQLException e) { e.printStackTrace(); } return connection; } public static Connection getConnection() { return instance.createConnection(); } }
[ "hduser@arogya_supp.com" ]
hduser@arogya_supp.com
588b73f7df481a94bb24c67262f1626bc8e44d69
900521857ed0f6ee9234a7a4ac15bfa2377167f1
/src/main/java/com/lambton/string_handling.java
ea5545ae16c902efa7cea0a8057bca68ea5c5b74
[]
no_license
MANBEERGIL/string
1594968c4982d9f390c79a8b394b05570b81d759
2cf68287cee9e9af4215ebf4076f6d671ff0fd80
refs/heads/master
2020-12-20T16:40:42.377511
2020-01-25T07:49:38
2020-01-25T07:49:38
236,140,947
0
0
null
null
null
null
UTF-8
Java
false
false
1,213
java
package com.lambton; public class string_handling { public static void main(String[] args) { String s[]; s =new String[5]; s[0]="canada"; s[1]="geet"; s[2]="komal"; s[3]="kamal"; s[4]="manu"; String zigzagStrings[]=new String[s.length]; System.out.println("\n_________reverse string_______"); for(int i=0;i<s.length;i++) { String zigzag = zigzagString(s[i]); zigzagStrings[i] = zigzag; System.out.println(s[i] + "<->" + zigzag); } } public static String zigzagString(String st) { String temp; char names[]= st.toCharArray(); char output[]= st.toCharArray(); int len =names.length; int count = len-len%2; for( int i =0;i<count;i+=2) { output[i]=names[i+1]; output[i+1]=names[i]; } temp = new String(output); if(len % 2 ==1) { String firstPart = temp.substring(0,len/2); String secondPart = temp.substring(len/2,len-1); temp = firstPart + output[output.length-1]+ secondPart; } return temp; } }
6023ec1df1ec27e3773168cba57e8708d2c40214
2fc30f1ba7df2dbbfa796a8bbda015a68a27261d
/Lab2/src/Bonus/Problem.java
e0a0ba117243d54bea6a277a75783fb396648591
[]
no_license
andreihaivas6/Advanced-Programming-Labs
0270e7138adafea0304c26073eefe9cfcb513a57
48d9a10c8276fcef2390b0ebe97df8464d12d140
refs/heads/main
2023-05-03T02:24:35.097091
2021-05-27T15:40:11
2021-05-27T15:40:11
340,159,118
0
0
null
null
null
null
UTF-8
Java
false
false
2,000
java
package Bonus; import java.util.Arrays; import java.util.Vector; public class Problem { protected Vector<Source> sources = new Vector<>(); protected Vector<Destination> destinations = new Vector<>(); protected int[][] costs; public Problem() { } public Problem(int[][] costs) { this.costs = costs; } public void setCosts(int[][] costs) { this.costs = costs; } public void setSources(Vector<Source> sources) { this.sources = sources; } public void setDestinations(Vector<Destination> destinations) { this.destinations = destinations; } public int[][] getCosts() { return costs; } public Vector<Source> getSources() { return sources; } public Vector<Destination> getDestinations() { return destinations; } public int getCost(int i, int j) { return costs[i][j]; } public Source getSource(int index) { return sources.get(index); } public Destination getDestination(int index) { return destinations.get(index); } @Override public String toString() { StringBuilder s = new StringBuilder("Problem {" + "\nsources = " + sources + ", \ndestinations = " + destinations + ", \ncost = ["); for (int[] line : costs) // afisam randurile din matrice pe rand s.append(Arrays.toString(line)); s.append("]}"); return s.toString(); } public void addSource(Source s) { for (Source source : sources) { // verificam existenta sursei if (source.equals(s)) { return; } } sources.add(s); } public void addDestination(Destination d) { for (Destination destination : destinations) { // verificam existenta destinatiei if (destination.equals(d)) { return; } } destinations.add(d); } }
e02f0f1d4e7cbd68c32b7d068615100a29e301d1
2d629ce27823b96b4ec6874dbe809ae8e2e55c76
/src/controller/SearchBookController.java
3d991bd565c466e7140f5e40a2e3a978be82ba1b
[]
no_license
dashrath-bawne/BookShopping
456da65e0d68b4cff408af01256f6674a9fe7d25
c892437a901b2182eaf0b065a1b162b1f8dbfd41
refs/heads/master
2021-10-08T02:15:13.460423
2014-12-10T18:31:49
2014-12-10T18:31:49
null
0
0
null
null
null
null
UTF-8
Java
false
false
6,894
java
package controller; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import javax.servlet.RequestDispatcher; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.log4j.Logger; import exception.BusinessException; import exception.DatabaseException; import vo.AddBookVO; import vo.CartDataVO; import vo.SearchBookVO; import bo.AddBookBO; import bo.SearchBookBO; public class SearchBookController extends HttpServlet { private static final long serialVersionUID = 1L; private final static Logger logger= Logger.getLogger("SearchController"); protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if(request.getSession(false)==null){ System.out.println("Inside search book controller session"); response.sendRedirect("/BookShopping/jsp/Login.jsp"); } else { /********** Logged in successfully; populate search criteria from database ***************/ if (getServletContext().getAttribute("userlogin")!=null || request.getParameter("userlogin")!=null) { System.out.println("Userlogin and search"); getServletContext().removeAttribute("userlogin"); getServletContext().removeAttribute("searchResult"); request.getSession(false).removeAttribute("result"); ArrayList list = new ArrayList(); SearchBookBO bo = new SearchBookBO(); RequestDispatcher dispatch = request .getRequestDispatcher("/jsp/SearchingAddingBooks.jsp"); try { list = bo.searchBookCriteria(); request.getSession(false).setAttribute("searchCriteria", list); //request.setAttribute("searchCriteria", "header"); logger.info("Search Criteria from database is fetched"); response.sendRedirect("/BookShopping/jsp/SearchingAddingBooks.jsp"); } catch(DatabaseException de) { DatabaseException db = new DatabaseException(); request.setAttribute("DbError", de.getErrorMessage()); dispatch.forward(request, response); } } /******* Search Button is clicked; Fetches matching data from database ************/ else if (request.getParameter("search") != null) { System.out.println("Inside search button in controller"); request.getSession(false).removeAttribute("result"); ArrayList list; SearchBookVO vo = new SearchBookVO(); vo.setCategory(request.getParameter("category")); if (!request.getParameter("price").equals("")) { vo.setPrice(Float.parseFloat(request.getParameter("price"))); } vo.setLanguage(request.getParameter("language")); vo.setBinding(request.getParameter("binding")); vo.setDeliveryTime(request.getParameter("deliverytime")); SearchBookBO bo = new SearchBookBO(); RequestDispatcher dispatch = request .getRequestDispatcher("/jsp/SearchingAddingBooks.jsp"); try { list = bo.setQuery(vo); getServletContext().setAttribute("searchResult", list); //request.setAttribute("searchResult", "SearchResult"); logger.info("search result is returned"); dispatch.forward(request,response); //dispatch.forward(request, response); } catch(DatabaseException de) { DatabaseException d = new DatabaseException(); request.setAttribute("DbError", d.getErrorMessage()); dispatch.forward(request, response); } } /*********** AddCart button is clicked; Saves data into Cart_details *********/ else if (request.getParameter("addcart") != null) { ArrayList<CartDataVO> list = new ArrayList<CartDataVO>(); request.getSession(false).removeAttribute("result"); String items[] = request.getParameterValues("items"); /******* If items in not null means atleast one book is selected ***********/ if (items != null) { for (int i = 0; i < items.length; i++) { CartDataVO vo = new CartDataVO(); vo.setBookId(Integer.parseInt(items[i])); try { vo.setQuantity(Integer.parseInt(request .getParameter(items[i]))); } catch (NumberFormatException e) { vo.setTextQuantity(request.getParameter(items[i])); vo.setQuantity(-999); } list.add(vo); } HashMap<Integer, Integer> map = (HashMap<Integer, Integer>) getServletContext() .getAttribute("availability"); AddBookBO bo = new AddBookBO(); try { ArrayList<CartDataVO> result = bo.validateBookData(list, map); /********** If result is contains false means quantity is not invalid ********************/ if (result.contains(false)) { RequestDispatcher dispatch = request .getRequestDispatcher("/jsp/SearchingAddingSuccess.jsp"); try { ArrayList result1 = bo .addBook(list, map, (Integer) request.getSession(false).getAttribute("cartid")); ArrayList<AddBookVO> cartData = (ArrayList<AddBookVO>) result1.get(0); ArrayList<CartDataVO> successData = (ArrayList<CartDataVO>)result1.get(1); getServletContext().setAttribute("searchResult", cartData); request.getSession(false).setAttribute("addsuccess", successData); logger.info("Books added to cart"); response.sendRedirect("/BookShopping/jsp/SearchingAddingSuccess.jsp"); } catch(DatabaseException de) { DatabaseException d = new DatabaseException(); request.setAttribute("DbError", d.getErrorMessage()); dispatch.forward(request, response); } } else { result.remove(true); //request.getSession(false).setAttribute("searchCriteria", "header"); //request.getSession(false).setAttribute("searchResult", "SearchResult"); request.getSession(false).setAttribute("result", result); request.getSession(false).setAttribute("Invalid Entry", "Invalid"); BusinessException b = new BusinessException(); throw b; } } catch(BusinessException be) { response.sendRedirect("/BookShopping/jsp/SearchingAddingBooks.jsp"); } } /********** None book is selected **********/ else { //request.getSession(false).setAttribute("searchCriteria", "header"); //request.getSession(false).setAttribute("searchResult", "SearchResult"); request.getSession(false).setAttribute("NoSelection", "Please select at least one book"); logger.info("No book is selected"); //RequestDispatcher dispatch = request // .getRequestDispatcher("/jsp/SearchingAddingBooks.jsp"); //dispatch.forward(request, response); response.sendRedirect("/BookShopping/jsp/SearchingAddingBooks.jsp"); } } } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
d1a8a56f10c4797309be5a8e9295b981717d1dd5
71948eb96dfaa3f4a1707bffd70487af9985f4af
/algs/src/test/java/me/jy/sort/NumericSeriesTest.java
9b9572297dcec0422a20d08faed6e8e5d26756da
[]
no_license
px307/tech
d86354960dfbee4495d1d10226f6ae221ce3cb5a
74fe24ce80153929b7a4fe080d60e98fcca7346d
refs/heads/master
2020-07-08T05:03:03.590658
2019-08-21T10:32:45
2019-08-21T10:32:45
null
0
0
null
null
null
null
UTF-8
Java
false
false
724
java
package me.jy.sort; import org.junit.Assert; import org.junit.Test; import static me.jy.sort.NumericSeries.getNextSeries; /** * @author jy */ public class NumericSeriesTest { @Test public void testGetNextSeries() { Assert.assertArrayEquals(new int[]{5, 2, 3, 4, 1}, getNextSeries(new int[]{5, 2, 3, 1, 4})); Assert.assertArrayEquals(new int[]{5, 2, 3, 1, 4}, getNextSeries(new int[]{5, 2, 1, 4, 3})); Assert.assertArrayEquals(new int[]{1, 3, 2, 3}, getNextSeries(new int[]{1, 2, 3, 3})); Assert.assertArrayEquals(new int[]{1, 3, 3, 2}, getNextSeries(new int[]{1, 3, 2, 3})); Assert.assertArrayEquals(new int[]{9, 8, 7, 6}, getNextSeries(new int[]{9, 8, 7, 6})); } }
2bec71a729029c1248de0fafe2757ceaa9bd3a72
27602550b705ec0ee08f2ca35fa6653b6d5fc53d
/Movie-Stage-2/testing/app/src/main/java/com/example/android/movie_json/database/MovieContract.java
b36c183df49bcbe93b7a010b7c75f0c54df41ecb
[ "Apache-2.0" ]
permissive
vivekingh/Udacity-Nano-Degree
4984c46d978400dea40fd186186a600b64a28d00
0ed220a2f4e589696ffcc78a633f68b571697a01
refs/heads/master
2020-03-19T04:54:43.856057
2018-09-15T09:05:34
2018-09-15T09:05:34
135,881,290
1
0
null
null
null
null
UTF-8
Java
false
false
1,023
java
package com.example.android.movie_json.database; import android.net.Uri; import android.provider.BaseColumns; public class MovieContract { public static final String AUTHORITY = "com.example.android.movie_json"; public static final Uri BASE_CONTENT_URI = Uri.parse("content://" + AUTHORITY); public static final String PATH_FAVOURITE = "favouritemovies"; private MovieContract(){} public static final class MovieEntry implements BaseColumns{ public static final Uri CONTENT_URI = BASE_CONTENT_URI.buildUpon().appendPath(PATH_FAVOURITE).build(); public static final String TABLE_NAME = "favouritemovies"; public static final String MOVIE_ID = "_id"; public static final String MOVIE_TITLE = "title"; public static final String MOVIE_RELEASE_DATE = "date"; public static final String MOVIE_OVERVIEW = "overview"; public static final String MOVIE_RATING = "rating"; public static final String MOVIE_POSTER_PATH = "posterpath"; } }
c9d8160fce9c57aead110790ced43b6b3ce761e3
401acd2c65254be8eafa84eaa065aff7c6943d72
/eclipse-workspace/aula2/src/aula2/Teste.java
cb3b7caedcaca9c9eedc42dd01be5d4b8b38b85d
[]
no_license
WeskleySantos/Java
d4c5e9466d024023e84ea51c7ee88cd272b85a01
844d2f5c6ea43e6ca560df0e0efd9b1a2b7da79b
refs/heads/master
2021-02-10T15:08:59.163748
2020-03-02T14:34:53
2020-03-02T14:34:53
244,392,544
0
0
null
null
null
null
UTF-8
Java
false
false
512
java
package aula2; public class Teste { public static void main(String[] args) { Arma metralhadora = new Arma(2,3); metralhadora.atirar(); metralhadora.atirar(); metralhadora.atirar(); metralhadora.atirar(); metralhadora.atirar(); metralhadora.atirar(); metralhadora.atirar(); metralhadora.atirar(); metralhadora.atirar(); metralhadora.recaregar(); metralhadora.recaregar(); metralhadora.recaregar(); metralhadora.recaregar(); metralhadora.recaregar(); } }
b6a48159f97dcd614c169404b188bdbda5aadf12
0fc43e89aaabdf94d77a58fc81cdb1af3dfe0c6f
/src/data/week10/Week10Level2Run.java
848201ee12da5ed339e8dc63c894876c2e9c1dae
[]
no_license
mrLWachs/programmingChallenges
211886e30d716d3dbe776e8b17851e58852b3f97
af20726446a8ee3641a483cbfcea4b52f20eec82
refs/heads/master
2023-09-01T13:15:46.850650
2023-08-25T18:07:36
2023-08-25T18:07:36
220,297,407
0
1
null
null
null
null
UTF-8
Java
false
false
4,485
java
package data.week10; import io.System; import java.util.ArrayList; import mainpackage.AutoRun; public class Week10Level2Run extends AutoRun { public void auto(int week, int level) { start(week, level); System.autoFlush(); } public void run(int week, int level) { start(week, level); System.flush(); } private void start(int week, int level) { System.out.header("Week " + week + ", Level " + level + ": starting"); String[] lines = { "4", "6", "24", "30420", "10078" }; System.out.println("Inputs:\n"); for (int i = 0; i < lines.length; i++) { System.out.println(lines[i]); } System.out.println("\nOutputs:\n"); int currentLine = 0; int dataSets = Integer.parseInt(lines[currentLine]); for (int dataSet = 0; dataSet < dataSets; dataSet++) { currentLine++; int number = Integer.parseInt(lines[currentLine]); checkForNasty(number); } System.out.header("Week " + week + ", Level " + level + ": complete"); } private void checkForNasty(int number) { ArrayList<Integer> factors = getFactors(number); if (checkNastySum(factors,number)) System.out.println(number + " is nasty"); else System.out.println(number + " is not nasty"); } private ArrayList<Integer> getFactors(int number) { ArrayList<Integer> factors = new ArrayList<>(); for (int value = 1; value <= number; value++) { if (isFactor(value,number)) factors.add(value); } return factors; } private boolean isFactor(int value, int number) { if (number % value == 0) return true; else return false; } private boolean checkNastySum(ArrayList<Integer> factors, int number) { boolean isNasty = false; ArrayList<FactorPairs> factorPairs = getFactorPairs(factors,number); for (int i = 0; i < factorPairs.size(); i++) { FactorPairs currentPair = factorPairs.get(i); isNasty = checkForNasty(currentPair,factorPairs,number); if (isNasty) return true; } return false; } private boolean checkForNasty(FactorPairs pair, ArrayList<FactorPairs> factorPairs, int number) { for (int i = 0; i < factorPairs.size(); i++) { FactorPairs newPair = factorPairs.get(i); if (!newPair.equals(pair)) { if (pair.minusValue == newPair.addValue) return true; } } return false; } private ArrayList<FactorPairs> getFactorPairs(ArrayList<Integer> factors, int number) { ArrayList<FactorPairs> factorPairs = new ArrayList<>(); for (int i = 0; i < factors.size(); i++) { int factor = factors.get(i); int match = findMatchingFactor(factor,factors,number); FactorPairs pair = new FactorPairs(factor, match); if (!factorPairs.contains(pair)) factorPairs.add(pair); } return factorPairs; } private int findMatchingFactor(int factor, ArrayList<Integer> factors, int number) { for (int i = 0; i < factors.size(); i++) { int value = factors.get(i); if (value != factor) { if (value * factor == number) return value; } } return 0; } private class FactorPairs { public int factor1; public int factor2; public int minusValue; public int addValue; public FactorPairs(int factor1, int factor2) { this.factor1 = factor1; this.factor2 = factor2; int highest = factor1; int lowest = factor2; if (factor2 > factor1) highest = factor2; if (factor1 < factor2) lowest = factor1; minusValue = highest - lowest; addValue = lowest + highest; } public boolean equals(Object object) { FactorPairs that = (FactorPairs)object; if (this.factor1 == that.factor1 && this.factor2 == that.factor2) { return true; } return false; } } }
a06f6c9c3a81365539330889b98af2b1e1a54be1
315347959b6275f413eb529c7d4aa49b656960fb
/kie-dmn/kie-dmn-core/src/test/java/org/kie/dmn/core/stronglytyped/JavadocTest.java
728f034894593046e3f561a4ee8f19a357d4c939
[ "Apache-2.0" ]
permissive
yangjava/drools
b12cf12f94de329a1d152be28426724bb3f728b8
1b34665ba4c84c5fe92c20e70b1fe52938822c6c
refs/heads/master
2022-04-29T07:01:18.856979
2022-04-26T08:03:29
2022-04-26T08:03:29
53,998,396
0
0
null
null
null
null
UTF-8
Java
false
false
9,297
java
/* * Copyright 2020 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kie.dmn.core.stronglytyped; import java.util.HashMap; import java.util.Map; import java.util.Optional; import com.github.javaparser.StaticJavaParser; import com.github.javaparser.ast.CompilationUnit; import com.github.javaparser.ast.body.FieldDeclaration; import com.github.javaparser.ast.comments.JavadocComment; import org.drools.util.StringUtils; import org.junit.Test; import org.junit.runners.Parameterized; import org.kie.dmn.api.core.DMNModel; import org.kie.dmn.api.core.DMNRuntime; import org.kie.dmn.core.BaseVariantTest; import org.kie.dmn.core.DMNRuntimeTest; import org.kie.dmn.core.util.DMNRuntimeUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertTrue; import static org.kie.dmn.core.BaseVariantTest.VariantTestConf.BUILDER_DEFAULT_NOCL_TYPECHECK_TYPESAFE; import static org.kie.dmn.core.BaseVariantTest.VariantTestConf.KIE_API_TYPECHECK_TYPESAFE; public class JavadocTest extends BaseVariantTest { public static final Logger LOG = LoggerFactory.getLogger(JavadocTest.class); public JavadocTest(VariantTestConf testConfig) { super(testConfig); } @Parameterized.Parameters(name = "{0}") public static Object[] params() { return new Object[]{BUILDER_DEFAULT_NOCL_TYPECHECK_TYPESAFE, KIE_API_TYPECHECK_TYPESAFE}; } @Test public void testDateAndTime() throws Exception { final DMNRuntime runtime = createRuntime("0007-date-time.dmn", DMNRuntimeTest.class); runtime.addListener(DMNRuntimeUtil.createListener()); final DMNModel dmnModel = runtime.getModel("http://www.trisotech.com/definitions/_69430b3e-17b8-430d-b760-c505bf6469f9", "dateTime Table 58"); assertThat(dmnModel).isNotNull(); assertThat(dmnModel.hasErrors()).as(DMNRuntimeUtil.formatMessages(dmnModel.getMessages())).isFalse(); // Typesafe only test Map<String, String> sourceMap = new HashMap<>(); allSources.forEach((k, v) -> sourceMap.put(k.substring(k.lastIndexOf(".") + 1), v)); String inputSet = sourceMap.get("InputSet"); CompilationUnit cu = StaticJavaParser.parse(inputSet); assertJavadoc(cu, "dateTimeString", "DMNType{ http://www.omg.org/spec/DMN/20180521/FEEL/ : string }"); assertJavadoc(cu, "Timezone", "DMNType{ http://www.omg.org/spec/DMN/20180521/FEEL/ : string }"); assertJavadoc(cu, "oneHour", "DMNType{ http://www.omg.org/spec/DMN/20180521/FEEL/ : days and time duration }"); assertJavadoc(cu, "Month", "DMNType{ http://www.omg.org/spec/DMN/20180521/FEEL/ : number }"); assertJavadoc(cu, "Year", "DMNType{ http://www.omg.org/spec/DMN/20180521/FEEL/ : number }"); assertJavadoc(cu, "Hours", "DMNType{ http://www.omg.org/spec/DMN/20180521/FEEL/ : number }"); assertJavadoc(cu, "timeString", "DMNType{ http://www.omg.org/spec/DMN/20180521/FEEL/ : string }"); assertJavadoc(cu, "dateString", "DMNType{ http://www.omg.org/spec/DMN/20180521/FEEL/ : string }"); assertJavadoc(cu, "Seconds", "DMNType{ http://www.omg.org/spec/DMN/20180521/FEEL/ : number }"); assertJavadoc(cu, "Day", "DMNType{ http://www.omg.org/spec/DMN/20180521/FEEL/ : number }"); assertJavadoc(cu, "Minutes", "DMNType{ http://www.omg.org/spec/DMN/20180521/FEEL/ : number }"); assertJavadoc(cu, "durationString", "DMNType{ http://www.omg.org/spec/DMN/20180521/FEEL/ : string }"); String outputSet = sourceMap.get("OutputSet"); cu = StaticJavaParser.parse(outputSet); assertJavadoc(cu, "Timezone", "DMNType{ http://www.omg.org/spec/DMN/20180521/FEEL/ : string }"); assertJavadoc(cu, "Date_45Time", "DMNType{ http://www.omg.org/spec/DMN/20180521/FEEL/ : date and time }"); assertJavadoc(cu, "Hours", "DMNType{ http://www.omg.org/spec/DMN/20180521/FEEL/ : number }"); assertJavadoc(cu, "Time", "DMNType{ http://www.omg.org/spec/DMN/20180521/FEEL/ : time }"); assertJavadoc(cu, "Minutes", "DMNType{ http://www.omg.org/spec/DMN/20180521/FEEL/ : number }"); assertJavadoc(cu, "Date_45Time2", "DMNType{ http://www.omg.org/spec/DMN/20180521/FEEL/ : date and time }"); assertJavadoc(cu, "years", "DMNType{ http://www.omg.org/spec/DMN/20180521/FEEL/ : number }"); assertJavadoc(cu, "dateTimeString", "DMNType{ http://www.omg.org/spec/DMN/20180521/FEEL/ : string }"); assertJavadoc(cu, "oneHour", "DMNType{ http://www.omg.org/spec/DMN/20180521/FEEL/ : days and time duration }"); assertJavadoc(cu, "d1seconds", "DMNType{ http://www.omg.org/spec/DMN/20180521/FEEL/ : number }"); assertJavadoc(cu, "Month", "DMNType{ http://www.omg.org/spec/DMN/20180521/FEEL/ : number }"); assertJavadoc(cu, "cDay", "DMNType{ http://www.omg.org/spec/DMN/20180521/FEEL/ : number }"); assertJavadoc(cu, "sumDurations", "DMNType{ http://www.omg.org/spec/DMN/20180521/FEEL/ : days and time duration }"); assertJavadoc(cu, "cYear", "DMNType{ http://www.omg.org/spec/DMN/20180521/FEEL/ : number }"); assertJavadoc(cu, "cSecond", "DMNType{ http://www.omg.org/spec/DMN/20180521/FEEL/ : number }"); assertJavadoc(cu, "dateString", "DMNType{ http://www.omg.org/spec/DMN/20180521/FEEL/ : string }"); assertJavadoc(cu, "cTimezone", "DMNType{ http://www.omg.org/spec/DMN/20180521/FEEL/ : string }"); assertJavadoc(cu, "durationString", "DMNType{ http://www.omg.org/spec/DMN/20180521/FEEL/ : string }"); assertJavadoc(cu, "cHour", "DMNType{ http://www.omg.org/spec/DMN/20180521/FEEL/ : number }"); assertJavadoc(cu, "Year", "DMNType{ http://www.omg.org/spec/DMN/20180521/FEEL/ : number }"); assertJavadoc(cu, "Time2", "DMNType{ http://www.omg.org/spec/DMN/20180521/FEEL/ : time }"); assertJavadoc(cu, "timeString", "DMNType{ http://www.omg.org/spec/DMN/20180521/FEEL/ : string }"); assertJavadoc(cu, "Time3", "DMNType{ http://www.omg.org/spec/DMN/20180521/FEEL/ : time }"); assertJavadoc(cu, "hoursInDuration", "DMNType{ http://www.omg.org/spec/DMN/20180521/FEEL/ : number }"); assertJavadoc(cu, "dtDuration1", "DMNType{ http://www.omg.org/spec/DMN/20180521/FEEL/ : days and time duration }"); assertJavadoc(cu, "Seconds", "DMNType{ http://www.omg.org/spec/DMN/20180521/FEEL/ : number }"); assertJavadoc(cu, "dtDuration2", "DMNType{ http://www.omg.org/spec/DMN/20180521/FEEL/ : days and time duration }"); assertJavadoc(cu, "Day", "DMNType{ http://www.omg.org/spec/DMN/20180521/FEEL/ : number }"); assertJavadoc(cu, "cMonth", "DMNType{ http://www.omg.org/spec/DMN/20180521/FEEL/ : number }"); assertJavadoc(cu, "cMinute", "DMNType{ http://www.omg.org/spec/DMN/20180521/FEEL/ : number }"); assertJavadoc(cu, "ymDuration2", "DMNType{ http://www.omg.org/spec/DMN/20180521/FEEL/ : days and time duration }"); String tDateVariants = sourceMap.get("TDateVariants"); cu = StaticJavaParser.parse(tDateVariants); assertJavadoc(cu, "fromString", "DMNType{ http://www.omg.org/spec/DMN/20180521/FEEL/ : date }"); assertJavadoc(cu, "fromDateTime", "DMNType{ http://www.omg.org/spec/DMN/20180521/FEEL/ : date }"); assertJavadoc(cu, "fromYearMonthDay", "DMNType{ http://www.omg.org/spec/DMN/20180521/FEEL/ : date }"); String tDateTimeComponents = sourceMap.get("TDateTimeComponents"); cu = StaticJavaParser.parse(tDateTimeComponents); assertJavadoc(cu, "Year", "DMNType{ http://www.omg.org/spec/DMN/20180521/FEEL/ : number }"); assertJavadoc(cu, "Month", "DMNType{ http://www.omg.org/spec/DMN/20180521/FEEL/ : number }"); assertJavadoc(cu, "Day", "DMNType{ http://www.omg.org/spec/DMN/20180521/FEEL/ : number }"); assertJavadoc(cu, "Hour", "DMNType{ http://www.omg.org/spec/DMN/20180521/FEEL/ : number }"); assertJavadoc(cu, "Minute", "DMNType{ http://www.omg.org/spec/DMN/20180521/FEEL/ : number }"); assertJavadoc(cu, "Second", "DMNType{ http://www.omg.org/spec/DMN/20180521/FEEL/ : number }"); } private void assertJavadoc(CompilationUnit cu, String field, String expectedJavadocComment) { String lcField = StringUtils.lcFirst(field); Optional<FieldDeclaration> opt = cu.findFirst(FieldDeclaration.class, fd -> fd.asFieldDeclaration().getVariable(0).getNameAsString().equals(lcField)); assertTrue(opt.isPresent()); Optional<JavadocComment> actual = opt.get().getJavadocComment(); assertTrue(actual.isPresent()); assertThat(actual.get().getContent()).contains(expectedJavadocComment); } }
6b80e9e5e35db9b3ae5b565ebc100131d39b6f4e
0b95a85deaf1c9fade3e2a5af2e816a5b00607a4
/tempcode/src/main/java/com/temp/code/thread/pooldesign/demo/Worker.java
ec185f9d68efee8fac7afaa1c639c8c38093cd81
[]
no_license
liwen666/lw_code
6009fb1a83ad74c987a5e58937c3a178537094b0
6fb3f4373fdf1363938ee4f30b39c9fd17c8a8d7
refs/heads/master
2020-04-09T22:58:38.355751
2019-04-25T07:37:52
2019-04-25T07:37:52
160,643,842
0
0
null
null
null
null
UTF-8
Java
false
false
1,885
java
package com.temp.code.thread.pooldesign.demo; import javafx.beans.property.ReadOnlyBooleanProperty; import javafx.beans.property.ReadOnlyDoubleProperty; import javafx.beans.property.ReadOnlyObjectProperty; import javafx.beans.property.ReadOnlyStringProperty; /** * <p>describe</p> * <p>Worker.java</p> * <p></p> * @author lw * @date 2017年1月13日 * @version 1.0 * @link */ public class Worker extends Thread{ /** * 对象的关联 一对多的关系 每个worker 都分装了同一个pool这样可以拿pool对worker进行操作 */ private ThreadPoolTEST pool; private Runnable target; private boolean isShutDown=false; private boolean isIdle=false; public Worker(Runnable target, String string, ThreadPoolTEST threadPoolTEST) { super(string); this.pool=threadPoolTEST; this.target=target; } public ThreadPoolTEST getPool() { return pool; } public void setPool(ThreadPoolTEST pool) { this.pool = pool; } public boolean isShutDown() { return isShutDown; } public void setShutDown(boolean isShutDown) { this.isShutDown = isShutDown; } public boolean isIdle() { return isIdle; } public void setIdle(boolean isIdle) { this.isIdle = isIdle; } public Runnable getTarget() { return target; } @Override public void run() { /** * 为线程池工作的线程不是关闭状态就会执行任务 target */ while (!isShutDown){ isIdle=false; if(target!=null){ target.run(); } /** * 任务结束了 标记为空闲状态 */ isIdle=true; try{ /** * 将空闲线程回收 */ pool.repool(this); synchronized (this) { wait(); } }catch(InterruptedException e){ } isIdle=false; } } public void shutDown() { isShutDown=true; notifyAll(); } public void setTarget(Runnable newtarget) { target= newtarget; notifyAll(); } }
cd29234e3590db15f0f0b4c64b4b0ed5734b905d
12a001b6723a6e4f1e840cca696218a368919c0b
/src/main/java/com/StaticPH/SongJ/cli/ArgManager.java
2097411bf522baed887387d19a9d1f0e9e285964
[ "MIT" ]
permissive
StaticPH/SongJ
7550aad1827bd2ab05b6d05861602b0443dd5ca8
587d367bb4335a4ad9c0cb7a5fd5a95b7993b749
refs/heads/master
2021-12-14T19:50:39.179510
2021-12-10T15:41:52
2021-12-10T15:41:52
230,526,661
0
0
MIT
2021-12-10T15:41:53
2019-12-27T22:25:21
Java
UTF-8
Java
false
false
2,858
java
package com.StaticPH.SongJ.cli; import com.StaticPH.SongJ.Constants.Colors; import com.StaticPH.SongJ.StringUtils; import com.beust.jcommander.JCommander; import java.io.File; import java.util.List; import java.util.Vector; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.LogManager; @SuppressWarnings({"UnnecessaryReturnStatement", "RedundantSuppression", "unused"}) public class ArgManager { private static Logger loggo = LogManager.getLogger("ArgManager"); private CLIArguments arguments; private JCommander jCommander; private List<String> unknownOptions; private String programDesc = null; public CLIArguments getArguments() { return this.arguments;} public JCommander getJCommander() { return this.jCommander;} public ArgManager(String[] args) { this.arguments = new CLIArguments(); this.initArgs(args); } private void initArgs(final String[] args) { // ???: Is there really any reason for this, if initArgs is only ever called after instantiating ArgManager.arguments? this.arguments = new CLIArguments(); this.jCommander = new JCommander(this.arguments, null, args); this.unknownOptions = this.jCommander.getUnknownOptions(); } public void setProgramDesc(String programDesc) { this.programDesc = programDesc; } /** * Execute base behavior for ArgManager. * * @return {@code false} if this function results in a call to {@code JCommander.usage()}, otherwise {@code true} */ private boolean baseBehavior() { Vector<File> files = this.arguments.getAudioFiles(); int fileCount = 0; if (files != null) { files.removeIf(f -> f.getName().toLowerCase().endsWith(".properties")); fileCount = files.size(); } // Directory traversal and file list cleanup is handled during the first call to arguments.getAudioFiles(); /* If no files were given, display the program help and ignore further arguments.*/ if (fileCount == 0) { System.out.println(Colors.FG.RED + "ERROR: No playable files were discovered." + Colors.DEFAULT); this.jCommander.usage(); return false; } else if (this.unknownOptions.size() != 0) { System.out.println( Colors.FG.RED + "ERROR: Unknown option(s) found: " + StringUtils.delimitStrings(", ", this.unknownOptions.toString()) + Colors.DEFAULT ); // this.jCommander.usage(); // return false; } return true; } @SuppressWarnings("WeakerAccess") protected void configureJCommander() { this.jCommander.setExpandAtSign(false); this.jCommander.setAcceptUnknownOptions(false); this.jCommander.setUsageFormatter( new CustomUsageFormatter(this.jCommander, this.programDesc, CLIArguments.realAudioFilesParamDescription) ); } // Only ever run this AFTER instantiating ArgManager!! public boolean init() { new Colors(this.arguments.useColor()); this.configureJCommander(); return this.baseBehavior(); } }
c2e47a12be53417a2d9eed141fbd073f7acc83dd
7360bcbf840bc1284de56e12b757df9ad077b992
/base_library/src/main/java/com/ljh/custom/base_library/receiver/LibProvider.java
246b898b3e5b39885ea7aa673f4106d875728085
[]
no_license
lijunhuayc/ExamSDK
b26d32655215ef11e137013a57dcbe8917dae1bb
91320efa4e2e965a04ed2f2b807b08bb66f40908
refs/heads/master
2020-09-11T23:59:39.001180
2019-11-17T14:03:32
2019-11-17T14:03:32
222,233,504
0
0
null
null
null
null
UTF-8
Java
false
false
1,434
java
package com.ljh.custom.base_library.receiver; import android.content.ContentProvider; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.support.annotation.NonNull; import android.support.annotation.Nullable; /** * Desc: * Created by Junhua.Li * Date: 2019/11/17 14:13 */ public class LibProvider extends ContentProvider { private static Context sContext = null; @Nullable public static Context getLibContext() { return sContext; } @Override public boolean onCreate() { sContext = getContext(); return false; } @Nullable @Override public Cursor query(@NonNull Uri uri, @Nullable String[] projection, @Nullable String selection, @Nullable String[] selectionArgs, @Nullable String sortOrder) { return null; } @Nullable @Override public String getType(@NonNull Uri uri) { return null; } @Nullable @Override public Uri insert(@NonNull Uri uri, @Nullable ContentValues values) { return null; } @Override public int delete(@NonNull Uri uri, @Nullable String selection, @Nullable String[] selectionArgs) { return 0; } @Override public int update(@NonNull Uri uri, @Nullable ContentValues values, @Nullable String selection, @Nullable String[] selectionArgs) { return 0; } }
f8a1ef60c8be9412f30df213f6d236e7bf8fdc1b
55b09434be16c7cbefdf12236a9ee77ad63bcc2d
/Proyecto/CrudFirebaseJAVA/app/src/test/java/com/example/crudfirebasejava/ExampleUnitTest.java
321b17bf838e7877dc668b8355f49c6a0c68e523
[]
no_license
alcarazolabs/android_crud-firebase-java
4d350791445d6c5a10514ab53c918b5af7ba40f7
08e705ad13fccd21eb0873901dc5976dc0501581
refs/heads/main
2023-01-19T11:16:51.648852
2020-11-07T22:56:23
2020-11-07T22:56:23
309,800,717
1
1
null
null
null
null
UTF-8
Java
false
false
389
java
package com.example.crudfirebasejava; import org.junit.Test; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() { assertEquals(4, 2 + 2); } }
7cae1cc55525ace1cba37d94aeb5ceb174faa972
afc6d1c3ffc4af1d257b46e0a3857feb40c4f068
/src/main/java/Detection/AssignmentOptimal.java
d862219f4f51f1f455ece2dd3ca9d714f01e4485
[]
no_license
Apparum/Projet-Info-HogwarTse
f62d94afde836227332901115be4ba643776b91f
16287239dd295d2faddd6ebd97588dc0f5602e81
refs/heads/master
2021-04-28T10:47:45.932825
2018-03-11T20:54:21
2018-03-11T20:54:21
122,075,396
0
0
null
null
null
null
UTF-8
Java
false
false
583
java
package Detection; import java.util.Vector; public class AssignmentOptimal { public double Solve(double[][] DistMatrix, Vector<Integer> Assignment) { int N = DistMatrix.length; // number of columns (tracks) int M = DistMatrix[0].length; // number of rows (measurements) int dim = Math.max(N, M); // Init int[] match = new int[dim]; HungarianAlg3 b = new HungarianAlg3(DistMatrix); match = b.execute(); // form result Assignment.clear(); for (int x = 0; x < N; x++) { Assignment.add(match[x]); } return b.computeCost(DistMatrix, match); } }
dcb71cbbbb405a70993c320a534bc5555880b07c
ac8ff39884195bf9107653442dee659d36829f4b
/irontest-core-server/src/main/java/io/irontest/core/assertion/JSONPathXMLEqualAssertionVerifier.java
11c99681cf0760bccca74dc466b6761cf6687e9f
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
Nicky82/irontest
dac0b4252c3f633b70525270c407e0d0da0a96bd
d7cc1a5f25d1c189f9b1a05e9dafda8246a98c56
refs/heads/master
2022-09-16T08:16:17.063356
2020-06-01T12:19:02
2020-06-01T12:19:02
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,728
java
package io.irontest.core.assertion; import com.fasterxml.jackson.databind.ObjectMapper; import com.jayway.jsonpath.JsonPath; import io.irontest.models.TestResult; import io.irontest.models.assertion.Assertion; import io.irontest.models.assertion.AssertionVerificationResult; import io.irontest.models.assertion.JSONPathXMLEqualAssertionProperties; import io.irontest.models.assertion.JSONPathXMLEqualAssertionVerificationResult; import io.irontest.utils.XMLUtils; import org.apache.commons.lang3.StringUtils; public class JSONPathXMLEqualAssertionVerifier extends AssertionVerifier { /** * * @param assertion * @param inputs contains only one argument: the JSON string that the assertion is verified against * @return * @throws Exception */ @Override public AssertionVerificationResult _verify(Assertion assertion, Object ...inputs) throws Exception { JSONPathXMLEqualAssertionProperties otherProperties = (JSONPathXMLEqualAssertionProperties) assertion.getOtherProperties(); // validate other properties if ("".equals(StringUtils.trimToEmpty(otherProperties.getJsonPath()))) { throw new IllegalArgumentException("JSONPath not specified"); } else if ("".equals(StringUtils.trimToEmpty(otherProperties.getExpectedXML()))) { throw new IllegalArgumentException("Expected XML not specified"); } else { try { XMLUtils.xmlStringToDOM(otherProperties.getExpectedXML()); } catch (Exception e) { throw new IllegalArgumentException("Expected XML is not a valid XML. ", e); } } Object actualValue = JsonPath.read((String) inputs[0], otherProperties.getJsonPath()); if (!(actualValue instanceof String)) { ObjectMapper objectMapper = new ObjectMapper(); throw new Exception("JSONPath does not evaluate to a string. It evaluates to:\n " + objectMapper.writeValueAsString(actualValue)); } else { try { XMLUtils.xmlStringToDOM((String) actualValue); } catch (Exception e) { throw new Exception("JSONPath does not evaluate to an XML. It evaluates to a normal string:\n " + actualValue); } } JSONPathXMLEqualAssertionVerificationResult result = new JSONPathXMLEqualAssertionVerificationResult(); String actualXML = (String) actualValue; result.setActualXML(actualXML); String differencesStr = XMLUtils.compareXML(otherProperties.getExpectedXML(), actualXML); result.setResult(differencesStr.length() > 0 ? TestResult.FAILED : TestResult.PASSED); return result; } }
736d34485fc34e59db74842a93cc7b77f6809292
e297e599702b92293c275fb2b5e2b30870671507
/app/src/main/java/com/example/menudigital/RecyclerViewAdapter.java
12d50e471e8416ba9c83823590ece59e2cdfb13d
[]
no_license
OscarNoe/DeliveryMovil
4eec1edfe758cb1fac7124c6d8d88c3c1666e8f6
1e3a884ce3c4d00b94cb65c5b12e07312e4bf22f
refs/heads/master
2022-02-02T00:36:50.428176
2019-07-16T05:31:04
2019-07-16T05:31:04
197,116,975
0
0
null
null
null
null
UTF-8
Java
false
false
6,632
java
package com.example.menudigital; import android.content.ContentValues; import android.database.sqlite.SQLiteDatabase; import android.support.v4.app.DialogFragment; import android.content.Context; import android.graphics.Bitmap; import android.media.Image; import android.os.Handler; import android.support.annotation.NonNull; import android.support.v4.app.FragmentManager; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.ImageRequest; import com.android.volley.toolbox.Volley; import com.example.menudigital.entidades.ConexionSQLiteHelper; import java.io.ByteArrayOutputStream; import java.util.List; import static java.lang.String.valueOf; public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyViewHolder> { private List<Product> listaProducto; RequestQueue request; Context context; Bitmap bmap=null; Boolean posible=true; int p=0; public RecyclerViewAdapter( List<Product> mData, Context context) { this.listaProducto = mData; this.context = context; request= Volley.newRequestQueue(context); } @NonNull @Override public MyViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) { View view= LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.cardview_item_product, null, false); return new MyViewHolder(view); } CartProduct cartProduct=null; @Override public void onBindViewHolder(@NonNull MyViewHolder myViewHolder, final int i) { myViewHolder.tv_product_desc.setText(listaProducto.get(i).getDescripcion()); myViewHolder.tv_product_nombre.setText(listaProducto.get(i).getNombre()); myViewHolder.tv_product_precio.setText(valueOf(listaProducto.get(i).getPrecio())); final dialogProduct frag; frag = dialogProduct.newInstance("Titulo jaja"); cartProduct = new CartProduct(); cartProduct.setIdProduct(listaProducto.get(i).getId()); //Toast.makeText(context, "ID ES "+cartProduct.getIdProduct(), Toast.LENGTH_SHORT).show(); cartProduct.setNombre(listaProducto.get(i).getNombre()); cartProduct.setDescripcion(listaProducto.get(i).getDescripcion()); cartProduct.setPrecio(listaProducto.get(i).getPrecio()); final ContentValues values = new ContentValues(); values.put("id", String.valueOf(cartProduct.getIdProduct())); values.put("titulo", cartProduct.getNombre()); values.put("descripcion", cartProduct.getDescripcion()); values.put("precio", String.valueOf(cartProduct.getPrecio())); frag.setId(listaProducto.get(i).getId()); if(listaProducto.get(i).getRuta_imagen()!=null) { //myViewHolder.img_product_thumbnail.setImageBitmap(listaProducto.get(i).getImagen()); cargarImagen(listaProducto.get(i).getRuta_imagen() , myViewHolder, frag, values); }else{ myViewHolder.img_product_thumbnail.setImageResource(R.drawable.producto1); } myViewHolder.btnCart.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ConexionSQLiteHelper conn = new ConexionSQLiteHelper(context, "bd_pedidos",null,1); SQLiteDatabase db= conn.getWritableDatabase(); Toast.makeText(context, "Se agregó el producto a su carrito.", Toast.LENGTH_SHORT).show(); Long idResultado = db.insert("pedidos", "idOrden", values); //Toast.makeText(context, "IdRegistro= "+ idResultado, Toast.LENGTH_SHORT).show(); } }); //bmap= null; myViewHolder.linearLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //Cuando se da click en un LinearLayout del CardView if(frag != null && frag.isAdded() ) { return; }else{ frag.show(((PrincipalActivity)context).getSupportFragmentManager(),"Title" ); posible=false; } } }); } private void cargarImagen(String ruta_imagen, final MyViewHolder myViewHolder, final dialogProduct frag, final ContentValues values) { String urlimg = "http://"+context.getResources().getString(R.string.ip)+"/bdSistemaPOS/"+ruta_imagen; urlimg = urlimg.replace(" ", "%20"); ImageRequest imageRequest = new ImageRequest(urlimg, new Response.Listener<Bitmap>() { @Override public void onResponse(Bitmap response) { ByteArrayOutputStream baos = new ByteArrayOutputStream(20480); myViewHolder.img_product_thumbnail.setImageBitmap(response); response.compress(Bitmap.CompressFormat.PNG, 0 , baos); frag.setImG(response); byte[] blob = baos.toByteArray(); values.put("imagen", blob); } }, 0, 0, ImageView.ScaleType.CENTER, null, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Toast.makeText(context, "Error al conectarse"+error, Toast.LENGTH_LONG).show(); } }); request.add(imageRequest); } @Override public int getItemCount() { return listaProducto.size(); } public static class MyViewHolder extends RecyclerView.ViewHolder{ TextView tv_product_nombre, tv_product_precio, tv_product_desc; ImageView img_product_thumbnail; Button btnCart; LinearLayout linearLayout; public MyViewHolder(@NonNull View itemView) { super(itemView); btnCart=itemView.findViewById(R.id.btnCart); linearLayout =itemView.findViewById(R.id.linearLayout); tv_product_desc = itemView.findViewById(R.id.tvDesc); tv_product_nombre = itemView.findViewById(R.id.tvNombre); tv_product_precio = itemView.findViewById(R.id.tvPrecio); img_product_thumbnail = itemView.findViewById(R.id.ivCardview); } } }
0527dd04e2f8c8eb3e0cec83350682ba25bb0434
bdc2dad0bd3246338299e0ef8e1df3c08bd374c4
/app/src/main/java/ertzil/com/huella/FingerprintActivity.java
e68d6e25a60034f8be97d0d544890d6f81d6394e
[]
no_license
lubaspc/House
9b7ec712c0a13583ceedb9327dadb8faede18109
9cdcb47dc2a9e90294ee3e96b65de10ed9a789db
refs/heads/master
2020-08-30T10:44:41.201584
2019-11-07T02:54:49
2019-11-07T02:54:49
218,355,256
0
0
null
null
null
null
UTF-8
Java
false
false
6,119
java
package ertzil.com.huella; import android.Manifest; import android.annotation.TargetApi; import android.app.KeyguardManager; import android.content.pm.PackageManager; import android.hardware.fingerprint.FingerprintManager; import android.os.Build; import android.security.keystore.KeyGenParameterSpec; import android.security.keystore.KeyPermanentlyInvalidatedException; import android.security.keystore.KeyProperties; import android.support.v4.app.ActivityCompat; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.TextView; import java.io.IOException; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.UnrecoverableKeyException; import java.security.cert.CertificateException; import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.NoSuchPaddingException; import javax.crypto.SecretKey; public class FingerprintActivity extends AppCompatActivity { private KeyStore keyStore; // Variable used for storing the key in the Android Keystore container private static final String KEY_NAME = "pruebaHuella"; private Cipher cipher; private TextView textView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_fingerprint); // Initializing both Android Keyguard Manager and Fingerprint Manager KeyguardManager keyguardManager = (KeyguardManager) getSystemService(KEYGUARD_SERVICE); FingerprintManager fingerprintManager = (FingerprintManager) getSystemService(FINGERPRINT_SERVICE); textView = (TextView) findViewById(R.id.errorText); // Check whether the device has a Fingerprint sensor. if(!fingerprintManager.isHardwareDetected()){ /** * An error message will be displayed if the device does not contain the fingerprint hardware. * However if you plan to implement a default authentication method, * you can redirect the user to a default authentication activity from here. * Example: * Intent intent = new Intent(this, DefaultAuthenticationActivity.class); * startActivity(intent); */ textView.setText("Your Device does not have a Fingerprint Sensor"); }else { // Checks whether fingerprint permission is set on manifest if (ActivityCompat.checkSelfPermission(this, Manifest.permission.USE_FINGERPRINT) != PackageManager.PERMISSION_GRANTED) { textView.setText("Fingerprint authentication permission not enabled"); }else{ // Check whether at least one fingerprint is registered if (!fingerprintManager.hasEnrolledFingerprints()) { textView.setText("Register at least one fingerprint in Settings"); }else{ // Checks whether lock screen security is enabled or not if (!keyguardManager.isKeyguardSecure()) { textView.setText("Lock screen security not enabled in Settings"); }else{ generateKey(); if (cipherInit()) { FingerprintManager.CryptoObject cryptoObject = new FingerprintManager.CryptoObject(cipher); FingerprintHandler helper = new FingerprintHandler(this); helper.startAuth(fingerprintManager, cryptoObject); } } } } } } @TargetApi(Build.VERSION_CODES.M) protected void generateKey() { try { keyStore = KeyStore.getInstance("AndroidKeyStore"); } catch (Exception e) { e.printStackTrace(); } KeyGenerator keyGenerator; try { keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore"); } catch (NoSuchAlgorithmException | NoSuchProviderException e) { throw new RuntimeException("Failed to get KeyGenerator instance", e); } try { keyStore.load(null); keyGenerator.init(new KeyGenParameterSpec.Builder(KEY_NAME, KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT) .setBlockModes(KeyProperties.BLOCK_MODE_CBC) .setUserAuthenticationRequired(true) .setEncryptionPaddings( KeyProperties.ENCRYPTION_PADDING_PKCS7) .build()); keyGenerator.generateKey(); } catch (NoSuchAlgorithmException | InvalidAlgorithmParameterException | CertificateException | IOException e) { throw new RuntimeException(e); } } @TargetApi(Build.VERSION_CODES.M) public boolean cipherInit() { try { cipher = Cipher.getInstance(KeyProperties.KEY_ALGORITHM_AES + "/" + KeyProperties.BLOCK_MODE_CBC + "/" + KeyProperties.ENCRYPTION_PADDING_PKCS7); } catch (NoSuchAlgorithmException | NoSuchPaddingException e) { throw new RuntimeException("Failed to get Cipher", e); } try { keyStore.load(null); SecretKey key = (SecretKey) keyStore.getKey(KEY_NAME, null); cipher.init(Cipher.ENCRYPT_MODE, key); return true; } catch (KeyPermanentlyInvalidatedException e) { return false; } catch (KeyStoreException | CertificateException | UnrecoverableKeyException | IOException | NoSuchAlgorithmException | InvalidKeyException e) { throw new RuntimeException("Failed to init Cipher", e); } } }
062b7a340ed9ae35049d2e7570861cb41968baa2
5b2563b913959dc06719e338b1c20afda22a95f9
/mobile/src/main/java/model/DatabaseToJSON.java
a6dacfb364ee7e3662ba0233521c58c85ae3cd03
[]
no_license
upadhyay213213/Communicator
1a471169b66f85269ff815a61f7a4e05980b87e8
0a6d954bc0a17ebf64ead6fd65b4ca0609a8540e
refs/heads/master
2021-05-03T06:56:00.160783
2016-12-07T19:44:18
2016-12-07T19:44:18
68,847,892
0
0
null
2016-12-07T19:44:18
2016-09-21T18:50:39
Java
UTF-8
Java
false
false
1,152
java
package model; import android.content.ClipData; import android.content.Context; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import databasequery.DataBaseQuery; import databasequery.DatabaseHelper; /** * Created by nupadhay on 9/20/2016. */ public class DatabaseToJSON { public DatabaseToJSON(Context context) { DatabaseHelper.init(context); } public JSONObject getJSON() throws JSONException { ArrayList<MessageResposneDatabase> item = null; JSONObject pl = new JSONObject(); item = DataBaseQuery.getMessageResponse(); JSONArray jsonArray = new JSONArray(); for(int i=0;i<item.size();i++){ JSONObject val = new JSONObject(); try { val.put("id", item.get(i).getmID()); val.put("name", item.get(i).getmSenderID()); jsonArray.put(val); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } pl.put("data",jsonArray); return pl; } }
d42d779759d55083344e7631376b25dbf948a375
f77d2b687a0e22365c8ce119449c4619377f2b71
/app/src/main/java/com/wlb/framework/learning/ui/learning/allList/AllTrendingList.java
22ea7601f577f2c529791135e0d96cd1385a7251
[ "Apache-2.0" ]
permissive
khaerulumam11/wlblearning
80849906077cfa48651ab25b32bb787e6f326ba6
bff132688570a03e4ca7d72c210299e25b9ce13d
refs/heads/master
2020-05-16T08:00:33.124677
2019-04-23T01:21:34
2019-04-23T01:21:34
182,894,828
0
0
null
null
null
null
UTF-8
Java
false
false
6,185
java
package com.wlb.framework.learning.ui.learning.allList; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.view.View; import android.widget.Toast; import com.androidnetworking.error.ANError; import com.wlb.framework.learning.BR; import com.wlb.framework.learning.R; import com.wlb.framework.learning.ViewModelProviderFactory; import com.wlb.framework.learning.databinding.ActivityAllTrendingListBinding; import com.wlb.framework.learning.databinding.ItemBlogEmptyViewBinding; import com.wlb.framework.learning.ui.base.BaseActivity; import com.wlb.framework.learning.ui.learning.allList.adapter.AllTrendingListAdapter; import com.wlb.framework.learning.ui.learning.allList.model.CourseModelTrending; import com.wlb.framework.learning.ui.learning.allList.navigator.AllTrendingNavigator; import com.wlb.framework.learning.ui.learning.allList.util.DemoConfiguration; import com.wlb.framework.learning.ui.learning.allList.viewModel.AllTrendingListViewModel; import java.util.ArrayList; import java.util.List; import javax.inject.Inject; import androidx.appcompat.widget.Toolbar; import androidx.lifecycle.ViewModelProviders; import androidx.recyclerview.widget.DefaultItemAnimator; import androidx.recyclerview.widget.GridLayoutManager; import androidx.recyclerview.widget.RecyclerView; import androidx.swiperefreshlayout.widget.SwipeRefreshLayout; public class AllTrendingList extends BaseActivity<ActivityAllTrendingListBinding, AllTrendingListViewModel> implements AllTrendingNavigator, AllTrendingListAdapter.AllTrendingListListener { private static final String TAG = "AllTrendingList"; @Inject ViewModelProviderFactory factory; AllTrendingListAdapter allTrendingListAdapter; ActivityAllTrendingListBinding mActivityAllTrendingBinding; private Toolbar mToolbar; private AllTrendingListViewModel allTrendingListViewModel; RecyclerView.LayoutManager layoutManager; ArrayList<CourseModelTrending.Data> courses = new ArrayList<CourseModelTrending.Data>(); public static Intent newIntent(Context context) { Intent intent = new Intent(context, AllTrendingList.class); return intent; } @Override public int getBindingVariable() { return BR.model; } @Override public int getLayoutId() { return R.layout.activity_all_trending_list; } @Override public AllTrendingListViewModel getViewModel() { allTrendingListViewModel = ViewModelProviders.of(this, factory).get(AllTrendingListViewModel.class); return allTrendingListViewModel; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mActivityAllTrendingBinding = getViewDataBinding(); allTrendingListViewModel.setNavigator(this); // allTrendingListAdapter.setListener(this); setUp(); // } private void setUp() { mToolbar = mActivityAllTrendingBinding.toolbar; setSupportActionBar(mToolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); mToolbar.setTitle("All Trending Learning"); mActivityAllTrendingBinding.rvLis.setLayoutManager(new GridLayoutManager(this,2)); mActivityAllTrendingBinding.rvLis.setItemAnimator(new DefaultItemAnimator()); allTrendingListAdapter = new AllTrendingListAdapter(courses,this); mActivityAllTrendingBinding.rvLis.setAdapter(allTrendingListAdapter); // mActivityAllTrendingBinding.rvLis.showShimmerAdapter(); // mActivityAllTrendingBinding.shimmerLayout.startShimmerAnimation(); // mActivityAllTrendingBinding.shimmerLayout.setVisibility(View.GONE); // mActivityAllTrendingBinding.rvList.postDelayed(new Runnable() { // @Override // public void run() { // mActivityAllTrendingBinding.rvList.showShimmerAdapter(); // } // },3000); updateRecommendationCourse(); mActivityAllTrendingBinding.swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { new Handler().postDelayed(new Runnable() { @Override public void run() { courses.clear(); // Berhenti berputar/refreshing mActivityAllTrendingBinding.swipeRefreshLayout.setRefreshing(false); // fungsi-fungsi lain yang dijalankan saat refresh berhenti allTrendingListViewModel.fetchBlogs(); allTrendingListAdapter.notifyDataSetChanged(); } }, 5000); } }); } // @Override // public void onRetryClick() { // allTrendingListViewModel.fetchBlogs(); // } @Override public void handleError(Throwable throwable) { } private void updateRecommendationCourse(){ if (isNetworkConnected()){ allTrendingListViewModel.fetchBlogs(); allTrendingListAdapter.notifyDataSetChanged(); // mActivityAllTrendingBinding.shimmerLayout.stopShimmerAnimation(); // mActivityAllTrendingBinding.shimmerLayout.setVisibility(View.GONE); }else{ } } @Override public void updateUI(CourseModelTrending courseModelTrending) { CourseModelTrending.Data academyCourseCategory; // for (int i = 0; i < courseModelTrending.getData().size(); i++){ academyCourseCategory = courseModelTrending.getData().get(i); courses.add(academyCourseCategory); } allTrendingListAdapter.notifyDataSetChanged(); } @Override public void handleErrorNetwork(ANError error) { } // @Override // public void onResume() { // super.onResume(); // mActivityAllTrendingBinding.shimmerLayout.startShimmerAnimation(); // } // // @Override // protected void onPause() { // mActivityAllTrendingBinding.shimmerLayout.stopShimmerAnimation(); // super.onPause(); // } }
b6e76c89f98693ec29a7aa66a2c4c4f5b7907221
ddace72fcb5996d589541bf9ee1b4e6afab57751
/TeamCode/src/main/java/org/firstinspires/ftc/teamcode/intro.java
08e1f01ff72c78e4b6c4a69348031b759fdaea2a
[ "BSD-3-Clause" ]
permissive
bkcrusadersrobotics/bkCrusaders2019-2020
7516036ba1e22a9338de1124276a6559c700768f
0e7c275906838189c44e832d62c7b93f63c1499b
refs/heads/master
2020-07-27T15:35:46.541411
2019-09-24T19:34:09
2019-09-24T19:34:09
209,142,869
0
0
null
null
null
null
UTF-8
Java
false
false
5,287
java
/* Copyright (c) 2017 FIRST. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted (subject to the limitations in the disclaimer below) provided that * the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * Neither the name of FIRST nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY THIS * LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.firstinspires.ftc.teamcode; import com.qualcomm.robotcore.eventloop.opmode.Autonomous; import com.qualcomm.robotcore.eventloop.opmode.Disabled; import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode; import com.qualcomm.robotcore.util.ElapsedTime; import org.firstinspires.ftc.robotcontroller.external.samples.HardwarePushbot; /** * This file illustrates the concept of driving a path based on time. * It uses the common Pushbot hardware class to define the drive on the robot. * The code is structured as a LinearOpMode * * The code assumes that you do NOT have encoders on the wheels, * otherwise you would use: PushbotAutoDriveByEncoder; * * The desired path in this example is: * - Drive forward for 3 seconds * - Spin right for 1.3 seconds * - Drive Backwards for 1 Second * - Stop and close the claw. * * The code is written in a simple form with no optimizations. * However, there are several ways that this type of sequence could be streamlined, * * Use Android Studios to Copy this Class, and Paste it into your team's code folder with a new name. * Remove or comment out the @Disabled line to add this opmode to the Driver Station OpMode list */ // this is a test comment hello world @Autonomous(name="Pushbot: Auto Drive By Time", group="Pushbot") @Disabled public class intro extends LinearOpMode { /* Declare OpMode members. */ HardwarePushbot robot = new HardwarePushbot(); // Use a Pushbot's hardware private ElapsedTime runtime = new ElapsedTime(); static final double FORWARD_SPEED = 0.6; static final double TURN_SPEED = 0.5; @Override public void runOpMode() { /* * Initialize the drive system variables. * The init() method of the hardware class does all the work here */ robot.init(hardwareMap); // Send telemetry message to signify robot waiting; telemetry.addData("Status", "Ready to run"); // telemetry.update(); // Wait for the game to start (driver presses PLAY) waitForStart(); // Step through each leg of the path, ensuring that the Auto mode has not been stopped along the way // Step 1: Drive forward for 3 seconds robot.leftDrive.setPower(FORWARD_SPEED); robot.rightDrive.setPower(FORWARD_SPEED); runtime.reset(); while (opModeIsActive() && (runtime.seconds() < 3.0)) { telemetry.addData("Path", "Leg 1: %2.5f S Elapsed", runtime.seconds()); telemetry.update(); } // Step 2: Spin right for 1.3 seconds robot.leftDrive.setPower(TURN_SPEED); robot.rightDrive.setPower(-TURN_SPEED); runtime.reset(); while (opModeIsActive() && (runtime.seconds() < 1.3)) { telemetry.addData("Path", "Leg 2: %2.5f S Elapsed", runtime.seconds()); telemetry.update(); } // Step 3: Drive Backwards for 1 Second robot.leftDrive.setPower(-FORWARD_SPEED); robot.rightDrive.setPower(-FORWARD_SPEED); runtime.reset(); while (opModeIsActive() && (runtime.seconds() < 1.0)) { telemetry.addData("Path", "Leg 3: %2.5f S Elapsed", runtime.seconds()); telemetry.update(); } // Step 4: Stop and close the claw. robot.leftDrive.setPower(0); robot.rightDrive.setPower(0); robot.leftClaw.setPosition(1.0); robot.rightClaw.setPosition(0.0); telemetry.addData("Path", "Complete"); telemetry.update(); sleep(1000); } }
e1c893187ac79afef3b8db8a706ac63edfae1e6d
bfff24d1042a4cc926c411916e59fdcabdb62b1c
/src/test/java/com/codewars/kyu7/AlphabetWar/AlphabetWarTest.java
8f392a0979a3a3dbe32c71297419682ea03632b7
[]
no_license
mkosecki1/codewars
5b9e4982158f8b116ed35276d4a156e22215c4ec
c57147e8577f1b4540b9dcb8accd1199376fc1a5
refs/heads/master
2021-03-30T23:32:27.446891
2019-01-06T13:41:53
2019-01-06T13:41:53
124,662,737
0
0
null
null
null
null
UTF-8
Java
false
false
465
java
package com.codewars.kyu7.AlphabetWar; import org.junit.Test; import static org.junit.Assert.assertEquals; public class AlphabetWarTest { @Test public void BasicTest() { assertEquals("Right side wins!", Kata.alphabetWar("z")); assertEquals("Let's fight again!", Kata.alphabetWar("zdqmwpbs")); assertEquals("Right side wins!", Kata.alphabetWar("zzzzs")); assertEquals("Left side wins!", Kata.alphabetWar("wwwwwwz")); } }
ac10787892da6df0d54fd450ccef262bc64cbdf6
57e9ddffc08d7f2d48c78f01a266d9823c1fffb5
/article-service/src/main/java/cn/manchester/blog/article/ArticleApplication.java
9f563ecbbdbe661e5951c301d801ed02ba4e4d43
[]
no_license
ManchesterLee/blog
927cb8f121ed0d4ed1ebbd0a551b04e993aa1d9f
4e235bbc831458f4fc4f9b4afe265fefc38584b7
refs/heads/master
2021-01-12T16:08:49.718471
2019-02-21T05:05:47
2019-02-21T05:05:47
70,562,704
0
0
null
null
null
null
UTF-8
Java
false
false
851
java
package cn.manchester.blog.article; import cn.manchester.blog.account.facade.AccountFacade; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.openfeign.EnableFeignClients; /** * @author ManchesterLee <a href="mailto:[email protected]">Contact me.</a> * @version 1.0 * @since 2019-02-16 */ @SpringBootApplication @EnableDiscoveryClient @EnableFeignClients(basePackages = "cn.manchester.blog") public class ArticleApplication { @Autowired private AccountFacade accountFacade; public static void main(String[] args) { SpringApplication.run(ArticleApplication.class); } }
b51f3194bbac67370d16bb40bd31cf103735f1cf
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/30/30_79826b292cecba9c0cb4f3117d09900c1b664408/Tokenizer/30_79826b292cecba9c0cb4f3117d09900c1b664408_Tokenizer_s.java
2268621bd04b96fdc8c051eb6e227cd900a4c56c
[]
no_license
zhongxingyu/Seer
48e7e5197624d7afa94d23f849f8ea2075bcaec0
c11a3109fdfca9be337e509ecb2c085b60076213
refs/heads/master
2023-07-06T12:48:55.516692
2023-06-22T07:55:56
2023-06-22T07:55:56
259,613,157
6
2
null
2023-06-22T07:55:57
2020-04-28T11:07:49
null
UTF-8
Java
false
false
235,294
java
/* * Copyright (c) 2005, 2006, 2007 Henri Sivonen * Copyright (c) 2007-2008 Mozilla Foundation * Portions of comments Copyright 2004-2007 Apple Computer, Inc., Mozilla * Foundation, and Opera Software ASA. * * 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. */ /* * The comments following this one that use the same comment syntax as this * comment are quotes from the WHATWG HTML 5 spec as of 2 June 2007 * amended as of June 18 2008. * That document came with this statement: * "© Copyright 2004-2007 Apple Computer, Inc., Mozilla Foundation, and * Opera Software ASA. You are granted a license to use, reproduce and * create derivative works of this document." */ package nu.validator.htmlparser.impl; import nu.validator.htmlparser.annotation.Local; import nu.validator.htmlparser.annotation.NoLength; import nu.validator.htmlparser.common.EncodingDeclarationHandler; import nu.validator.htmlparser.common.TokenHandler; import nu.validator.htmlparser.common.XmlViolationPolicy; import org.xml.sax.ErrorHandler; import org.xml.sax.Locator; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; /** * An implementation of * http://www.whatwg.org/specs/web-apps/current-work/multipage/tokenization.html * * This class implements the <code>Locator</code> interface. This is not an * incidental implementation detail: Users of this class are encouraged to make * use of the <code>Locator</code> nature. * * By default, the tokenizer may report data that XML 1.0 bans. The tokenizer * can be configured to treat these conditions as fatal or to coerce the infoset * to something that XML 1.0 allows. * * @version $Id$ * @author hsivonen */ public final class Tokenizer implements Locator { private static final int DATA = 0; private static final int RCDATA = 1; private static final int CDATA = 2; private static final int PLAINTEXT = 3; private static final int TAG_OPEN = 49; private static final int CLOSE_TAG_OPEN_PCDATA = 50; private static final int TAG_NAME = 58; private static final int BEFORE_ATTRIBUTE_NAME = 4; private static final int ATTRIBUTE_NAME = 5; private static final int AFTER_ATTRIBUTE_NAME = 6; private static final int BEFORE_ATTRIBUTE_VALUE = 7; private static final int ATTRIBUTE_VALUE_DOUBLE_QUOTED = 8; private static final int ATTRIBUTE_VALUE_SINGLE_QUOTED = 9; private static final int ATTRIBUTE_VALUE_UNQUOTED = 10; private static final int AFTER_ATTRIBUTE_VALUE_QUOTED = 11; private static final int BOGUS_COMMENT = 12; private static final int MARKUP_DECLARATION_OPEN = 13; private static final int DOCTYPE = 14; private static final int BEFORE_DOCTYPE_NAME = 15; private static final int DOCTYPE_NAME = 16; private static final int AFTER_DOCTYPE_NAME = 17; private static final int BEFORE_DOCTYPE_PUBLIC_IDENTIFIER = 18; private static final int DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED = 19; private static final int DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED = 20; private static final int AFTER_DOCTYPE_PUBLIC_IDENTIFIER = 21; private static final int BEFORE_DOCTYPE_SYSTEM_IDENTIFIER = 22; private static final int DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED = 23; private static final int DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED = 24; private static final int AFTER_DOCTYPE_SYSTEM_IDENTIFIER = 25; private static final int BOGUS_DOCTYPE = 26; private static final int COMMENT_START = 27; private static final int COMMENT_START_DASH = 28; private static final int COMMENT = 29; private static final int COMMENT_END_DASH = 30; private static final int COMMENT_END = 31; private static final int CLOSE_TAG_OPEN_NOT_PCDATA = 32; private static final int MARKUP_DECLARATION_HYPHEN = 33; private static final int MARKUP_DECLARATION_OCTYPE = 34; private static final int DOCTYPE_UBLIC = 35; private static final int DOCTYPE_YSTEM = 36; private static final int CONSUME_CHARACTER_REFERENCE = 37; private static final int CONSUME_NCR = 38; private static final int CHARACTER_REFERENCE_LOOP = 39; private static final int HEX_NCR_LOOP = 41; private static final int DECIMAL_NRC_LOOP = 42; private static final int HANDLE_NCR_VALUE = 43; private static final int SELF_CLOSING_START_TAG = 44; private static final int CDATA_START = 45; private static final int CDATA_SECTION = 46; private static final int CDATA_RSQB = 47; private static final int CDATA_RSQB_RSQB = 48; private static final int TAG_OPEN_NON_PCDATA = 51; private static final int ESCAPE_EXCLAMATION = 52; private static final int ESCAPE_EXCLAMATION_HYPHEN = 53; private static final int ESCAPE = 54; private static final int ESCAPE_HYPHEN = 55; private static final int ESCAPE_HYPHEN_HYPHEN = 56; private static final int BOGUS_COMMENT_HYPHEN = 57; /** * Magic value for UTF-16 operations. */ private static final int LEAD_OFFSET = 0xD800 - (0x10000 >> 10); /** * Magic value for UTF-16 operations. */ private static final int SURROGATE_OFFSET = 0x10000 - (0xD800 << 10) - 0xDC00; /** * UTF-16 code unit array containing less than and greater than for emitting * those characters on certain parse errors. */ private static final @NoLength char[] LT_GT = { '<', '>' }; /** * UTF-16 code unit array containing less than and solidus for emitting * those characters on certain parse errors. */ private static final @NoLength char[] LT_SOLIDUS = { '<', '/' }; /** * UTF-16 code unit array containing ]] for emitting those characters on * state transitions. */ private static final @NoLength char[] RSQB_RSQB = { ']', ']' }; /** * Array version of U+FFFD. */ private static final char[] REPLACEMENT_CHARACTER = { '\uFFFD' }; /** * Array version of space. */ private static final char[] SPACE = { ' ' }; /** * Array version of line feed. */ private static final char[] LF = { '\n' }; /** * Buffer growth parameter. */ private static final int BUFFER_GROW_BY = 1024; /** * "CDATA[" as <code>char[]</code> */ private static final @NoLength char[] CDATA_LSQB = "CDATA[".toCharArray(); /** * "octype" as <code>char[]</code> */ private static final @NoLength char[] OCTYPE = "octype".toCharArray(); /** * "ublic" as <code>char[]</code> */ private static final @NoLength char[] UBLIC = "ublic".toCharArray(); /** * "ystem" as <code>char[]</code> */ private static final @NoLength char[] YSTEM = "ystem".toCharArray(); private final EncodingDeclarationHandler encodingDeclarationHandler; /** * The token handler. */ private final TokenHandler tokenHandler; /** * The error handler. */ private ErrorHandler errorHandler; /** * The previous <code>char</code> read from the buffer with infoset * alteration applied except for CR. Used for CRLF normalization and * surrogate pair checking. */ private char prev; /** * The current line number in the current resource being parsed. (First line * is 1.) Passed on as locator data. */ private int line; private int linePrev; /** * The current column number in the current resource being tokenized. (First * column is 1, counted by UTF-16 code units.) Passed on as locator data. */ private int col; private int colPrev; private boolean nextCharOnNewLine; private int stateSave; private int returnStateSave; private int index; private boolean forceQuirks; private char additional; private int entCol; private int lo; private int hi; private int candidate; private int strBufMark; private int prevValue; private int value; private boolean seenDigits; private int pos; private int end; private @NoLength char[] buf; private int cstart; /** * The SAX public id for the resource being tokenized. (Only passed to back * as part of locator data.) */ private String publicId; /** * The SAX system id for the resource being tokenized. (Only passed to back * as part of locator data.) */ private String systemId; /** * Buffer for short identifiers. */ private char[] strBuf; /** * Number of significant <code>char</code>s in <code>strBuf</code>. */ private int strBufLen = 0; /** * <code>-1</code> to indicate that <code>strBuf</code> is used or * otherwise an offset to the main buffer. */ private int strBufOffset = -1; /** * Buffer for long strings. */ private char[] longStrBuf; /** * Number of significant <code>char</code>s in <code>longStrBuf</code>. */ private int longStrBufLen = 0; /** * <code>-1</code> to indicate that <code>longStrBuf</code> is used or * otherwise an offset to the main buffer. */ private int longStrBufOffset = -1; /** * The attribute holder. */ private HtmlAttributes attributes; /** * Buffer for expanding NCRs falling into the Basic Multilingual Plane. */ private final char[] bmpChar = new char[1]; /** * Buffer for expanding astral NCRs. */ private final char[] astralChar = new char[2]; /** * Keeps track of PUA warnings. */ private boolean alreadyWarnedAboutPrivateUseCharacters; /** * http://www.whatwg.org/specs/web-apps/current-work/#content2 */ private ContentModelFlag contentModelFlag = ContentModelFlag.PCDATA; /** * The element whose end tag closes the current CDATA or RCDATA element. */ private ElementName contentModelElement = null; /** * <code>true</code> if tokenizing an end tag */ private boolean endTag; /** * The current tag token name. */ private ElementName tagName = null; /** * The current attribute name. */ private AttributeName attributeName = null; /** * Whether comment tokens are emitted. */ private boolean wantsComments = false; /** * If <code>false</code>, <code>addAttribute*()</code> are no-ops. */ private boolean shouldAddAttributes; /** * <code>true</code> when HTML4-specific additional errors are requested. */ private boolean html4; /** * Used together with <code>nonAsciiProhibited</code>. */ private boolean alreadyComplainedAboutNonAscii; /** * Whether the stream is past the first 512 bytes. */ private boolean metaBoundaryPassed; /** * The name of the current doctype token. */ private @Local String doctypeName; /** * The public id of the current doctype token. */ private String publicIdentifier; /** * The system id of the current doctype token. */ private String systemIdentifier; // [NOCPP[ /** * The policy for vertical tab and form feed. */ private XmlViolationPolicy contentSpacePolicy = XmlViolationPolicy.ALTER_INFOSET; /** * The policy for non-space non-XML characters. */ private XmlViolationPolicy contentNonXmlCharPolicy = XmlViolationPolicy.ALTER_INFOSET; /** * The policy for comments. */ private XmlViolationPolicy commentPolicy = XmlViolationPolicy.ALTER_INFOSET; private XmlViolationPolicy xmlnsPolicy = XmlViolationPolicy.ALTER_INFOSET; private XmlViolationPolicy namePolicy = XmlViolationPolicy.ALTER_INFOSET; private boolean html4ModeCompatibleWithXhtml1Schemata; private final boolean newAttributesEachTime; // ]NOCPP] private int mappingLangToXmlLang; private boolean shouldSuspend; private boolean confident; private PushedLocation pushedLocation; private LocatorImpl ampersandLocation; /** * The constructor. * * @param tokenHandler * the handler for receiving tokens */ public Tokenizer(TokenHandler tokenHandler) { this.tokenHandler = tokenHandler; this.encodingDeclarationHandler = null; this.newAttributesEachTime = false; } public Tokenizer(TokenHandler tokenHandler, EncodingDeclarationHandler encodingDeclarationHandler) { this.tokenHandler = tokenHandler; this.encodingDeclarationHandler = encodingDeclarationHandler; this.newAttributesEachTime = false; } public void initLocation(String newPublicId, String newSystemId) { this.systemId = newSystemId; this.publicId = newPublicId; } // [NOCPP[ public Tokenizer(TokenHandler tokenHandler, EncodingDeclarationHandler encodingDeclarationHandler, boolean newAttributesEachTime) { this.tokenHandler = tokenHandler; this.encodingDeclarationHandler = encodingDeclarationHandler; this.newAttributesEachTime = newAttributesEachTime; } // ]NOCPP] /** * Returns the mappingLangToXmlLang. * * @return the mappingLangToXmlLang */ public boolean isMappingLangToXmlLang() { return mappingLangToXmlLang == AttributeName.HTML_LANG; } /** * Sets the mappingLangToXmlLang. * * @param mappingLangToXmlLang * the mappingLangToXmlLang to set */ public void setMappingLangToXmlLang(boolean mappingLangToXmlLang) { this.mappingLangToXmlLang = mappingLangToXmlLang ? AttributeName.HTML_LANG : AttributeName.HTML; } /** * Sets the error handler. * * @see org.xml.sax.XMLReader#setErrorHandler(org.xml.sax.ErrorHandler) */ public void setErrorHandler(ErrorHandler eh) { this.errorHandler = eh; } public ErrorHandler getErrorHandler() { return this.errorHandler; } // [NOCPP[ /** * Sets the commentPolicy. * * @param commentPolicy * the commentPolicy to set */ public void setCommentPolicy(XmlViolationPolicy commentPolicy) { this.commentPolicy = commentPolicy; } /** * Sets the contentNonXmlCharPolicy. * * @param contentNonXmlCharPolicy * the contentNonXmlCharPolicy to set */ public void setContentNonXmlCharPolicy( XmlViolationPolicy contentNonXmlCharPolicy) { this.contentNonXmlCharPolicy = contentNonXmlCharPolicy; } /** * Sets the contentSpacePolicy. * * @param contentSpacePolicy * the contentSpacePolicy to set */ public void setContentSpacePolicy(XmlViolationPolicy contentSpacePolicy) { this.contentSpacePolicy = contentSpacePolicy; } /** * Sets the xmlnsPolicy. * * @param xmlnsPolicy * the xmlnsPolicy to set */ public void setXmlnsPolicy(XmlViolationPolicy xmlnsPolicy) { if (xmlnsPolicy == XmlViolationPolicy.FATAL) { throw new IllegalArgumentException("Can't use FATAL here."); } this.xmlnsPolicy = xmlnsPolicy; } public void setNamePolicy(XmlViolationPolicy namePolicy) { this.namePolicy = namePolicy; } /** * Sets the html4ModeCompatibleWithXhtml1Schemata. * * @param html4ModeCompatibleWithXhtml1Schemata * the html4ModeCompatibleWithXhtml1Schemata to set */ public void setHtml4ModeCompatibleWithXhtml1Schemata( boolean html4ModeCompatibleWithXhtml1Schemata) { this.html4ModeCompatibleWithXhtml1Schemata = html4ModeCompatibleWithXhtml1Schemata; } // ]NOCPP] // For the token handler to call /** * Sets the content model flag and the associated element name. * * @param contentModelFlag * the flag * @param contentModelElement * the element causing the flag to be set */ public void setContentModelFlag(ContentModelFlag contentModelFlag, @Local String contentModelElement) { this.contentModelFlag = contentModelFlag; char[] asArray = Portability.newCharArrayFromLocal(contentModelElement); this.contentModelElement = ElementName.elementNameByBuffer(asArray, 0, asArray.length); } /** * Sets the content model flag and the associated element name. * * @param contentModelFlag * the flag * @param contentModelElement * the element causing the flag to be set */ public void setContentModelFlag(ContentModelFlag contentModelFlag, ElementName contentModelElement) { this.contentModelFlag = contentModelFlag; this.contentModelElement = contentModelElement; } // start Locator impl /** * @see org.xml.sax.Locator#getPublicId() */ public String getPublicId() { return publicId; } /** * @see org.xml.sax.Locator#getSystemId() */ public String getSystemId() { return systemId; } /** * @see org.xml.sax.Locator#getLineNumber() */ public int getLineNumber() { if (line > 0) { return line; } else { return -1; } } /** * @see org.xml.sax.Locator#getColumnNumber() */ public int getColumnNumber() { if (col > 0) { return col; } else { return -1; } } // end Locator impl // end public API public void notifyAboutMetaBoundary() { metaBoundaryPassed = true; } // [NOCPP[ void turnOnAdditionalHtml4Errors() { html4 = true; } // ]NOCPP] HtmlAttributes emptyAttributes() { // [NOCPP[ if (newAttributesEachTime) { return new HtmlAttributes(mappingLangToXmlLang); } else { // ]NOCPP] return HtmlAttributes.EMPTY_ATTRIBUTES; // [NOCPP[ } // ]NOCPP] } private void detachStrBuf() { // if (strBufOffset == -1) { // return; // } // if (strBufLen > 0) { // if (strBuf.length < strBufLen) { // Portability.releaseArray(strBuf); // strBuf = new char[strBufLen + (strBufLen >> 1)]; // } // System.arraycopy(buf, strBufOffset, strBuf, 0, strBufLen); // } // strBufOffset = -1; } private void detachLongStrBuf() { // if (longStrBufOffset == -1) { // return; // } // if (longStrBufLen > 0) { // if (longStrBuf.length < longStrBufLen) { // Portability.releaseArray(longStrBuf); // longStrBuf = new char[longStrBufLen + (longStrBufLen >> 1)]; // } // System.arraycopy(buf, longStrBufOffset, longStrBuf, 0, // longStrBufLen); // } // longStrBufOffset = -1; } private void clearStrBufAndAppendCurrentC(char c) { strBuf[0] = c; strBufLen = 1; // strBufOffset = pos; } private void clearStrBufAndAppendForceWrite(char c) { strBuf[0] = c; // test strBufLen = 1; // strBufOffset = pos; // buf[pos] = c; } private void clearStrBufForNextState() { strBufLen = 0; // strBufOffset = pos + 1; } /** * Appends to the smaller buffer. * * @param c * the UTF-16 code unit to append */ private void appendStrBuf(char c) { // if (strBufOffset != -1) { // strBufLen++; // } else { if (strBufLen == strBuf.length) { char[] newBuf = new char[strBuf.length + Tokenizer.BUFFER_GROW_BY]; System.arraycopy(strBuf, 0, newBuf, 0, strBuf.length); strBuf = newBuf; } strBuf[strBufLen++] = c; // } } /** * Appends to the smaller buffer. * * @param c * the UTF-16 code unit to append */ private void appendStrBufForceWrite(char c) { // if (strBufOffset != -1) { // strBufLen++; // buf[pos] = c; // } else { if (strBufLen == strBuf.length) { char[] newBuf = new char[strBuf.length + Tokenizer.BUFFER_GROW_BY]; System.arraycopy(strBuf, 0, newBuf, 0, strBuf.length); strBuf = newBuf; } strBuf[strBufLen++] = c; // } } /** * The smaller buffer as a String. * * @return the smaller buffer as a string */ private String strBufToString() { // if (strBufOffset != -1) { // return Portability.newStringFromBuffer(buf, strBufOffset, strBufLen); // } else { return Portability.newStringFromBuffer(strBuf, 0, strBufLen); // } } /** * Emits the smaller buffer as character tokens. * * @throws SAXException * if the token handler threw */ private void emitStrBuf() throws SAXException { if (strBufLen > 0) { // if (strBufOffset != -1) { // tokenHandler.characters(buf, strBufOffset, strBufLen); // } else { tokenHandler.characters(strBuf, 0, strBufLen); // } } } private void clearLongStrBufForNextState() { // longStrBufOffset = pos + 1; longStrBufLen = 0; } private void clearLongStrBuf() { // longStrBufOffset = pos; longStrBufLen = 0; } private void clearLongStrBufAndAppendCurrentC() { longStrBuf[0] = buf[pos]; longStrBufLen = 1; // longStrBufOffset = pos; } private void clearLongStrBufAndAppendToComment(char c) { longStrBuf[0] = c; // longStrBufOffset = pos; longStrBufLen = 1; } /** * Appends to the larger buffer. * * @param c * the UTF-16 code unit to append */ private void appendLongStrBuf(char c) { // if (longStrBufOffset != -1) { // longStrBufLen++; // } else { if (longStrBufLen == longStrBuf.length) { char[] newBuf = new char[longStrBufLen + (longStrBufLen >> 1)]; System.arraycopy(longStrBuf, 0, newBuf, 0, longStrBuf.length); Portability.releaseArray(longStrBuf); longStrBuf = newBuf; } longStrBuf[longStrBufLen++] = c; // } } private void appendSecondHyphenToBogusComment() throws SAXException { switch (commentPolicy) { case ALTER_INFOSET: // detachLongStrBuf(); appendLongStrBuf(' '); // FALLTHROUGH case ALLOW: warn("The document is not mappable to XML 1.0 due to two consecutive hyphens in a comment."); appendLongStrBuf('-'); break; case FATAL: fatal("The document is not mappable to XML 1.0 due to two consecutive hyphens in a comment."); break; } } private void maybeAppendSpaceToBogusComment() throws SAXException { switch (commentPolicy) { case ALTER_INFOSET: // detachLongStrBuf(); appendLongStrBuf(' '); // FALLTHROUGH case ALLOW: warn("The document is not mappable to XML 1.0 due to a trailing hyphen in a comment."); break; case FATAL: fatal("The document is not mappable to XML 1.0 due to a trailing hyphen in a comment."); break; } } private void adjustDoubleHyphenAndAppendToLongStrBuf(char c) throws SAXException { switch (commentPolicy) { case ALTER_INFOSET: // detachLongStrBuf(); longStrBufLen--; appendLongStrBuf(' '); appendLongStrBuf('-'); // FALLTHROUGH case ALLOW: warn("The document is not mappable to XML 1.0 due to two consecutive hyphens in a comment."); appendLongStrBuf(c); break; case FATAL: fatal("The document is not mappable to XML 1.0 due to two consecutive hyphens in a comment."); break; } } private void appendLongStrBuf(char[] buffer, int offset, int length) { int reqLen = longStrBufLen + length; if (longStrBuf.length < reqLen) { char[] newBuf = new char[reqLen + (reqLen >> 1)]; System.arraycopy(longStrBuf, 0, newBuf, 0, longStrBuf.length); Portability.releaseArray(longStrBuf); longStrBuf = newBuf; } System.arraycopy(buffer, offset, longStrBuf, longStrBufLen, length); longStrBufLen = reqLen; } /** * Appends to the larger buffer. * * @param arr * the UTF-16 code units to append */ private void appendLongStrBuf(char[] arr) { // assert longStrBufOffset == -1; appendLongStrBuf(arr, 0, arr.length); } /** * Append the contents of the smaller buffer to the larger one. */ private void appendStrBufToLongStrBuf() { // assert longStrBufOffset == -1; // if (strBufOffset != -1) { // appendLongStrBuf(buf, strBufOffset, strBufLen); // } else { appendLongStrBuf(strBuf, 0, strBufLen); // } } /** * The larger buffer as a string. * * @return the larger buffer as a string */ private String longStrBufToString() { // if (longStrBufOffset != -1) { // return Portability.newStringFromBuffer(buf, longStrBufOffset, // longStrBufLen); // } else { return Portability.newStringFromBuffer(longStrBuf, 0, longStrBufLen); // } } /** * Emits the current comment token. * * @throws SAXException */ private void emitComment(int provisionalHyphens) throws SAXException { if (wantsComments) { // if (longStrBufOffset != -1) { // tokenHandler.comment(buf, longStrBufOffset, longStrBufLen // - provisionalHyphens); // } else { tokenHandler.comment(longStrBuf, 0, longStrBufLen - provisionalHyphens); // } } cstart = pos + 1; } // [NOCPP[ private String toUPlusString(char c) { String hexString = Integer.toHexString(c); switch (hexString.length()) { case 1: return "U+000" + hexString; case 2: return "U+00" + hexString; case 3: return "U+0" + hexString; case 4: return "U+" + hexString; default: throw new RuntimeException("Unreachable."); } } // ]NOCPP] /** * Emits a warning about private use characters if the warning has not been * emitted yet. * * @throws SAXException */ private void warnAboutPrivateUseChar() throws SAXException { if (!alreadyWarnedAboutPrivateUseCharacters) { warn("Document uses the Unicode Private Use Area(s), which should not be used in publicly exchanged documents. (Charmod C073)"); alreadyWarnedAboutPrivateUseCharacters = true; } } /** * Tells if the argument is a BMP PUA character. * * @param c * the UTF-16 code unit to check * @return <code>true</code> if PUA character */ private boolean isPrivateUse(char c) { return c >= '\uE000' && c <= '\uF8FF'; } /** * Tells if the argument is an astral PUA character. * * @param c * the code point to check * @return <code>true</code> if astral private use */ private boolean isAstralPrivateUse(int c) { return (c >= 0xF0000 && c <= 0xFFFFD) || (c >= 0x100000 && c <= 0x10FFFD); } /** * Tells if the argument is a non-character (works for BMP and astral). * * @param c * the code point to check * @return <code>true</code> if non-character */ private boolean isNonCharacter(int c) { return (c & 0xFFFE) == 0xFFFE; } /** * Flushes coalesced character tokens. * * @throws SAXException */ private void flushChars() throws SAXException { if (pos > cstart) { int currLine = line; int currCol = col; line = linePrev; col = colPrev; tokenHandler.characters(buf, cstart, pos - cstart); line = currLine; col = currCol; } cstart = Integer.MAX_VALUE; } /** * Reports an condition that would make the infoset incompatible with XML * 1.0 as fatal. * * @param message * the message * @throws SAXException * @throws SAXParseException */ public void fatal(String message) throws SAXException { SAXParseException spe = new SAXParseException(message, this); if (errorHandler != null) { errorHandler.fatalError(spe); } throw spe; } /** * Reports a Parse Error. * * @param message * the message * @throws SAXException */ public void err(String message) throws SAXException { if (errorHandler == null) { return; } SAXParseException spe = new SAXParseException(message, this); errorHandler.error(spe); } public void errTreeBuilder(String message) throws SAXException { ErrorHandler eh = null; if (tokenHandler instanceof TreeBuilder<?>) { TreeBuilder<?> treeBuilder = (TreeBuilder<?>) tokenHandler; eh = treeBuilder.getErrorHandler(); } if (eh == null) { eh = errorHandler; } if (eh == null) { return; } SAXParseException spe = new SAXParseException(message, this); eh.error(spe); } /** * Reports a warning * * @param message * the message * @throws SAXException */ public void warn(String message) throws SAXException { if (errorHandler == null) { return; } SAXParseException spe = new SAXParseException(message, this); errorHandler.warning(spe); } /** * */ private void resetAttributes() { // [NOCPP[ if (newAttributesEachTime) { attributes = null; } else { // ]NOCPP] attributes.clear(); // [NOCPP[ } // ]NOCPP] } private ElementName strBufToElementNameString() { // if (strBufOffset != -1) { // return ElementName.elementNameByBuffer(buf, strBufOffset, strBufLen); // } else { return ElementName.elementNameByBuffer(strBuf, 0, strBufLen); // } } private int emitCurrentTagToken(boolean selfClosing) throws SAXException { cstart = pos + 1; if (selfClosing && endTag) { err("Stray \u201C/\u201D at the end of an end tag."); } int rv = Tokenizer.DATA; HtmlAttributes attrs = (attributes == null ? HtmlAttributes.EMPTY_ATTRIBUTES : attributes); if (endTag) { /* * When an end tag token is emitted, the content model flag must be * switched to the PCDATA state. */ contentModelFlag = ContentModelFlag.PCDATA; if (attrs.getLength() != 0) { /* * When an end tag token is emitted with attributes, that is a * parse error. */ err("End tag had attributes."); } tokenHandler.endTag(tagName); } else { tokenHandler.startTag(tagName, attrs, selfClosing); switch (contentModelFlag) { case PCDATA: rv = Tokenizer.DATA; break; case CDATA: rv = Tokenizer.CDATA; break; case RCDATA: rv = Tokenizer.RCDATA; break; case PLAINTEXT: rv = Tokenizer.PLAINTEXT; } } resetAttributes(); return rv; } private void attributeNameComplete() throws SAXException { // if (strBufOffset != -1) { // attributeName = AttributeName.nameByBuffer(buf, strBufOffset, // strBufLen, namePolicy != XmlViolationPolicy.ALLOW); // } else { attributeName = AttributeName.nameByBuffer(strBuf, 0, strBufLen, namePolicy != XmlViolationPolicy.ALLOW); // } // [NOCPP[ if (attributes == null) { attributes = new HtmlAttributes(mappingLangToXmlLang); } // ]NOCPP] /* * When the user agent leaves the attribute name state (and before * emitting the tag token, if appropriate), the complete attribute's * name must be compared to the other attributes on the same token; if * there is already an attribute on the token with the exact same name, * then this is a parse error and the new attribute must be dropped, * along with the value that gets associated with it (if any). */ if (attributes.contains(attributeName)) { shouldAddAttributes = false; err("Duplicate attribute \u201C" + attributeName.getLocal(AttributeName.HTML) + "\u201D."); } else { shouldAddAttributes = true; // if (namePolicy == XmlViolationPolicy.ALLOW) { // shouldAddAttributes = true; // } else { // if (NCName.isNCName(attributeName)) { // shouldAddAttributes = true; // } else { // if (namePolicy == XmlViolationPolicy.FATAL) { // fatal("Attribute name \u201C" + attributeName // + "\u201D is not an NCName."); // } else { // shouldAddAttributes = false; // warn("Attribute name \u201C" // + attributeName // + "\u201D is not an NCName. Ignoring the attribute."); // } // } // } } } private void addAttributeWithoutValue() throws SAXException { // [NOCPP[ if (metaBoundaryPassed && AttributeName.CHARSET == attributeName && ElementName.META == tagName) { err("A \u201Ccharset\u201D attribute on a \u201Cmeta\u201D element found after the first 512 bytes."); } // ]NOCPP] if (shouldAddAttributes) { // [NOCPP[ if (html4) { if (attributeName.isBoolean()) { if (html4ModeCompatibleWithXhtml1Schemata) { attributes.addAttribute(attributeName, attributeName.getLocal(AttributeName.HTML), xmlnsPolicy); } else { attributes.addAttribute(attributeName, "", xmlnsPolicy); } } else { err("Attribute value omitted for a non-boolean attribute. (HTML4-only error.)"); attributes.addAttribute(attributeName, "", xmlnsPolicy); } } else { if (AttributeName.SRC == attributeName || AttributeName.HREF == attributeName) { warn("Attribute \u201C" + attributeName.getLocal(AttributeName.HTML) + "\u201D without an explicit value seen. The attribute may be dropped by IE7."); } // ]NOCPP] attributes.addAttribute(attributeName, "", xmlnsPolicy); // [NOCPP[ } // ]NOCPP] } } private void addAttributeWithValue() throws SAXException { // [NOCPP[ if (metaBoundaryPassed && ElementName.META == tagName && AttributeName.CHARSET == attributeName) { err("A \u201Ccharset\u201D attribute on a \u201Cmeta\u201D element found after the first 512 bytes."); } // ]NOCPP] if (shouldAddAttributes) { String value = longStrBufToString(); // [NOCPP[ if (!endTag && html4 && html4ModeCompatibleWithXhtml1Schemata && attributeName.isCaseFolded()) { value = newAsciiLowerCaseStringFromString(value); } // ]NOCPP] attributes.addAttribute(attributeName, value, xmlnsPolicy); } } // [NOCPP[ private static String newAsciiLowerCaseStringFromString(String str) { if (str == null) { return null; } char[] buf = new char[str.length()]; for (int i = 0; i < str.length(); i++) { char c = str.charAt(i); if (c >= 'A' && c <= 'Z') { c += 0x20; } buf[i] = c; } return new String(buf); } // ]NOCPP] public void start() throws SAXException { confident = false; strBuf = new char[64]; longStrBuf = new char[1024]; alreadyComplainedAboutNonAscii = false; contentModelFlag = ContentModelFlag.PCDATA; line = linePrev = 0; col = colPrev = 1; nextCharOnNewLine = true; prev = '\u0000'; html4 = false; alreadyWarnedAboutPrivateUseCharacters = false; metaBoundaryPassed = false; tokenHandler.startTokenization(this); wantsComments = tokenHandler.wantsComments(); switch (contentModelFlag) { case PCDATA: stateSave = Tokenizer.DATA; break; case CDATA: stateSave = Tokenizer.CDATA; break; case RCDATA: stateSave = Tokenizer.RCDATA; break; case PLAINTEXT: stateSave = Tokenizer.PLAINTEXT; } index = 0; forceQuirks = false; additional = '\u0000'; entCol = -1; lo = 0; hi = (NamedCharacters.NAMES.length - 1); candidate = -1; strBufMark = 0; prevValue = -1; value = 0; seenDigits = false; shouldSuspend = false; // [NOCPP[ if (!newAttributesEachTime) { // ]NOCPP] attributes = new HtmlAttributes(mappingLangToXmlLang); // [NOCPP[ } // ]NOCPP] } public boolean tokenizeBuffer(UTF16Buffer buffer) throws SAXException { buf = buffer.getBuffer(); int state = stateSave; int returnState = returnStateSave; char c = '\u0000'; shouldSuspend = false; int start = buffer.getStart(); /** * The index of the last <code>char</code> read from <code>buf</code>. */ pos = start - 1; /** * The index of the first <code>char</code> in <code>buf</code> that * is part of a coalesced run of character tokens or * <code>Integer.MAX_VALUE</code> if there is not a current run being * coalesced. */ switch (state) { case DATA: case RCDATA: case CDATA: case PLAINTEXT: case CDATA_SECTION: case ESCAPE: case ESCAPE_EXCLAMATION: case ESCAPE_EXCLAMATION_HYPHEN: case ESCAPE_HYPHEN: case ESCAPE_HYPHEN_HYPHEN: cstart = start; break; default: cstart = Integer.MAX_VALUE; break; } /** * The number of <code>char</code>s in <code>buf</code> that have * meaning. (The rest of the array is garbage and should not be * examined.) */ end = buffer.getEnd(); boolean reconsume = false; stateLoop(state, c, reconsume, returnState); detachStrBuf(); detachLongStrBuf(); if (pos == end) { // exiting due to end of buffer buffer.setStart(pos); } else { buffer.setStart(pos + 1); } if (prev == '\r') { prev = ' '; return true; } else { return false; } } // WARNING When editing this, makes sure the bytecode length shown by javap // stays under 8000 bytes! private void stateLoop(int state, char c, boolean reconsume, int returnState) throws SAXException { stateloop: for (;;) { switch (state) { case DATA: dataloop: for (;;) { if (reconsume) { reconsume = false; } else { c = read(); } switch (c) { case '\u0000': break stateloop; case '&': /* * U+0026 AMPERSAND (&) When the content model * flag is set to one of the PCDATA or RCDATA * states and the escape flag is false: switch * to the character reference data state. * Otherwise: treat it as per the "anything * else" entry below. */ flushChars(); clearStrBufAndAppendCurrentC(c); additional = '\u0000'; rememberAmpersandLocation(); returnState = state; state = Tokenizer.CONSUME_CHARACTER_REFERENCE; continue stateloop; case '<': /* * U+003C LESS-THAN SIGN (<) When the content * model flag is set to the PCDATA state: switch * to the tag open state. When the content model * flag is set to either the RCDATA state or the * CDATA state and the escape flag is false: * switch to the tag open state. Otherwise: * treat it as per the "anything else" entry * below. */ flushChars(); state = Tokenizer.TAG_OPEN; break dataloop; // FALL THROUGH continue // stateloop; default: /* * Anything else Emit the input character as a * character token. */ /* * Stay in the data state. */ continue; } } // WARNING FALLTHRU CASE TRANSITION: DON'T REORDER case TAG_OPEN: tagopenloop: for (;;) { /* * The behavior of this state depends on the content * model flag. */ /* * If the content model flag is set to the PCDATA state * Consume the next input character: */ c = read(); if (c >= 'A' && c <= 'Z') { /* * U+0041 LATIN CAPITAL LETTER A through to U+005A * LATIN CAPITAL LETTER Z Create a new start tag * token, */ endTag = false; /* * set its tag name to the lowercase version of the * input character (add 0x0020 to the character's * code point), */ clearStrBufAndAppendForceWrite((char) (c + 0x20)); /* then switch to the tag name state. */ state = Tokenizer.TAG_NAME; /* * (Don't emit the token yet; further details will * be filled in before it is emitted.) */ break tagopenloop; // continue stateloop; } else if (c >= 'a' && c <= 'z') { /* * U+0061 LATIN SMALL LETTER A through to U+007A * LATIN SMALL LETTER Z Create a new start tag * token, */ endTag = false; /* * set its tag name to the input character, */ clearStrBufAndAppendCurrentC(c); /* then switch to the tag name state. */ state = Tokenizer.TAG_NAME; /* * (Don't emit the token yet; further details will * be filled in before it is emitted.) */ break tagopenloop; // continue stateloop; } switch (c) { case '\u0000': break stateloop; case '!': /* * U+0021 EXCLAMATION MARK (!) Switch to the * markup declaration open state. */ state = Tokenizer.MARKUP_DECLARATION_OPEN; continue stateloop; case '/': /* * U+002F SOLIDUS (/) Switch to the close tag * open state. */ state = Tokenizer.CLOSE_TAG_OPEN_PCDATA; continue stateloop; case '?': /* * U+003F QUESTION MARK (?) Parse error. */ err("Saw \u201C<?\u201D. Probable cause: Attempt to use an XML processing instruction in HTML. (XML processing instructions are not supported in HTML.)"); /* * Switch to the bogus comment state. */ clearLongStrBufAndAppendToComment('?'); state = Tokenizer.BOGUS_COMMENT; continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Parse error. */ err("Saw \u201C<>\u201D. Probable causes: Unescaped \u201C<\u201D (escape as \u201C&lt;\u201D) or mistyped start tag."); /* * Emit a U+003C LESS-THAN SIGN character token * and a U+003E GREATER-THAN SIGN character * token. */ tokenHandler.characters(Tokenizer.LT_GT, 0, 2); /* Switch to the data state. */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; default: /* * Anything else Parse error. */ err("Bad character \u201C" + c + "\u201D after \u201C<\u201D. Probable cause: Unescaped \u201C<\u201D. Try escaping it as \u201C&lt;\u201D."); /* * Emit a U+003C LESS-THAN SIGN character token */ tokenHandler.characters(Tokenizer.LT_GT, 0, 1); /* * and reconsume the current input character in * the data state. */ cstart = pos; state = Tokenizer.DATA; reconsume = true; continue stateloop; } } // FALL THROUGH DON'T REORDER case TAG_NAME: tagnameloop: for (;;) { c = read(); /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED * (LF) U+000C FORM FEED (FF) U+0020 SPACE * Switch to the before attribute name state. */ tagName = strBufToElementNameString(); state = Tokenizer.BEFORE_ATTRIBUTE_NAME; break tagnameloop; // continue stateloop; case '/': /* * U+002F SOLIDUS (/) Switch to the self-closing * start tag state. */ tagName = strBufToElementNameString(); state = Tokenizer.SELF_CLOSING_START_TAG; continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Emit the current * tag token. */ tagName = strBufToElementNameString(); state = emitCurrentTagToken(false); if (shouldSuspend) { break stateloop; } /* * Switch to the data state. */ continue stateloop; default: if (c >= 'A' && c <= 'Z') { /* * U+0041 LATIN CAPITAL LETTER A through to * U+005A LATIN CAPITAL LETTER Z Append the * lowercase version of the current input * character (add 0x0020 to the character's * code point) to the current tag token's * tag name. */ appendStrBufForceWrite((char) (c + 0x20)); } else { /* * Anything else Append the current input * character to the current tag token's tag * name. */ appendStrBuf(c); } /* * Stay in the tag name state. */ continue; } } // FALLTHRU DON'T REORDER case BEFORE_ATTRIBUTE_NAME: beforeattributenameloop: for (;;) { if (reconsume) { reconsume = false; } else { c = read(); } /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED * (LF) U+000C FORM FEED (FF) U+0020 SPACE Stay * in the before attribute name state. */ continue; case '/': /* * U+002F SOLIDUS (/) Switch to the self-closing * start tag state. */ state = Tokenizer.SELF_CLOSING_START_TAG; continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Emit the current * tag token. */ state = emitCurrentTagToken(false); if (shouldSuspend) { break stateloop; } /* * Switch to the data state. */ continue stateloop; case '\"': case '\'': case '=': /* * U+0022 QUOTATION MARK (") U+0027 APOSTROPHE * (') U+003D EQUALS SIGN (=) Parse error. */ if (c == '=') { err("Saw \u201C=\u201D when expecting an attribute name. Probable cause: Attribute name missing."); } else { errQuoteBeforeAttributeName(c); } /* * Treat it as per the "anything else" entry * below. */ default: /* * Anything else Start a new attribute in the * current tag token. */ if (c >= 'A' && c <= 'Z') { /* * U+0041 LATIN CAPITAL LETTER A through to * U+005A LATIN CAPITAL LETTER Z Set that * attribute's name to the lowercase version * of the current input character (add * 0x0020 to the character's code point) */ clearStrBufAndAppendForceWrite((char) (c + 0x20)); } else { /* * Set that attribute's name to the current * input character, */ clearStrBufAndAppendCurrentC(c); } /* * and its value to the empty string. */ // Will do later. /* * Switch to the attribute name state. */ state = Tokenizer.ATTRIBUTE_NAME; break beforeattributenameloop; // continue stateloop; } } // FALLTHRU DON'T REORDER case ATTRIBUTE_NAME: attributenameloop: for (;;) { c = read(); /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED * (LF) U+000C FORM FEED (FF) U+0020 SPACE * Switch to the after attribute name state. */ attributeNameComplete(); state = Tokenizer.AFTER_ATTRIBUTE_NAME; continue stateloop; case '/': /* * U+002F SOLIDUS (/) Switch to the self-closing * start tag state. */ attributeNameComplete(); addAttributeWithoutValue(); state = Tokenizer.SELF_CLOSING_START_TAG; continue stateloop; case '=': /* * U+003D EQUALS SIGN (=) Switch to the before * attribute value state. */ attributeNameComplete(); state = Tokenizer.BEFORE_ATTRIBUTE_VALUE; break attributenameloop; // continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Emit the current * tag token. */ attributeNameComplete(); addAttributeWithoutValue(); state = emitCurrentTagToken(false); if (shouldSuspend) { break stateloop; } /* * Switch to the data state. */ continue stateloop; case '\"': case '\'': /* * U+0022 QUOTATION MARK (") U+0027 APOSTROPHE * (') Parse error. */ errQuoteInAttributeName(c); /* * Treat it as per the "anything else" entry * below. */ default: if (c >= 'A' && c <= 'Z') { /* * U+0041 LATIN CAPITAL LETTER A through to * U+005A LATIN CAPITAL LETTER Z Append the * lowercase version of the current input * character (add 0x0020 to the character's * code point) to the current attribute's * name. */ appendStrBufForceWrite((char) (c + 0x20)); } else { /* * Anything else Append the current input * character to the current attribute's * name. */ appendStrBuf(c); } /* * Stay in the attribute name state. */ continue; } } // FALLTHRU DON'T REORDER case BEFORE_ATTRIBUTE_VALUE: beforeattributevalueloop: for (;;) { c = read(); /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED * (LF) U+000C FORM FEED (FF) U+0020 SPACE Stay * in the before attribute value state. */ continue; case '"': /* * U+0022 QUOTATION MARK (") Switch to the * attribute value (double-quoted) state. */ clearLongStrBufForNextState(); state = Tokenizer.ATTRIBUTE_VALUE_DOUBLE_QUOTED; break beforeattributevalueloop; // continue stateloop; case '&': /* * U+0026 AMPERSAND (&) Switch to the attribute * value (unquoted) state and reconsume this * input character. */ clearLongStrBuf(); state = Tokenizer.ATTRIBUTE_VALUE_UNQUOTED; reconsume = true; continue stateloop; case '\'': /* * U+0027 APOSTROPHE (') Switch to the attribute * value (single-quoted) state. */ clearLongStrBufForNextState(); state = Tokenizer.ATTRIBUTE_VALUE_SINGLE_QUOTED; continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Parse error. */ err("Attribute value missing."); /* * Emit the current tag token. */ addAttributeWithoutValue(); state = emitCurrentTagToken(false); if (shouldSuspend) { break stateloop; } /* * Switch to the data state. */ continue stateloop; case '=': /* * U+003D EQUALS SIGN (=) Parse error. */ err("\u201C=\u201D in an unquoted attribute value. Probable cause: Stray duplicate equals sign."); /* * Treat it as per the "anything else" entry * below. */ default: if (html4 && !((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '.' || c == '-' || c == '_' || c == ':')) { err("Non-name character in an unquoted attribute value. (This is an HTML4-only error.)"); } /* * Anything else Append the current input * character to the current attribute's value. */ clearLongStrBufAndAppendCurrentC(); /* * Switch to the attribute value (unquoted) * state. */ state = Tokenizer.ATTRIBUTE_VALUE_UNQUOTED; continue stateloop; } } // FALLTHRU DON'T REORDER case ATTRIBUTE_VALUE_DOUBLE_QUOTED: attributevaluedoublequotedloop: for (;;) { if (reconsume) { reconsume = false; } else { c = read(); } /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case '"': /* * U+0022 QUOTATION MARK (") Switch to the after * attribute value (quoted) state. */ addAttributeWithValue(); state = Tokenizer.AFTER_ATTRIBUTE_VALUE_QUOTED; break attributevaluedoublequotedloop; // continue stateloop; case '&': /* * U+0026 AMPERSAND (&) Switch to the character * reference in attribute value state, with the * additional allowed character being U+0022 * QUOTATION MARK ("). */ detachLongStrBuf(); clearStrBufAndAppendCurrentC(c); additional = '\"'; rememberAmpersandLocation(); returnState = state; state = Tokenizer.CONSUME_CHARACTER_REFERENCE; continue stateloop; default: /* * Anything else Append the current input * character to the current attribute's value. */ appendLongStrBuf(c); /* * Stay in the attribute value (double-quoted) * state. */ continue; } } // FALLTHRU DON'T REORDER case AFTER_ATTRIBUTE_VALUE_QUOTED: afterattributevaluequotedloop: for (;;) { c = read(); /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED * (LF) U+000C FORM FEED (FF) U+0020 SPACE * Switch to the before attribute name state. */ state = Tokenizer.BEFORE_ATTRIBUTE_NAME; continue stateloop; case '/': /* * U+002F SOLIDUS (/) Switch to the self-closing * start tag state. */ state = Tokenizer.SELF_CLOSING_START_TAG; break afterattributevaluequotedloop; // continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Emit the current * tag token. */ state = emitCurrentTagToken(false); if (shouldSuspend) { break stateloop; } /* * Switch to the data state. */ continue stateloop; default: /* * Anything else Parse error. */ err("No space between attributes."); /* * Reconsume the character in the before * attribute name state. */ state = Tokenizer.BEFORE_ATTRIBUTE_NAME; reconsume = true; continue stateloop; } } // FALLTHRU DON'T REORDER case SELF_CLOSING_START_TAG: c = read(); /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Set the self-closing * flag of the current tag token. Emit the current * tag token. */ if (html4) { err("The \u201C/>\u201D syntax on void elements is not allowed. (This is an HTML4-only error.)"); } state = emitCurrentTagToken(true); if (shouldSuspend) { break stateloop; } /* * Switch to the data state. */ continue stateloop; default: /* Anything else Parse error. */ err("A slash was not immediate followed by \u201C>\u201D."); /* * Reconsume the character in the before attribute * name state. */ state = Tokenizer.BEFORE_ATTRIBUTE_NAME; reconsume = true; continue stateloop; } // XXX reorder point case ATTRIBUTE_VALUE_UNQUOTED: for (;;) { if (reconsume) { reconsume = false; } else { c = read(); } /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED * (LF) U+000C FORM FEED (FF) U+0020 SPACE * Switch to the before attribute name state. */ addAttributeWithValue(); state = Tokenizer.BEFORE_ATTRIBUTE_NAME; continue stateloop; case '&': /* * U+0026 AMPERSAND (&) Switch to the character * reference in attribute value state, with no + * additional allowed character. */ detachLongStrBuf(); clearStrBufAndAppendCurrentC(c); additional = '\u0000'; rememberAmpersandLocation(); returnState = state; state = Tokenizer.CONSUME_CHARACTER_REFERENCE; continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Emit the current * tag token. */ addAttributeWithValue(); state = emitCurrentTagToken(false); if (shouldSuspend) { break stateloop; } /* * Switch to the data state. */ continue stateloop; case '<': case '\"': case '\'': case '=': if (c == '<') { warn("\u201C<\u201D in an unquoted attribute value. This does not end the tag. Probable cause: Missing \u201C>\u201D immediately before."); } else { /* * U+0022 QUOTATION MARK (") U+0027 * APOSTROPHE (') U+003D EQUALS SIGN (=) * Parse error. */ err("\u201C" + c + "\u201D in an unquoted attribute value. Probable causes: Attributes running together or a URL query string in an unquoted attribute value."); /* * Treat it as per the "anything else" entry * below. */ } // fall through default: if (html4 && !((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '.' || c == '-' || c == '_' || c == ':')) { err("Non-name character in an unquoted attribute value. (This is an HTML4-only error.)"); } /* * Anything else Append the current input * character to the current attribute's value. */ appendLongStrBuf(c); /* * Stay in the attribute value (unquoted) state. */ continue; } } // XXX reorder point case AFTER_ATTRIBUTE_NAME: for (;;) { c = read(); /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED * (LF) U+000C FORM FEED (FF) U+0020 SPACE Stay * in the after attribute name state. */ continue; case '/': /* * U+002F SOLIDUS (/) Switch to the self-closing * start tag state. */ addAttributeWithoutValue(); state = Tokenizer.SELF_CLOSING_START_TAG; continue stateloop; case '=': /* * U+003D EQUALS SIGN (=) Switch to the before * attribute value state. */ state = Tokenizer.BEFORE_ATTRIBUTE_VALUE; continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Emit the current * tag token. */ addAttributeWithoutValue(); state = emitCurrentTagToken(false); if (shouldSuspend) { break stateloop; } /* * Switch to the data state. */ continue stateloop; case '\"': case '\'': errQuoteInAttributeName(c); /* * Treat it as per the "anything else" entry * below. */ default: addAttributeWithoutValue(); /* * Anything else Start a new attribute in the * current tag token. */ if (c >= 'A' && c <= 'Z') { /* * U+0041 LATIN CAPITAL LETTER A through to * U+005A LATIN CAPITAL LETTER Z Set that * attribute's name to the lowercase version * of the current input character (add * 0x0020 to the character's code point) */ clearStrBufAndAppendForceWrite((char) (c + 0x20)); } else { /* * Set that attribute's name to the current * input character, */ clearStrBufAndAppendCurrentC(c); } /* * and its value to the empty string. */ // Will do later. /* * Switch to the attribute name state. */ state = Tokenizer.ATTRIBUTE_NAME; continue stateloop; } } // XXX reorder point case BOGUS_COMMENT: boguscommentloop: for (;;) { if (reconsume) { reconsume = false; } else { c = read(); } /* * (This can only happen if the content model flag is * set to the PCDATA state.) * * Consume every character up to and including the first * U+003E GREATER-THAN SIGN character (>) or the end of * the file (EOF), whichever comes first. Emit a comment * token whose data is the concatenation of all the * characters starting from and including the character * that caused the state machine to switch into the * bogus comment state, up to and including the * character immediately before the last consumed * character (i.e. up to the character just before the * U+003E or EOF character). (If the comment was started * by the end of the file (EOF), the token is empty.) * * Switch to the data state. * * If the end of the file was reached, reconsume the EOF * character. */ switch (c) { case '\u0000': break stateloop; case '>': emitComment(0); state = Tokenizer.DATA; continue stateloop; case '-': appendLongStrBuf(c); state = Tokenizer.BOGUS_COMMENT_HYPHEN; break boguscommentloop; default: appendLongStrBuf(c); continue; } } // FALLTHRU DON'T REORDER case BOGUS_COMMENT_HYPHEN: boguscommenthyphenloop: for (;;) { c = read(); switch (c) { case '\u0000': break stateloop; case '>': maybeAppendSpaceToBogusComment(); emitComment(0); state = Tokenizer.DATA; continue stateloop; case '-': appendSecondHyphenToBogusComment(); continue boguscommenthyphenloop; default: appendLongStrBuf(c); continue stateloop; } } // XXX reorder point case MARKUP_DECLARATION_OPEN: markupdeclarationopenloop: for (;;) { c = read(); /* * (This can only happen if the content model flag is * set to the PCDATA state.) * * If the next two characters are both U+002D * HYPHEN-MINUS (-) characters, consume those two * characters, create a comment token whose data is the * empty string, and switch to the comment start state. * * Otherwise, if the next seven characters are an ASCII * case-insensitive match for the word "DOCTYPE", then * consume those characters and switch to the DOCTYPE * state. * * Otherwise, if the insertion mode is "in foreign * content" and the current node is not an element in * the HTML namespace and the next seven characters are * an ASCII case-sensitive match for the string * "[CDATA[" (the five uppercase letters "CDATA" with a * U+005B LEFT SQUARE BRACKET character before and * after), then consume those characters and switch to * the CDATA section state (which is unrelated to the * content model flag's CDATA state). * * Otherwise, is is a parse error. Switch to the bogus * comment state. The next character that is consumed, * if any, is the first character that will be in the * comment. */ switch (c) { case '\u0000': break stateloop; case '-': clearLongStrBufAndAppendToComment(c); state = Tokenizer.MARKUP_DECLARATION_HYPHEN; break markupdeclarationopenloop; // continue stateloop; case 'd': case 'D': clearLongStrBufAndAppendToComment(c); index = 0; state = Tokenizer.MARKUP_DECLARATION_OCTYPE; continue stateloop; case '[': if (tokenHandler.inForeign()) { clearLongStrBufAndAppendToComment(c); index = 0; state = Tokenizer.CDATA_START; continue stateloop; } else { // fall through } default: err("Bogus comment."); clearLongStrBuf(); state = Tokenizer.BOGUS_COMMENT; reconsume = true; continue stateloop; } } // FALLTHRU DON'T REORDER case MARKUP_DECLARATION_HYPHEN: markupdeclarationhyphenloop: for (;;) { c = read(); switch (c) { case '\u0000': break stateloop; case '-': clearLongStrBufForNextState(); state = Tokenizer.COMMENT_START; break markupdeclarationhyphenloop; // continue stateloop; default: err("Bogus comment."); state = Tokenizer.BOGUS_COMMENT; reconsume = true; continue stateloop; } } // FALLTHRU DON'T REORDER case COMMENT_START: commentstartloop: for (;;) { c = read(); /* * Comment start state * * * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case '-': /* * U+002D HYPHEN-MINUS (-) Switch to the comment * start dash state. */ appendLongStrBuf(c); state = Tokenizer.COMMENT_START_DASH; continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Parse error. */ err("Premature end of comment. Use \u201C-->\u201D to end a comment properly."); /* Emit the comment token. */ emitComment(0); /* * Switch to the data state. */ state = Tokenizer.DATA; continue stateloop; default: /* * Anything else Append the input character to * the comment token's data. */ appendLongStrBuf(c); /* * Switch to the comment state. */ state = Tokenizer.COMMENT; break commentstartloop; // continue stateloop; } } // FALLTHRU DON'T REORDER case COMMENT: commentloop: for (;;) { c = read(); /* * Comment state Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case '-': /* * U+002D HYPHEN-MINUS (-) Switch to the comment * end dash state */ appendLongStrBuf(c); state = Tokenizer.COMMENT_END_DASH; break commentloop; // continue stateloop; default: /* * Anything else Append the input character to * the comment token's data. */ appendLongStrBuf(c); /* * Stay in the comment state. */ continue; } } // FALLTHRU DON'T REORDER case COMMENT_END_DASH: commentenddashloop: for (;;) { c = read(); /* * Comment end dash state Consume the next input * character: */ switch (c) { case '\u0000': break stateloop; case '-': /* * U+002D HYPHEN-MINUS (-) Switch to the comment * end state */ appendLongStrBuf(c); state = Tokenizer.COMMENT_END; break commentenddashloop; // continue stateloop; default: /* * Anything else Append a U+002D HYPHEN-MINUS * (-) character and the input character to the * comment token's data. */ appendLongStrBuf(c); /* * Switch to the comment state. */ state = Tokenizer.COMMENT; continue stateloop; } } // FALLTHRU DON'T REORDER case COMMENT_END: for (;;) { c = read(); /* * Comment end dash state Consume the next input * character: */ switch (c) { case '\u0000': break stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Emit the comment * token. */ emitComment(2); /* * Switch to the data state. */ state = Tokenizer.DATA; continue stateloop; case '-': /* U+002D HYPHEN-MINUS (-) Parse error. */ err("Consecutive hyphens did not terminate a comment. \u201C--\u201D is not permitted inside a comment, but e.g. \u201C- -\u201D is."); /* * Append a U+002D HYPHEN-MINUS (-) character to * the comment token's data. */ adjustDoubleHyphenAndAppendToLongStrBuf(c); /* * Stay in the comment end state. */ continue; default: /* * Anything else Parse error. */ err("Consecutive hyphens did not terminate a comment. \u201C--\u201D is not permitted inside a comment, but e.g. \u201C- -\u201D is."); /* * Append two U+002D HYPHEN-MINUS (-) characters * and the input character to the comment * token's data. */ adjustDoubleHyphenAndAppendToLongStrBuf(c); /* * Switch to the comment state. */ state = Tokenizer.COMMENT; continue stateloop; } } // XXX reorder point case COMMENT_START_DASH: c = read(); /* * Comment start dash state * * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case '-': /* * U+002D HYPHEN-MINUS (-) Switch to the comment end * state */ appendLongStrBuf(c); state = Tokenizer.COMMENT_END; continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Parse error. */ err("Premature end of comment. Use \u201C-->\u201D to end a comment properly."); /* Emit the comment token. */ emitComment(1); /* * Switch to the data state. */ state = Tokenizer.DATA; continue stateloop; default: /* * Anything else Append a U+002D HYPHEN-MINUS (-) * character and the input character to the comment * token's data. */ appendLongStrBuf(c); /* * Switch to the comment state. */ state = Tokenizer.COMMENT; continue stateloop; } // XXX reorder point case MARKUP_DECLARATION_OCTYPE: markupdeclarationdoctypeloop: for (;;) { c = read(); if (c == '\u0000') { break stateloop; } if (index < 6) { // OCTYPE.length char folded = c; if (c >= 'A' && c <= 'Z') { folded += 0x20; } if (folded == Tokenizer.OCTYPE[index]) { appendLongStrBuf(c); } else { err("Bogus comment."); state = Tokenizer.BOGUS_COMMENT; reconsume = true; continue stateloop; } index++; continue; } else { state = Tokenizer.DOCTYPE; reconsume = true; break markupdeclarationdoctypeloop; // continue stateloop; } } // FALLTHRU DON'T REORDER case DOCTYPE: doctypeloop: for (;;) { if (reconsume) { reconsume = false; } else { c = read(); } systemIdentifier = null; publicIdentifier = null; doctypeName = null; /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED * (LF) U+000C FORM FEED (FF) U+0020 SPACE * Switch to the before DOCTYPE name state. */ state = Tokenizer.BEFORE_DOCTYPE_NAME; break doctypeloop; // continue stateloop; default: /* * Anything else Parse error. */ err("Missing space before doctype name."); /* * Reconsume the current character in the before * DOCTYPE name state. */ state = Tokenizer.BEFORE_DOCTYPE_NAME; reconsume = true; break doctypeloop; // continue stateloop; } } // FALLTHRU DON'T REORDER case BEFORE_DOCTYPE_NAME: beforedoctypenameloop: for (;;) { if (reconsume) { reconsume = false; } else { c = read(); } /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED * (LF) U+000C FORM FEED (FF) U+0020 SPACE Stay * in the before DOCTYPE name state. */ continue; case '>': /* * U+003E GREATER-THAN SIGN (>) Parse error. */ err("Nameless doctype."); /* * Create a new DOCTYPE token. Set its * force-quirks flag to on. Emit the token. */ tokenHandler.doctype("", null, null, true); /* * Switch to the data state. */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; default: /* Anything else Create a new DOCTYPE token. */ /* * Set the token's name name to the current * input character. */ clearStrBufAndAppendCurrentC(c); /* * Switch to the DOCTYPE name state. */ state = Tokenizer.DOCTYPE_NAME; break beforedoctypenameloop; // continue stateloop; } } // FALLTHRU DON'T REORDER case DOCTYPE_NAME: doctypenameloop: for (;;) { c = read(); /* * First, consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED * (LF) U+000C FORM FEED (FF) U+0020 SPACE * Switch to the after DOCTYPE name state. */ doctypeName = strBufToString(); state = Tokenizer.AFTER_DOCTYPE_NAME; break doctypenameloop; // continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Emit the current * DOCTYPE token. */ tokenHandler.doctype(strBufToString(), null, null, false); /* * Switch to the data state. */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; default: /* * Anything else Append the current input * character to the current DOCTYPE token's * name. */ appendStrBuf(c); /* * Stay in the DOCTYPE name state. */ continue; } } // FALLTHRU DON'T REORDER case AFTER_DOCTYPE_NAME: afterdoctypenameloop: for (;;) { c = read(); /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED * (LF) U+000C FORM FEED (FF) U+0020 SPACE Stay * in the after DOCTYPE name state. */ continue; case '>': /* * U+003E GREATER-THAN SIGN (>) Emit the current * DOCTYPE token. */ tokenHandler.doctype(doctypeName, null, null, false); /* * Switch to the data state. */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; case 'p': case 'P': index = 0; state = Tokenizer.DOCTYPE_UBLIC; break afterdoctypenameloop; // continue stateloop; case 's': case 'S': index = 0; state = Tokenizer.DOCTYPE_YSTEM; continue stateloop; default: /* * Otherwise, this is the parse error. */ bogusDoctype(); /* * Set the DOCTYPE token's force-quirks flag to * on. */ // done by bogusDoctype(); /* * Switch to the bogus DOCTYPE state. */ state = Tokenizer.BOGUS_DOCTYPE; continue stateloop; } } // FALLTHRU DON'T REORDER case DOCTYPE_UBLIC: doctypeublicloop: for (;;) { c = read(); if (c == '\u0000') { break stateloop; } /* * If the next six characters are an ASCII * case-insensitive match for the word "PUBLIC", then * consume those characters and switch to the before * DOCTYPE public identifier state. */ if (index < 5) { // UBLIC.length char folded = c; if (c >= 'A' && c <= 'Z') { folded += 0x20; } if (folded != Tokenizer.UBLIC[index]) { bogusDoctype(); // forceQuirks = true; state = Tokenizer.BOGUS_DOCTYPE; reconsume = true; continue stateloop; } index++; continue; } else { state = Tokenizer.BEFORE_DOCTYPE_PUBLIC_IDENTIFIER; reconsume = true; break doctypeublicloop; // continue stateloop; } } // FALLTHRU DON'T REORDER case BEFORE_DOCTYPE_PUBLIC_IDENTIFIER: beforedoctypepublicidentifierloop: for (;;) { if (reconsume) { reconsume = false; } else { c = read(); } /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED * (LF) U+000C FORM FEED (FF) U+0020 SPACE Stay * in the before DOCTYPE public identifier * state. */ continue; case '"': /* * U+0022 QUOTATION MARK (") Set the DOCTYPE * token's public identifier to the empty string * (not missing), */ clearLongStrBufForNextState(); /* * then switch to the DOCTYPE public identifier * (double-quoted) state. */ state = Tokenizer.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED; break beforedoctypepublicidentifierloop; // continue stateloop; case '\'': /* * U+0027 APOSTROPHE (') Set the DOCTYPE token's * public identifier to the empty string (not * missing), */ clearLongStrBufForNextState(); /* * then switch to the DOCTYPE public identifier * (single-quoted) state. */ state = Tokenizer.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED; continue stateloop; case '>': /* U+003E GREATER-THAN SIGN (>) Parse error. */ err("Expected a public identifier but the doctype ended."); /* * Set the DOCTYPE token's force-quirks flag to * on. Emit that DOCTYPE token. */ tokenHandler.doctype(doctypeName, null, null, true); /* * Switch to the data state. */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; default: bogusDoctype(); /* * Set the DOCTYPE token's force-quirks flag to * on. */ // done by bogusDoctype(); /* * Switch to the bogus DOCTYPE state. */ state = Tokenizer.BOGUS_DOCTYPE; continue stateloop; } } // FALLTHRU DON'T REORDER case DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED: doctypepublicidentifierdoublequotedloop: for (;;) { c = read(); /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case '"': /* * U+0022 QUOTATION MARK (") Switch to the after * DOCTYPE public identifier state. */ publicIdentifier = longStrBufToString(); state = Tokenizer.AFTER_DOCTYPE_PUBLIC_IDENTIFIER; break doctypepublicidentifierdoublequotedloop; // continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Parse error. */ err("\u201C>\u201D in public identifier."); /* * Set the DOCTYPE token's force-quirks flag to * on. Emit that DOCTYPE token. */ tokenHandler.doctype(doctypeName, longStrBufToString(), null, true); /* * Switch to the data state. */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; default: /* * Anything else Append the current input * character to the current DOCTYPE token's * public identifier. */ appendLongStrBuf(c); /* * Stay in the DOCTYPE public identifier * (double-quoted) state. */ continue; } } // FALLTHRU DON'T REORDER case AFTER_DOCTYPE_PUBLIC_IDENTIFIER: afterdoctypepublicidentifierloop: for (;;) { c = read(); /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED * (LF) U+000C FORM FEED (FF) U+0020 SPACE Stay * in the after DOCTYPE public identifier state. */ continue; case '"': /* * U+0022 QUOTATION MARK (") Set the DOCTYPE * token's system identifier to the empty string * (not missing), */ clearLongStrBufForNextState(); /* * then switch to the DOCTYPE system identifier * (double-quoted) state. */ state = Tokenizer.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED; break afterdoctypepublicidentifierloop; // continue stateloop; case '\'': /* * U+0027 APOSTROPHE (') Set the DOCTYPE token's * system identifier to the empty string (not * missing), */ clearLongStrBufForNextState(); /* * then switch to the DOCTYPE system identifier * (single-quoted) state. */ state = Tokenizer.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED; continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Emit the current * DOCTYPE token. */ tokenHandler.doctype(doctypeName, publicIdentifier, null, false); /* * Switch to the data state. */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; default: bogusDoctype(); /* * Set the DOCTYPE token's force-quirks flag to * on. */ // done by bogusDoctype(); /* * Switch to the bogus DOCTYPE state. */ state = Tokenizer.BOGUS_DOCTYPE; continue stateloop; } } // FALLTHRU DON'T REORDER case DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED: doctypesystemidentifierdoublequotedloop: for (;;) { c = read(); /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case '"': /* * U+0022 QUOTATION MARK (") Switch to the after * DOCTYPE system identifier state. */ systemIdentifier = longStrBufToString(); state = Tokenizer.AFTER_DOCTYPE_SYSTEM_IDENTIFIER; continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Parse error. */ err("\u201C>\u201D in system identifier."); /* * Set the DOCTYPE token's force-quirks flag to * on. Emit that DOCTYPE token. */ tokenHandler.doctype(doctypeName, publicIdentifier, longStrBufToString(), true); /* * Switch to the data state. * */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; default: /* * Anything else Append the current input * character to the current DOCTYPE token's * system identifier. */ appendLongStrBuf(c); /* * Stay in the DOCTYPE system identifier * (double-quoted) state. */ continue; } } // FALLTHRU DON'T REORDER case AFTER_DOCTYPE_SYSTEM_IDENTIFIER: afterdoctypesystemidentifierloop: for (;;) { c = read(); /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED * (LF) U+000C FORM FEED (FF) U+0020 SPACE Stay * in the after DOCTYPE system identifier state. */ continue; case '>': /* * U+003E GREATER-THAN SIGN (>) Emit the current * DOCTYPE token. */ tokenHandler.doctype(doctypeName, publicIdentifier, systemIdentifier, false); /* * Switch to the data state. */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; default: /* * Switch to the bogus DOCTYPE state. (This does * not set the DOCTYPE token's force-quirks flag * to on.) */ bogusDoctypeWithoutQuirks(); state = Tokenizer.BOGUS_DOCTYPE; break afterdoctypesystemidentifierloop; // continue stateloop; } } // FALLTHRU DON'T REORDER case BOGUS_DOCTYPE: for (;;) { if (reconsume) { reconsume = false; } else { c = read(); } /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Emit that * DOCTYPE token. */ tokenHandler.doctype(doctypeName, publicIdentifier, systemIdentifier, forceQuirks); /* * Switch to the data state. */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; default: /* * Anything else Stay in the bogus DOCTYPE * state. */ continue; } } // XXX reorder point case DOCTYPE_YSTEM: doctypeystemloop: for (;;) { c = read(); if (c == '\u0000') { break stateloop; } /* * Otherwise, if the next six characters are an ASCII * case-insensitive match for the word "SYSTEM", then * consume those characters and switch to the before * DOCTYPE system identifier state. */ if (index < 5) { // YSTEM.length char folded = c; if (c >= 'A' && c <= 'Z') { folded += 0x20; } if (folded != Tokenizer.YSTEM[index]) { bogusDoctype(); state = Tokenizer.BOGUS_DOCTYPE; reconsume = true; continue stateloop; } index++; continue stateloop; } else { state = Tokenizer.BEFORE_DOCTYPE_SYSTEM_IDENTIFIER; reconsume = true; break doctypeystemloop; // continue stateloop; } } // FALLTHRU DON'T REORDER case BEFORE_DOCTYPE_SYSTEM_IDENTIFIER: beforedoctypesystemidentifierloop: for (;;) { if (reconsume) { reconsume = false; } else { c = read(); } /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED * (LF) U+000C FORM FEED (FF) U+0020 SPACE Stay * in the before DOCTYPE system identifier * state. */ continue; case '"': /* * U+0022 QUOTATION MARK (") Set the DOCTYPE * token's system identifier to the empty string * (not missing), */ clearLongStrBufForNextState(); /* * then switch to the DOCTYPE system identifier * (double-quoted) state. */ state = Tokenizer.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED; continue stateloop; case '\'': /* * U+0027 APOSTROPHE (') Set the DOCTYPE token's * system identifier to the empty string (not * missing), */ clearLongStrBufForNextState(); /* * then switch to the DOCTYPE system identifier * (single-quoted) state. */ state = Tokenizer.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED; break beforedoctypesystemidentifierloop; // continue stateloop; case '>': /* U+003E GREATER-THAN SIGN (>) Parse error. */ err("Expected a system identifier but the doctype ended."); /* * Set the DOCTYPE token's force-quirks flag to * on. Emit that DOCTYPE token. */ tokenHandler.doctype(doctypeName, null, null, true); /* * Switch to the data state. */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; default: bogusDoctype(); /* * Set the DOCTYPE token's force-quirks flag to * on. */ // done by bogusDoctype(); /* * Switch to the bogus DOCTYPE state. */ state = Tokenizer.BOGUS_DOCTYPE; continue stateloop; } } // FALLTHRU DON'T REORDER case DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED: for (;;) { c = read(); /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case '\'': /* * U+0027 APOSTROPHE (') Switch to the after * DOCTYPE system identifier state. */ systemIdentifier = longStrBufToString(); state = Tokenizer.AFTER_DOCTYPE_SYSTEM_IDENTIFIER; continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Parse error. */ err("\u201C>\u201D in system identifier."); /* * Set the DOCTYPE token's force-quirks flag to * on. Emit that DOCTYPE token. */ tokenHandler.doctype(doctypeName, publicIdentifier, longStrBufToString(), true); /* * Switch to the data state. * */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; default: /* * Anything else Append the current input * character to the current DOCTYPE token's * system identifier. */ appendLongStrBuf(c); /* * Stay in the DOCTYPE system identifier * (double-quoted) state. */ continue; } } // XXX reorder point case DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED: for (;;) { c = read(); /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case '\'': /* * U+0027 APOSTROPHE (') Switch to the after * DOCTYPE public identifier state. */ publicIdentifier = longStrBufToString(); state = Tokenizer.AFTER_DOCTYPE_PUBLIC_IDENTIFIER; continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Parse error. */ err("\u201C>\u201D in public identifier."); /* * Set the DOCTYPE token's force-quirks flag to * on. Emit that DOCTYPE token. */ tokenHandler.doctype(doctypeName, longStrBufToString(), null, true); /* * Switch to the data state. */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; default: /* * Anything else Append the current input * character to the current DOCTYPE token's * public identifier. */ appendLongStrBuf(c); /* * Stay in the DOCTYPE public identifier * (single-quoted) state. */ continue; } } // XXX reorder point case CDATA_START: for (;;) { c = read(); if (c == '\u0000') { break stateloop; } if (index < 6) { // CDATA_LSQB.length if (c == Tokenizer.CDATA_LSQB[index]) { appendLongStrBuf(c); } else { err("Bogus comment."); state = Tokenizer.BOGUS_COMMENT; reconsume = true; continue stateloop; } index++; continue; } else { cstart = pos; // start coalescing state = Tokenizer.CDATA_SECTION; reconsume = true; break; // FALL THROUGH continue stateloop; } } // WARNING FALLTHRU CASE TRANSITION: DON'T REORDER case CDATA_SECTION: cdataloop: for (;;) { if (reconsume) { reconsume = false; } else { c = read(); } switch (c) { case '\u0000': break stateloop; case ']': flushChars(); state = Tokenizer.CDATA_RSQB; break cdataloop; // FALL THROUGH default: continue; } } // WARNING FALLTHRU CASE TRANSITION: DON'T REORDER case CDATA_RSQB: cdatarsqb: for (;;) { c = read(); switch (c) { case '\u0000': break stateloop; case ']': state = Tokenizer.CDATA_RSQB_RSQB; break cdatarsqb; default: tokenHandler.characters(Tokenizer.RSQB_RSQB, 0, 1); cstart = pos; state = Tokenizer.CDATA_SECTION; reconsume = true; continue stateloop; } } // WARNING FALLTHRU CASE TRANSITION: DON'T REORDER case CDATA_RSQB_RSQB: c = read(); switch (c) { case '\u0000': break stateloop; case '>': cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; default: tokenHandler.characters(Tokenizer.RSQB_RSQB, 0, 2); cstart = pos; state = Tokenizer.CDATA_SECTION; reconsume = true; continue stateloop; } // XXX reorder point case ATTRIBUTE_VALUE_SINGLE_QUOTED: attributevaluesinglequotedloop: for (;;) { if (reconsume) { reconsume = false; } else { c = read(); } /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case '\'': /* * U+0027 APOSTROPHE (') Switch to the after * attribute value (quoted) state. */ addAttributeWithValue(); state = Tokenizer.AFTER_ATTRIBUTE_VALUE_QUOTED; continue stateloop; case '&': /* * U+0026 AMPERSAND (&) Switch to the character * reference in attribute value state, with the + * additional allowed character being U+0027 * APOSTROPHE ('). */ detachLongStrBuf(); clearStrBufAndAppendCurrentC(c); additional = '\''; rememberAmpersandLocation(); returnState = state; state = Tokenizer.CONSUME_CHARACTER_REFERENCE; break attributevaluesinglequotedloop; // continue stateloop; default: /* * Anything else Append the current input * character to the current attribute's value. */ appendLongStrBuf(c); /* * Stay in the attribute value (double-quoted) * state. */ continue; } } // FALLTHRU DON'T REORDER case CONSUME_CHARACTER_REFERENCE: c = read(); if (c == '\u0000') { break stateloop; } /* * Unlike the definition is the spec, this state does not * return a value and never requires the caller to * backtrack. This state takes care of emitting characters * or appending to the current attribute value. It also * takes care of that in the case when consuming the * character reference fails. */ /* * This section defines how to consume a character * reference. This definition is used when parsing character * references in text and in attributes. * * The behavior depends on the identity of the next * character (the one immediately after the U+0026 AMPERSAND * character): */ switch (c) { case ' ': case '\t': case '\n': case '\u000C': case '<': case '&': emitOrAppendStrBuf(returnState); cstart = pos; state = returnState; reconsume = true; continue stateloop; case '#': /* * U+0023 NUMBER SIGN (#) Consume the U+0023 NUMBER * SIGN. */ appendStrBuf('#'); state = Tokenizer.CONSUME_NCR; continue stateloop; default: if (c == additional) { emitOrAppendStrBuf(returnState); state = returnState; reconsume = true; continue stateloop; } entCol = -1; lo = 0; hi = (NamedCharacters.NAMES.length - 1); candidate = -1; strBufMark = 0; state = Tokenizer.CHARACTER_REFERENCE_LOOP; reconsume = true; // FALL THROUGH continue stateloop; } // WARNING FALLTHRU CASE TRANSITION: DON'T REORDER case CHARACTER_REFERENCE_LOOP: outer: for (;;) { if (reconsume) { reconsume = false; } else { c = read(); } if (c == '\u0000') { break stateloop; } entCol++; /* * Consume the maximum number of characters possible, * with the consumed characters matching one of the * identifiers in the first column of the named * character references table (in a case-sensitive * manner). */ hiloop: for (;;) { if (hi == -1) { break hiloop; } if (entCol == NamedCharacters.NAMES[hi].length) { break hiloop; } if (entCol > NamedCharacters.NAMES[hi].length) { break outer; } else if (c < NamedCharacters.NAMES[hi][entCol]) { hi--; } else { break hiloop; } } loloop: for (;;) { if (hi < lo) { break outer; } if (entCol == NamedCharacters.NAMES[lo].length) { candidate = lo; strBufMark = strBufLen; lo++; } else if (entCol > NamedCharacters.NAMES[lo].length) { break outer; } else if (c > NamedCharacters.NAMES[lo][entCol]) { lo++; } else { break loloop; } } if (hi < lo) { break outer; } appendStrBuf(c); continue; } // TODO warn about apos (IE) and TRADE (Opera) if (candidate == -1) { /* * If no match can be made, then this is a parse error. */ errNoNamedCharacterMatch(); emitOrAppendStrBuf(returnState); if ((returnState & (~1)) == 0) { cstart = pos; } state = returnState; reconsume = true; continue stateloop; } else { char[] candidateArr = NamedCharacters.NAMES[candidate]; if (candidateArr[candidateArr.length - 1] != ';') { /* * If the last character matched is not a U+003B * SEMICOLON (;), there is a parse error. */ if ((returnState & (~1)) != 0) { /* * If the entity is being consumed as part of an * attribute, and the last character matched is * not a U+003B SEMICOLON (;), */ char ch; if (strBufMark == strBufLen) { ch = c; } else { // if (strBufOffset != -1) { // ch = buf[strBufOffset + strBufMark]; // } else { ch = strBuf[strBufMark]; // } } if ((ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z')) { /* * and the next character is in the range * U+0030 DIGIT ZERO to U+0039 DIGIT NINE, * U+0041 LATIN CAPITAL LETTER A to U+005A * LATIN CAPITAL LETTER Z, or U+0061 LATIN * SMALL LETTER A to U+007A LATIN SMALL * LETTER Z, then, for historical reasons, * all the characters that were matched * after the U+0026 AMPERSAND (&) must be * unconsumed, and nothing is returned. */ errNotSemicolonMatchInAttribute(); appendStrBufToLongStrBuf(); state = returnState; reconsume = true; continue stateloop; } } errNotSemicolonTerminated(); } /* * Otherwise, return a character token for the character * corresponding to the entity name (as given by the * second column of the named character references * table). */ char[] val = NamedCharacters.VALUES[candidate]; emitOrAppend(val, returnState); // this is so complicated! if (strBufMark < strBufLen) { if (strBufOffset != -1) { if ((returnState & (~1)) != 0) { for (int i = strBufMark; i < strBufLen; i++) { appendLongStrBuf(buf[strBufOffset + i]); } } else { tokenHandler.characters(buf, strBufOffset + strBufMark, strBufLen - strBufMark); } } else { if ((returnState & (~1)) != 0) { for (int i = strBufMark; i < strBufLen; i++) { appendLongStrBuf(strBuf[i]); } } else { tokenHandler.characters(strBuf, strBufMark, strBufLen - strBufMark); } } } if ((returnState & (~1)) == 0) { cstart = pos; } state = returnState; reconsume = true; continue stateloop; /* * If the markup contains I'm &notit; I tell you, the * entity is parsed as "not", as in, I'm ¬it; I tell * you. But if the markup was I'm &notin; I tell you, * the entity would be parsed as "notin;", resulting in * I'm ∉ I tell you. */ } // XXX reorder point case CONSUME_NCR: c = read(); prevValue = -1; value = 0; seenDigits = false; /* * The behavior further depends on the character after the * U+0023 NUMBER SIGN: */ switch (c) { case '\u0000': break stateloop; case 'x': case 'X': /* * U+0078 LATIN SMALL LETTER X U+0058 LATIN CAPITAL * LETTER X Consume the X. * * Follow the steps below, but using the range of * characters U+0030 DIGIT ZERO through to U+0039 * DIGIT NINE, U+0061 LATIN SMALL LETTER A through * to U+0066 LATIN SMALL LETTER F, and U+0041 LATIN * CAPITAL LETTER A, through to U+0046 LATIN CAPITAL * LETTER F (in other words, 0-9, A-F, a-f). * * When it comes to interpreting the number, * interpret it as a hexadecimal number. */ appendStrBuf(c); state = Tokenizer.HEX_NCR_LOOP; continue stateloop; default: /* * Anything else Follow the steps below, but using * the range of characters U+0030 DIGIT ZERO through * to U+0039 DIGIT NINE (i.e. just 0-9). * * When it comes to interpreting the number, * interpret it as a decimal number. */ state = Tokenizer.DECIMAL_NRC_LOOP; reconsume = true; // FALL THROUGH continue stateloop; } // WARNING FALLTHRU CASE TRANSITION: DON'T REORDER case DECIMAL_NRC_LOOP: decimalloop: for (;;) { if (reconsume) { reconsume = false; } else { c = read(); } if (c == '\u0000') { break stateloop; } // Deal with overflow gracefully if (value < prevValue) { value = 0x110000; // Value above Unicode range but // within int // range } prevValue = value; /* * Consume as many characters as match the range of * characters given above. */ if (c >= '0' && c <= '9') { seenDigits = true; value *= 10; value += c - '0'; continue; } else if (c == ';') { if (seenDigits) { state = Tokenizer.HANDLE_NCR_VALUE; if ((returnState & (~1)) == 0) { cstart = pos + 1; } // FALL THROUGH continue stateloop; break decimalloop; } else { err("No digits after \u201C" + strBufToString() + "\u201D."); appendStrBuf(';'); emitOrAppendStrBuf(returnState); if ((returnState & (~1)) == 0) { cstart = pos + 1; } state = returnState; continue stateloop; } } else { /* * If no characters match the range, then don't * consume any characters (and unconsume the U+0023 * NUMBER SIGN character and, if appropriate, the X * character). This is a parse error; nothing is * returned. * * Otherwise, if the next character is a U+003B * SEMICOLON, consume that too. If it isn't, there * is a parse error. */ if (!seenDigits) { err("No digits after \u201C" + strBufToString() + "\u201D."); emitOrAppendStrBuf(returnState); if ((returnState & (~1)) == 0) { cstart = pos; } state = returnState; reconsume = true; continue stateloop; } else { err("Character reference was not terminated by a semicolon."); state = Tokenizer.HANDLE_NCR_VALUE; reconsume = true; if ((returnState & (~1)) == 0) { cstart = pos; } // FALL THROUGH continue stateloop; break decimalloop; } } } // WARNING FALLTHRU CASE TRANSITION: DON'T REORDER case HANDLE_NCR_VALUE: // WARNING previous state sets reconsume // XXX inline this case if the method size can take it handleNcrValue(returnState); state = returnState; continue stateloop; // XXX reorder point case HEX_NCR_LOOP: for (;;) { c = read(); if (c == '\u0000') { break stateloop; } // Deal with overflow gracefully if (value < prevValue) { value = 0x110000; // Value above Unicode range but // within int // range } prevValue = value; /* * Consume as many characters as match the range of * characters given above. */ if (c >= '0' && c <= '9') { seenDigits = true; value *= 16; value += c - '0'; continue; } else if (c >= 'A' && c <= 'F') { seenDigits = true; value *= 16; value += c - 'A' + 10; continue; } else if (c >= 'a' && c <= 'f') { seenDigits = true; value *= 16; value += c - 'a' + 10; continue; } else if (c == ';') { if (seenDigits) { state = Tokenizer.HANDLE_NCR_VALUE; cstart = pos + 1; continue stateloop; } else { err("No digits after \u201C" + strBufToString() + "\u201D."); appendStrBuf(';'); emitOrAppendStrBuf(returnState); if ((returnState & (~1)) == 0) { cstart = pos + 1; } state = returnState; continue stateloop; } } else { /* * If no characters match the range, then don't * consume any characters (and unconsume the U+0023 * NUMBER SIGN character and, if appropriate, the X * character). This is a parse error; nothing is * returned. * * Otherwise, if the next character is a U+003B * SEMICOLON, consume that too. If it isn't, there * is a parse error. */ if (!seenDigits) { err("No digits after \u201C" + strBufToString() + "\u201D."); emitOrAppendStrBuf(returnState); if ((returnState & (~1)) == 0) { cstart = pos; } state = returnState; reconsume = true; continue stateloop; } else { err("Character reference was not terminated by a semicolon."); if ((returnState & (~1)) == 0) { cstart = pos; } state = Tokenizer.HANDLE_NCR_VALUE; reconsume = true; continue stateloop; } } } // XXX reorder point case PLAINTEXT: plaintextloop: for (;;) { if (reconsume) { reconsume = false; } else { c = read(); } switch (c) { case '\u0000': break stateloop; default: /* * Anything else Emit the input character as a * character token. */ /* * Stay in the data state. */ continue; } } // XXX reorder point case CDATA: cdataloop: for (;;) { if (reconsume) { reconsume = false; } else { c = read(); } switch (c) { case '\u0000': break stateloop; case '<': /* * U+003C LESS-THAN SIGN (<) When the content * model flag is set to the PCDATA state: switch * to the tag open state. When the content model * flag is set to either the RCDATA state or the * CDATA state and the escape flag is false: * switch to the tag open state. Otherwise: * treat it as per the "anything else" entry * below. */ flushChars(); returnState = state; state = Tokenizer.TAG_OPEN_NON_PCDATA; break cdataloop; // FALL THRU continue // stateloop; default: /* * Anything else Emit the input character as a * character token. */ /* * Stay in the data state. */ continue; } } // WARNING FALLTHRU CASE TRANSITION: DON'T REORDER case TAG_OPEN_NON_PCDATA: tagopennonpcdataloop: for (;;) { c = read(); switch (c) { case '\u0000': break stateloop; case '!': tokenHandler.characters(Tokenizer.LT_GT, 0, 1); cstart = pos; state = Tokenizer.ESCAPE_EXCLAMATION; break tagopennonpcdataloop; // FALL THRU // continue // stateloop; case '/': /* * If the content model flag is set to the * RCDATA or CDATA states Consume the next input * character. */ if (contentModelElement != null) { /* * If it is a U+002F SOLIDUS (/) character, * switch to the close tag open state. */ index = 0; clearStrBufForNextState(); state = Tokenizer.CLOSE_TAG_OPEN_NOT_PCDATA; continue stateloop; } // else fall through default: /* * Otherwise, emit a U+003C LESS-THAN SIGN * character token */ tokenHandler.characters(Tokenizer.LT_GT, 0, 1); /* * and reconsume the current input character in * the data state. */ cstart = pos; state = returnState; reconsume = true; continue stateloop; } } // WARNING FALLTHRU CASE TRANSITION: DON'T REORDER case ESCAPE_EXCLAMATION: escapeexclamationloop: for (;;) { c = read(); switch (c) { case '\u0000': break stateloop; case '-': state = Tokenizer.ESCAPE_EXCLAMATION_HYPHEN; break escapeexclamationloop; // FALL THRU // continue // stateloop; default: state = returnState; reconsume = true; continue stateloop; } } // WARNING FALLTHRU CASE TRANSITION: DON'T REORDER case ESCAPE_EXCLAMATION_HYPHEN: escapeexclamationhyphenloop: for (;;) { c = read(); switch (c) { case '\u0000': break stateloop; case '-': state = Tokenizer.ESCAPE_HYPHEN_HYPHEN; break escapeexclamationhyphenloop; // continue stateloop; default: state = returnState; reconsume = true; continue stateloop; } } // WARNING FALLTHRU CASE TRANSITION: DON'T REORDER case ESCAPE_HYPHEN_HYPHEN: escapehyphenhyphenloop: for (;;) { c = read(); switch (c) { case '\u0000': break stateloop; case '-': continue; case '>': state = returnState; continue stateloop; default: state = Tokenizer.ESCAPE; break escapehyphenhyphenloop; // continue stateloop; } } // WARNING FALLTHRU CASE TRANSITION: DON'T REORDER case ESCAPE: escapeloop: for (;;) { c = read(); switch (c) { case '\u0000': break stateloop; case '-': state = Tokenizer.ESCAPE_HYPHEN; break escapeloop; // FALL THRU continue // stateloop; default: continue escapeloop; } } // WARNING FALLTHRU CASE TRANSITION: DON'T REORDER case ESCAPE_HYPHEN: escapehyphenloop: for (;;) { c = read(); switch (c) { case '\u0000': break stateloop; case '-': state = Tokenizer.ESCAPE_HYPHEN_HYPHEN; continue stateloop; default: state = Tokenizer.ESCAPE; continue stateloop; } } // XXX reorder point case CLOSE_TAG_OPEN_NOT_PCDATA: for (;;) { c = read(); if (c == '\u0000') { break stateloop; } // ASSERT! when entering this state, set index to 0 and // call clearStrBuf() assert (contentModelElement != null); /* * If the content model flag is set to the RCDATA or * CDATA states but no start tag token has ever been * emitted by this instance of the tokeniser (fragment * case), or, if the content model flag is set to the * RCDATA or CDATA states and the next few characters do * not match the tag name of the last start tag token * emitted (compared in an ASCII case insensitive * manner), or if they do but they are not immediately * followed by one of the following characters: + U+0009 * CHARACTER TABULATION + U+000A LINE FEED (LF) + + * U+000C FORM FEED (FF) + U+0020 SPACE + U+003E * GREATER-THAN SIGN (>) + U+002F SOLIDUS (/) + EOF * * ...then emit a U+003C LESS-THAN SIGN character token, * a U+002F SOLIDUS character token, and switch to the * data state to process the next input character. */ // Let's implement the above without lookahead. strBuf // holds // characters that need to be emitted if looking for an // end tag // fails. // Duplicating the relevant part of tag name state here // as well. if (index < contentModelElement.name.length()) { char e = contentModelElement.name.charAt(index); char folded = c; if (c >= 'A' && c <= 'Z') { folded += 0x20; } if (folded != e) { if (index > 0 || (folded >= 'a' && folded <= 'z')) { // [NOCPP[ if (html4) { if (ElementName.IFRAME != contentModelElement) { err((contentModelFlag == ContentModelFlag.CDATA ? "CDATA" : "RCDATA") + " element \u201C" + contentModelElement.name + "\u201D contained the string \u201C</\u201D, but it was not the start of the end tag. (HTML4-only error)"); } } else { // ]NOCPP] warn((contentModelFlag == ContentModelFlag.CDATA ? "CDATA" : "RCDATA") + " element \u201C" + contentModelElement.name + "\u201D contained the string \u201C</\u201D, but this did not close the element."); // [NOCPP[ } // ]NOCPP] } tokenHandler.characters(Tokenizer.LT_SOLIDUS, 0, 2); emitStrBuf(); cstart = pos; state = returnState; reconsume = true; continue stateloop; } appendStrBuf(c); index++; continue; } else { endTag = true; // XXX replace contentModelElement with different // type tagName = contentModelElement; switch (c) { case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE * FEED (LF) U+000C FORM FEED (FF) U+0020 * SPACE Switch to the before attribute name * state. */ state = Tokenizer.BEFORE_ATTRIBUTE_NAME; continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Emit the * current tag token. */ state = emitCurrentTagToken(false); if (shouldSuspend) { break stateloop; } /* * Switch to the data state. */ continue stateloop; case '/': /* * U+002F SOLIDUS (/) Parse error unless * this is a permitted slash. */ // never permitted here err("Stray \u201C/\u201D in end tag."); /* * Switch to the before attribute name * state. */ state = Tokenizer.BEFORE_ATTRIBUTE_NAME; continue stateloop; default: if (html4) { err((contentModelFlag == ContentModelFlag.CDATA ? "CDATA" : "RCDATA") + " element \u201C" + contentModelElement + "\u201D contained the string \u201C</\u201D, but it was not the start of the end tag. (HTML4-only error)"); } else { warn((contentModelFlag == ContentModelFlag.CDATA ? "CDATA" : "RCDATA") + " element \u201C" + contentModelElement + "\u201D contained the string \u201C</\u201D, but this did not close the element."); } tokenHandler.characters( Tokenizer.LT_SOLIDUS, 0, 2); emitStrBuf(); cstart = pos; // don't drop the character state = returnState; continue stateloop; } } } // XXX reorder point case CLOSE_TAG_OPEN_PCDATA: c = read(); if (c == '\u0000') { break stateloop; } /* * Otherwise, if the content model flag is set to the PCDATA * state, or if the next few characters do match that tag * name, consume the next input character: */ if (c >= 'A' && c <= 'Z') { /* * U+0041 LATIN CAPITAL LETTER A through to U+005A LATIN * CAPITAL LETTER Z Create a new end tag token, */ endTag = true; /* * set its tag name to the lowercase version of the * input character (add 0x0020 to the character's code * point), */ clearStrBufAndAppendForceWrite((char) (c + 0x20)); /* * then switch to the tag name state. (Don't emit the * token yet; further details will be filled in before * it is emitted.) */ state = Tokenizer.TAG_NAME; continue stateloop; } else if (c >= 'a' && c <= 'z') { /* * U+0061 LATIN SMALL LETTER A through to U+007A LATIN * SMALL LETTER Z Create a new end tag token, */ endTag = true; /* * set its tag name to the input character, */ clearStrBufAndAppendCurrentC(c); /* * then switch to the tag name state. (Don't emit the * token yet; further details will be filled in before * it is emitted.) */ state = Tokenizer.TAG_NAME; continue stateloop; } else if (c == '>') { /* U+003E GREATER-THAN SIGN (>) Parse error. */ err("Saw \u201C</>\u201D. Probable causes: Unescaped \u201C<\u201D (escape as \u201C&lt;\u201D) or mistyped end tag."); /* * Switch to the data state. */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; } else { /* Anything else Parse error. */ err("Garbage after \u201C</\u201D."); /* * Switch to the bogus comment state. */ clearLongStrBufAndAppendToComment(c); state = Tokenizer.BOGUS_COMMENT; continue stateloop; } // XXX reorder point case RCDATA: rcdataloop: for (;;) { if (reconsume) { reconsume = false; } else { c = read(); } switch (c) { case '\u0000': break stateloop; case '&': /* * U+0026 AMPERSAND (&) When the content model * flag is set to one of the PCDATA or RCDATA * states and the escape flag is false: switch * to the character reference data state. * Otherwise: treat it as per the "anything * else" entry below. */ flushChars(); clearStrBufAndAppendCurrentC(c); additional = '\u0000'; returnState = state; state = Tokenizer.CONSUME_CHARACTER_REFERENCE; continue stateloop; case '<': /* * U+003C LESS-THAN SIGN (<) When the content * model flag is set to the PCDATA state: switch * to the tag open state. When the content model * flag is set to either the RCDATA state or the * CDATA state and the escape flag is false: * switch to the tag open state. Otherwise: * treat it as per the "anything else" entry * below. */ flushChars(); returnState = state; state = Tokenizer.TAG_OPEN_NON_PCDATA; continue stateloop; default: /* * Anything else Emit the input character as a * character token. */ /* * Stay in the data state. */ continue; } } } } flushChars(); if (prev == '\r' && pos != end) { pos--; col--; } // Save locals stateSave = state; returnStateSave = returnState; } private void errNotSemicolonTerminated() throws SAXException { err("Named character reference was not terminated by a semicolon. Probable cause: \u201C&\u201D should have been escaped as \u201C&amp;\u201D."); } private void errNotSemicolonMatchInAttribute() throws SAXException { errNoNamedCharacterMatch(); } private void errNoNamedCharacterMatch() throws SAXException { if (errorHandler == null) { return; } SAXParseException spe = new SAXParseException("\u201C&\u201D should have been escaped as \u201C&amp;\u201D.", ampersandLocation); errorHandler.error(spe); } private void errQuoteBeforeAttributeName(char c) throws SAXException { err("Saw \u201C" + c + "\u201D when expecting an attribute name. Probable cause: \u201C=\u201D missing immediately before."); } private void errQuoteInAttributeName(char c) throws SAXException { err("Quote \u201C" + c + "\u201D in attribute name. Probable cause: Matching quote missing somewhere earlier."); } private void rememberAmpersandLocation() { ampersandLocation = new LocatorImpl(this); } private void bogusDoctype() throws SAXException { err("Bogus doctype."); forceQuirks = true; } private void bogusDoctypeWithoutQuirks() throws SAXException { err("Bogus doctype."); forceQuirks = false; } private void emitOrAppendStrBuf(int returnState) throws SAXException { if ((returnState & (~1)) != 0) { appendStrBufToLongStrBuf(); } else { emitStrBuf(); } } private void handleNcrValue(int returnState) throws SAXException { /* * If one or more characters match the range, then take them all and * interpret the string of characters as a number (either hexadecimal or * decimal as appropriate). */ if (value >= 0x80 && value <= 0x9f) { /* * If that number is one of the numbers in the first column of the * following table, then this is a parse error. */ err("A numeric character reference expanded to the C1 controls range."); /* * Find the row with that number in the first column, and return a * character token for the Unicode character given in the second * column of that row. */ char[] val = NamedCharacters.WINDOWS_1252[value - 0x80]; emitOrAppend(val, returnState); } else if (value == 0x0D) { err("A numeric character reference expanded to carriage return."); emitOrAppend(Tokenizer.LF, returnState); } else if (value == 0xC && contentSpacePolicy != XmlViolationPolicy.ALLOW) { if (contentSpacePolicy == XmlViolationPolicy.ALTER_INFOSET) { emitOrAppend(Tokenizer.SPACE, returnState); } else if (contentSpacePolicy == XmlViolationPolicy.FATAL) { fatal("A character reference expanded to a form feed which is not legal XML 1.0 white space."); } } else if ((value >= 0x0000 && value <= 0x0008) || (value == 0x000B) || (value >= 0x000E && value <= 0x001F) || value == 0x007F) { /* * OOtherwise, if the number is in the range 0x0000 to 0x0008, * U+000B, U+000E to 0x001F, 0x007F to 0x009F, 0xD800 to 0xDFFF , * 0xFDD0 to 0xFDDF, or is one of 0xFFFE, 0xFFFF, 0x1FFFE, 0x1FFFF, * 0x2FFFE, 0x2FFFF, 0x3FFFE, 0x3FFFF, 0x4FFFE, 0x4FFFF, 0x5FFFE, * 0x5FFFF, 0x6FFFE, 0x6FFFF, 0x7FFFE, 0x7FFFF, 0x8FFFE, 0x8FFFF, * 0x9FFFE, 0x9FFFF, 0xAFFFE, 0xAFFFF, 0xBFFFE, 0xBFFFF, 0xCFFFE, * 0xCFFFF, 0xDFFFE, 0xDFFFF, 0xEFFFE, 0xEFFFF, 0xFFFFE, 0xFFFFF, * 0x10FFFE, or 0x10FFFF, or is higher than 0x10FFFF, then this is a * parse error; return a character token for the U+FFFD REPLACEMENT * CHARACTER character instead. */ err("Character reference expands to a control character (" + toUPlusString((char) value) + ")."); emitOrAppend(Tokenizer.REPLACEMENT_CHARACTER, returnState); } else if ((value & 0xF800) == 0xD800) { err("Character reference expands to a surrogate."); emitOrAppend(Tokenizer.REPLACEMENT_CHARACTER, returnState); } else if (isNonCharacter(value)) { err("Character reference expands to a non-character."); emitOrAppend(Tokenizer.REPLACEMENT_CHARACTER, returnState); } else if (value <= 0xFFFF) { /* * Otherwise, return a character token for the Unicode character * whose code point is that number. */ char ch = (char) value; if (errorHandler != null && isPrivateUse(ch)) { warnAboutPrivateUseChar(); } bmpChar[0] = ch; emitOrAppend(bmpChar, returnState); } else if (value <= 0x10FFFF) { if (errorHandler != null && isAstralPrivateUse(value)) { warnAboutPrivateUseChar(); } astralChar[0] = (char) (Tokenizer.LEAD_OFFSET + (value >> 10)); astralChar[1] = (char) (0xDC00 + (value & 0x3FF)); emitOrAppend(astralChar, returnState); } else { err("Character reference outside the permissible Unicode range."); emitOrAppend(Tokenizer.REPLACEMENT_CHARACTER, returnState); } } public void eof() throws SAXException { int state = stateSave; int returnState = returnStateSave; eofloop: for (;;) { switch (state) { case TAG_OPEN_NON_PCDATA: /* * Otherwise, emit a U+003C LESS-THAN SIGN character token */ tokenHandler.characters(Tokenizer.LT_GT, 0, 1); /* * and reconsume the current input character in the data * state. */ break eofloop; case TAG_OPEN: /* * The behavior of this state depends on the content model * flag. */ /* * Anything else Parse error. */ err("End of file in the tag open state."); /* * Emit a U+003C LESS-THAN SIGN character token */ tokenHandler.characters(Tokenizer.LT_GT, 0, 1); /* * and reconsume the current input character in the data * state. */ break eofloop; case CLOSE_TAG_OPEN_NOT_PCDATA: break eofloop; case CLOSE_TAG_OPEN_PCDATA: /* EOF Parse error. */ err("Saw \u201C</\u201D immediately before end of file."); /* * Emit a U+003C LESS-THAN SIGN character token and a U+002F * SOLIDUS character token. */ tokenHandler.characters(Tokenizer.LT_SOLIDUS, 0, 2); /* * Reconsume the EOF character in the data state. */ break eofloop; case TAG_NAME: /* * EOF Parse error. */ err("End of file seen when looking for tag name"); /* * Emit the current tag token. */ tagName = strBufToElementNameString(); emitCurrentTagToken(false); /* * Reconsume the EOF character in the data state. */ break eofloop; case BEFORE_ATTRIBUTE_NAME: case AFTER_ATTRIBUTE_VALUE_QUOTED: case SELF_CLOSING_START_TAG: /* EOF Parse error. */ err("Saw end of file without the previous tag ending with \u201C>\u201D."); /* * Emit the current tag token. */ emitCurrentTagToken(false); /* * Reconsume the EOF character in the data state. */ break eofloop; case ATTRIBUTE_NAME: /* * EOF Parse error. */ err("End of file occurred in an attribute name."); /* * Emit the current tag token. */ attributeNameComplete(); addAttributeWithoutValue(); emitCurrentTagToken(false); /* * Reconsume the EOF character in the data state. */ break eofloop; case AFTER_ATTRIBUTE_NAME: case BEFORE_ATTRIBUTE_VALUE: /* EOF Parse error. */ err("Saw end of file without the previous tag ending with \u201C>\u201D."); /* * Emit the current tag token. */ addAttributeWithoutValue(); emitCurrentTagToken(false); /* * Reconsume the character in the data state. */ break eofloop; case ATTRIBUTE_VALUE_DOUBLE_QUOTED: case ATTRIBUTE_VALUE_SINGLE_QUOTED: case ATTRIBUTE_VALUE_UNQUOTED: /* EOF Parse error. */ err("End of file reached when inside an attribute value."); /* Emit the current tag token. */ addAttributeWithValue(); emitCurrentTagToken(false); /* * Reconsume the character in the data state. */ break eofloop; case BOGUS_COMMENT: emitComment(0); break eofloop; case BOGUS_COMMENT_HYPHEN: maybeAppendSpaceToBogusComment(); emitComment(0); break eofloop; case MARKUP_DECLARATION_OPEN: err("Bogus comment."); clearLongStrBuf(); emitComment(0); break eofloop; case MARKUP_DECLARATION_HYPHEN: err("Bogus comment."); emitComment(0); break eofloop; case MARKUP_DECLARATION_OCTYPE: err("Bogus comment."); emitComment(0); break eofloop; case COMMENT_START: case COMMENT: /* * EOF Parse error. */ err("End of file inside comment."); /* Emit the comment token. */ emitComment(0); /* * Reconsume the EOF character in the data state. */ break eofloop; case COMMENT_END: /* * EOF Parse error. */ err("End of file inside comment."); /* Emit the comment token. */ emitComment(2); /* * Reconsume the EOF character in the data state. */ break eofloop; case COMMENT_END_DASH: case COMMENT_START_DASH: /* * EOF Parse error. */ err("End of file inside comment."); /* Emit the comment token. */ emitComment(1); /* * Reconsume the EOF character in the data state. */ break eofloop; case DOCTYPE: case BEFORE_DOCTYPE_NAME: /* EOF Parse error. */ err("End of file inside doctype."); /* * Create a new DOCTYPE token. Set its force-quirks flag to * on. Emit the token. */ tokenHandler.doctype("", null, null, true); /* * Reconsume the EOF character in the data state. */ break eofloop; case DOCTYPE_NAME: /* EOF Parse error. */ err("End of file inside doctype."); /* * Set the DOCTYPE token's force-quirks flag to on. Emit * that DOCTYPE token. */ tokenHandler.doctype(strBufToString(), null, null, true); /* * Reconsume the EOF character in the data state. */ break eofloop; case DOCTYPE_UBLIC: case DOCTYPE_YSTEM: case AFTER_DOCTYPE_NAME: case BEFORE_DOCTYPE_PUBLIC_IDENTIFIER: /* EOF Parse error. */ err("End of file inside doctype."); /* * Set the DOCTYPE token's force-quirks flag to on. Emit * that DOCTYPE token. */ tokenHandler.doctype(doctypeName, null, null, true); /* * Reconsume the EOF character in the data state. */ break eofloop; case DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED: case DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED: /* EOF Parse error. */ err("End of file inside public identifier."); /* * Set the DOCTYPE token's force-quirks flag to on. Emit * that DOCTYPE token. */ tokenHandler.doctype(doctypeName, longStrBufToString(), null, true); /* * Reconsume the EOF character in the data state. */ break eofloop; case AFTER_DOCTYPE_PUBLIC_IDENTIFIER: case BEFORE_DOCTYPE_SYSTEM_IDENTIFIER: /* EOF Parse error. */ err("End of file inside doctype."); /* * Set the DOCTYPE token's force-quirks flag to on. Emit * that DOCTYPE token. */ tokenHandler.doctype(doctypeName, publicIdentifier, null, true); /* * Reconsume the EOF character in the data state. */ break eofloop; case DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED: case DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED: /* EOF Parse error. */ err("End of file inside system identifier."); /* * Set the DOCTYPE token's force-quirks flag to on. Emit * that DOCTYPE token. */ tokenHandler.doctype(doctypeName, publicIdentifier, longStrBufToString(), true); /* * Reconsume the EOF character in the data state. */ break eofloop; case AFTER_DOCTYPE_SYSTEM_IDENTIFIER: /* EOF Parse error. */ err("End of file inside doctype."); /* * Set the DOCTYPE token's force-quirks flag to on. Emit * that DOCTYPE token. */ tokenHandler.doctype(doctypeName, publicIdentifier, systemIdentifier, true); /* * Reconsume the EOF character in the data state. */ break eofloop; case BOGUS_DOCTYPE: /* * Emit that DOCTYPE token. */ tokenHandler.doctype(doctypeName, publicIdentifier, systemIdentifier, forceQuirks); /* * Reconsume the EOF character in the data state. */ break eofloop; case CONSUME_CHARACTER_REFERENCE: /* * Unlike the definition is the spec, this state does not * return a value and never requires the caller to * backtrack. This state takes care of emitting characters * or appending to the current attribute value. It also * takes care of that in the case when consuming the entity * fails. */ /* * This section defines how to consume an entity. This * definition is used when parsing entities in text and in * attributes. * * The behavior depends on the identity of the next * character (the one immediately after the U+0026 AMPERSAND * character): */ emitOrAppendStrBuf(returnState); state = returnState; continue; case CHARACTER_REFERENCE_LOOP: outer: for (;;) { char c = '\u0000'; entCol++; /* * Consume the maximum number of characters possible, * with the consumed characters matching one of the * identifiers in the first column of the named * character references table (in a case-sensitive * manner). */ hiloop: for (;;) { if (hi == -1) { break hiloop; } if (entCol == NamedCharacters.NAMES[hi].length) { break hiloop; } if (entCol > NamedCharacters.NAMES[hi].length) { break outer; } else if (c < NamedCharacters.NAMES[hi][entCol]) { hi--; } else { break hiloop; } } loloop: for (;;) { if (hi < lo) { break outer; } if (entCol == NamedCharacters.NAMES[lo].length) { candidate = lo; strBufMark = strBufLen; lo++; } else if (entCol > NamedCharacters.NAMES[lo].length) { break outer; } else if (c > NamedCharacters.NAMES[lo][entCol]) { lo++; } else { break loloop; } } if (hi < lo) { break outer; } continue; } // TODO warn about apos (IE) and TRADE (Opera) if (candidate == -1) { /* * If no match can be made, then this is a parse error. */ errNoNamedCharacterMatch(); emitOrAppendStrBuf(returnState); state = returnState; continue eofloop; } else { char[] candidateArr = NamedCharacters.NAMES[candidate]; if (candidateArr[candidateArr.length - 1] != ';') { /* * If the last character matched is not a U+003B * SEMICOLON (;), there is a parse error. */ if ((returnState & (~1)) != 0) { /* * If the entity is being consumed as part of an * attribute, and the last character matched is * not a U+003B SEMICOLON (;), */ char ch; if (strBufMark == strBufLen) { ch = '\u0000'; } else { ch = strBuf[strBufMark]; } if ((ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z')) { /* * and the next character is in the range * U+0030 DIGIT ZERO to U+0039 DIGIT NINE, * U+0041 LATIN CAPITAL LETTER A to U+005A * LATIN CAPITAL LETTER Z, or U+0061 LATIN * SMALL LETTER A to U+007A LATIN SMALL * LETTER Z, then, for historical reasons, * all the characters that were matched * after the U+0026 AMPERSAND (&) must be * unconsumed, and nothing is returned. */ errNotSemicolonMatchInAttribute(); appendStrBufToLongStrBuf(); state = returnState; continue eofloop; } } errNotSemicolonTerminated(); } /* * Otherwise, return a character token for the character * corresponding to the entity name (as given by the * second column of the named character references * table). */ char[] val = NamedCharacters.VALUES[candidate]; emitOrAppend(val, returnState); // this is so complicated! if (strBufMark < strBufLen) { if ((returnState & (~1)) != 0) { for (int i = strBufMark; i < strBufLen; i++) { appendLongStrBuf(strBuf[i]); } } else { tokenHandler.characters(strBuf, strBufMark, strBufLen - strBufMark); } } state = returnState; continue eofloop; /* * If the markup contains I'm &notit; I tell you, the * entity is parsed as "not", as in, I'm ¬it; I tell * you. But if the markup was I'm &notin; I tell you, * the entity would be parsed as "notin;", resulting in * I'm ∉ I tell you. */ } case CONSUME_NCR: case DECIMAL_NRC_LOOP: case HEX_NCR_LOOP: /* * If no characters match the range, then don't consume any * characters (and unconsume the U+0023 NUMBER SIGN * character and, if appropriate, the X character). This is * a parse error; nothing is returned. * * Otherwise, if the next character is a U+003B SEMICOLON, * consume that too. If it isn't, there is a parse error. */ if (!seenDigits) { err("No digits after \u201C" + strBufToString() + "\u201D."); emitOrAppendStrBuf(returnState); state = returnState; continue; } else { err("Character reference was not terminated by a semicolon."); // FALL THROUGH continue stateloop; } // WARNING previous state sets reconsume handleNcrValue(returnState); state = returnState; continue; case DATA: default: break eofloop; } } // case DATA: /* * EOF Emit an end-of-file token. */ tokenHandler.eof(); return; } private char read() throws SAXException { char c; pos++; if (pos == end) { return '\u0000'; } linePrev = line; colPrev = col; if (nextCharOnNewLine) { line++; col = 1; nextCharOnNewLine = false; } else { col++; } c = buf[pos]; // [NOCPP[ if (errorHandler == null && contentNonXmlCharPolicy == XmlViolationPolicy.ALLOW) { // ]NOCPP] switch (c) { case '\r': nextCharOnNewLine = true; buf[pos] = '\n'; prev = '\r'; return '\n'; case '\n': if (prev == '\r') { return '\u0000'; } nextCharOnNewLine = true; break; case '\u0000': /* * All U+0000 NULL characters in the input must be replaced * by U+FFFD REPLACEMENT CHARACTERs. Any occurrences of such * characters is a parse error. */ c = buf[pos] = '\uFFFD'; break; } // [NOCPP[ } else { if (!confident && !alreadyComplainedAboutNonAscii && c > '\u007F') { complainAboutNonAscii(); alreadyComplainedAboutNonAscii = true; } switch (c) { case '\r': nextCharOnNewLine = true; buf[pos] = '\n'; prev = '\r'; return '\n'; case '\n': if (prev == '\r') { return '\u0000'; } nextCharOnNewLine = true; break; case '\u0000': /* * All U+0000 NULL characters in the input must be replaced * by U+FFFD REPLACEMENT CHARACTERs. Any occurrences of such * characters is a parse error. */ err("Found U+0000 in the character stream."); c = buf[pos] = '\uFFFD'; break; case '\u000C': if (contentNonXmlCharPolicy == XmlViolationPolicy.FATAL) { fatal("This document is not mappable to XML 1.0 without data loss due to " + toUPlusString(c) + " which is not a legal XML 1.0 character."); } else { if (contentNonXmlCharPolicy == XmlViolationPolicy.ALTER_INFOSET) { c = buf[pos] = ' '; } warn("This document is not mappable to XML 1.0 without data loss due to " + toUPlusString(c) + " which is not a legal XML 1.0 character."); } break; default: if ((c & 0xFC00) == 0xDC00) { // Got a low surrogate. See if prev was high // surrogate if ((prev & 0xFC00) == 0xD800) { int intVal = (prev << 10) + c + Tokenizer.SURROGATE_OFFSET; if (isNonCharacter(intVal)) { err("Astral non-character."); } if (isAstralPrivateUse(intVal)) { warnAboutPrivateUseChar(); } } else { // XXX figure out what to do about lone high // surrogates err("Found low surrogate without high surrogate."); // c = buf[pos] = '\uFFFD'; } } else if ((c < ' ' || isNonCharacter(c)) && (c != '\t')) { switch (contentNonXmlCharPolicy) { case FATAL: fatal("Forbidden code point " + toUPlusString(c) + "."); break; case ALTER_INFOSET: c = buf[pos] = '\uFFFD'; // fall through case ALLOW: err("Forbidden code point " + toUPlusString(c) + "."); } } else if ((c >= '\u007F') && (c <= '\u009F') || (c >= '\uFDD0') && (c <= '\uFDDF')) { err("Forbidden code point " + toUPlusString(c) + "."); } else if (isPrivateUse(c)) { warnAboutPrivateUseChar(); } } } // ]NOCPP] prev = c; return c; } private void complainAboutNonAscii() throws SAXException { String encoding = null; if (encodingDeclarationHandler != null) { encoding = encodingDeclarationHandler.getCharacterEncoding(); } if (encoding == null) { err("The character encoding of the document was not explicit but the document contains non-ASCII."); } else { err("No explicit character encoding declaration has been seen yet (assumed \u201C" + encoding + "\u201D) but the document contains non-ASCII."); } } public void internalEncodingDeclaration(String internalCharset) throws SAXException { if (encodingDeclarationHandler != null) { encodingDeclarationHandler.internalEncodingDeclaration(internalCharset); } } /** * @param val * @throws SAXException */ private void emitOrAppend(char[] val, int returnState) throws SAXException { if ((returnState & (~1)) != 0) { appendLongStrBuf(val); } else { tokenHandler.characters(val, 0, val.length); } } public void end() throws SAXException { strBuf = null; longStrBuf = null; systemIdentifier = null; publicIdentifier = null; doctypeName = null; tagName = null; attributeName = null; tokenHandler.endTokenization(); if (attributes != null) { attributes.clear(); attributes.release(); } } public void requestSuspension() { shouldSuspend = true; } /** * Returns the alreadyComplainedAboutNonAscii. * * @return the alreadyComplainedAboutNonAscii */ public boolean isAlreadyComplainedAboutNonAscii() { return alreadyComplainedAboutNonAscii; } public void becomeConfident() { confident = true; } /** * Returns the nextCharOnNewLine. * * @return the nextCharOnNewLine */ public boolean isNextCharOnNewLine() { return nextCharOnNewLine; } public boolean isPrevCR() { return prev == '\r'; } /** * Returns the line. * * @return the line */ public int getLine() { return line; } /** * Returns the col. * * @return the col */ public int getCol() { return col; } }
1b1be4b49d7eeb757786926d65d91dc23490a1e5
ed76d002599caf2686d826783a17c157a7b80655
/common/src/main/java/com/github/dynamic/threadpool/common/config/ApplicationContextHolder.java
f12df7e4f19293c5cf2e05c4cb2884b956409ed1
[ "Apache-2.0" ]
permissive
Xusheng94/dynamic-threadpool
59ae1d4eddb7f83a7f30db07d42f78e8503587bf
28c6a9b627b514824f85530a46c98892b5ba539e
refs/heads/main
2023-09-02T23:43:20.765395
2021-10-31T14:07:49
2021-10-31T14:07:49
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,889
java
package com.github.dynamic.threadpool.common.config; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import java.lang.annotation.Annotation; import java.util.Map; /** * Application context holder. * * @author chen.ma * @date 2021/6/20 18:49 */ public class ApplicationContextHolder implements ApplicationContextAware { private static ApplicationContext CONTEXT; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { ApplicationContextHolder.CONTEXT = applicationContext; } /** * Get ioc container bean by type. * * @param clazz * @param <T> * @return */ public static <T> T getBean(Class<T> clazz) { return CONTEXT.getBean(clazz); } /** * Get ioc container bean by name and type. * * @param name * @param clazz * @param <T> * @return */ public static <T> T getBean(String name, Class<T> clazz) { return CONTEXT.getBean(name, clazz); } /** * Get a set of ioc container beans by type. * * @param clazz * @param <T> * @return */ public static <T> Map<String, T> getBeansOfType(Class<T> clazz) { return CONTEXT.getBeansOfType(clazz); } /** * Find whether the bean has annotations. * * @param beanName * @param annotationType * @param <A> * @return */ public static <A extends Annotation> A findAnnotationOnBean(String beanName, Class<A> annotationType) { return CONTEXT.findAnnotationOnBean(beanName, annotationType); } /** * Get ApplicationContext. * * @return */ public static ApplicationContext getInstance() { return CONTEXT; } }
1dbe483c4164e7e035acff1380ad17d94a84050d
a9938e101afa994c98e54ab4be5b7f9db1ecc6d5
/src/main/java/br/com/eicon/model/Cliente.java
53f76d2af268f0f85f0508f93e38ba7dd632f11f
[]
no_license
akiotiago/prova-eicon
5fd80eba7de7e3af0ae5e6e3b1beb19f4cf35ec8
72df50ecaa93d7d247af99518497de9a67f530b7
refs/heads/master
2022-12-08T03:21:37.686488
2021-02-18T22:00:36
2021-02-18T22:00:36
228,288,490
0
0
null
2022-11-16T01:19:42
2019-12-16T02:42:12
Java
UTF-8
Java
false
false
1,989
java
package br.com.eicon.model; import java.io.Serializable; import java.util.List; import java.util.Objects; import java.util.Optional; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.validation.constraints.Email; import javax.validation.constraints.NotBlank; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonManagedReference; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; @Entity @AllArgsConstructor @NoArgsConstructor @Getter @Setter @EqualsAndHashCode @Builder(toBuilder = true) @Table(name = "tb_cliente") public class Cliente implements Serializable { private static final long serialVersionUID = 9049686602408225632L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @NotBlank @Column(name = "nome_cliente") private String nomeCliente; // @CPF @Column(length = 14) private String cpf; @Email private String email; @JsonManagedReference(value = "pedido-cliente") @OneToMany(mappedBy = "cliente") private List<Pedido> listaDePedidos; @JsonIgnore public boolean isIdNotNull() { return Objects.nonNull(this.id); } @JsonIgnore public boolean isListaDePedidos() { return (this.listaDePedidos != null && !this.listaDePedidos.isEmpty()); } @JsonIgnore public Optional<Long> getIdOptional() { return Optional.ofNullable(this.id); } @JsonIgnore public Optional<String> getNomeClienteOptional() { return Optional.ofNullable(nomeCliente); } @JsonIgnore public Optional<String> getCpfOptional() { return Optional.ofNullable(cpf); } @JsonIgnore public Optional<String> getEmailOptional() { return Optional.ofNullable(email); } }
e07527e313435e7dc960fb049696a4ba552647e7
4e35f22c436ddba0229dac8e64b2141c9cc94d27
/src/com/adagio/java8/lesson02/ReusageDemo.java
2c3de431b60b68b0d75560ff3aa757f2212860a9
[]
no_license
poseidon-ocean/road
2a89333301f985e938f994add018ad43465e776d
b45a3c8ad0751ec61061979dd2a7ed7ae3e86f5e
refs/heads/master
2021-05-16T12:19:16.728007
2019-01-11T09:21:26
2019-01-11T09:21:26
105,232,119
0
0
null
null
null
null
UTF-8
Java
false
false
921
java
package com.adagio.java8.lesson02; import java.util.function.Supplier; import java.util.stream.Stream; /** * 复用数据流 * */ public class ReusageDemo { public static void main(String[] args) { // Java8的数据流不能被复用。一旦你调用了任何终止操作,数据流就关闭了 Stream<String> stream = Stream.of("d2", "a2", "b1", "b3", "c") .filter(s -> s.startsWith("a")); stream.anyMatch(s -> true); // ok // stream.noneMatch(s -> true); // exception //克服这个限制 // /每次对get()的调用都构造了一个新的数据流,我们将其保存来调用终止操作 Supplier<Stream<String>> streamSupplier = () -> Stream.of("d2", "a2", "b1", "b3", "c") .filter(s -> s.startsWith("a")); streamSupplier.get().anyMatch(s -> true); // ok streamSupplier.get().noneMatch(s -> true); // ok } }
cf7cc8d108a6ef054824f1e6aa9337836080e17e
04c0eea10d2e31e74b60f60c1cfd032d738b59e9
/src/main/java/com/tact/poec/todo/FakeAndBadTodoItemController.java
bd28dad29c5521a86ea1117850d95228b2dc6faa
[]
no_license
jponcy/poec_sept_rest_example
5b7f291fd28f86f656ba597e0c34784dc477ea90
0c48d112fa9ad5ed99488842279b9aa29e0561c8
refs/heads/master
2020-04-08T00:14:49.438779
2018-11-23T15:38:54
2018-11-23T15:38:54
158,843,701
0
0
null
null
null
null
UTF-8
Java
false
false
3,084
java
package com.tact.poec.todo; import java.util.List; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; /** * REST respect: * <ul> * <li>GET /resource => get resource list</li> * <li>POST /resource => create a new resource</li> * <li>GET /resource/PK => get the resource</li> * <li>PUT /resource/PK => update resource data</li> * <li>DELETE /resource/PK => remove the resource</li> * </ul> * * <p> * <b>NOTES:</b> * <ul> * <li>possibility to have a prefix before resource like /api/v2/resource</li> * <li>Others common verbs: OPTIONS (check CORS for example), HEAD (to know last * update date), ...</li> * </ul> * </p> */ @RestController public class FakeAndBadTodoItemController { @Autowired private FakeTodoItemRepository repository; // @RequestMapping(name = "todo", method = RequestMethod.GET) @GetMapping("todo") public List<TodoItem> getAll() { final List<TodoItem> result = this.repository.findAll(); // Specific business - standard response is 200 []. if (result.isEmpty()) { throw new MyNotFoundException(); } return result; } @PostMapping("todo") @ResponseStatus(HttpStatus.CREATED) public TodoItem create(@Valid @RequestBody final TodoItemUpdateDTO dto) { final TodoItem item = new TodoItem(dto.getLabel()); this.repository.save(item); return item; } // @DeleteMapping // No, due to not real deletion, except if we want declare is delete even if it is not. // Not RestFull, but common tips to add some action (for performance). @PutMapping("todo/{id:^\\d+$}/delete") @ResponseStatus(HttpStatus.NO_CONTENT) public void delete(@PathVariable final long id) { final TodoItem item = this.repository.findOne(id); item.setDeleted(true); this.repository.save(item); } /** * Rest defines the content for creation/update should be add as request content. * @param id * @param label */ @PutMapping("todo/{id:^\\d+$}") public void update(@RequestParam final long id, @RequestBody final TodoItemUpdateDTO dto) { final TodoItem item = this.repository.findOne(id); item.setLabel(dto.getLabel()); this.repository.save(item); } @PutMapping("todo/{id:^\\d+$}/done") public void done(@RequestParam final long id) { final TodoItem item = this.repository.findOne(id); item.setFinished(true); this.repository.save(item); } }
0d562d104bbe66df650332294c001b06a630f7d4
0144030fd822ff06d875e4ac2b1201c2cc04c77d
/IDE/src/main/java/org/jdesktop/swingx/calendar/AbstractDateSelectionModel.java
e7d3e75b16191085d103485f9be051ede9ecf91a
[ "MIT" ]
permissive
xiaolongWangDev/SikuliX1
56ecffe16f41aad888541328080210f2cb18474d
cad35cdc580ca12762f2410f279e06366c9e7cc2
refs/heads/master
2020-04-20T10:17:38.051534
2019-02-05T06:58:52
2019-02-05T06:58:52
168,786,983
0
0
MIT
2019-02-02T02:46:01
2019-02-02T02:46:00
null
UTF-8
Java
false
false
8,876
java
/* * Copyright (c) 2010-2018, sikuli.org, sikulix.com - MIT license */ package org.jdesktop.swingx.calendar; import java.util.Calendar; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.Locale; import java.util.SortedSet; import java.util.TimeZone; import java.util.TreeSet; import org.jdesktop.swingx.event.DateSelectionEvent; import org.jdesktop.swingx.event.DateSelectionListener; import org.jdesktop.swingx.event.EventListenerMap; import org.jdesktop.swingx.event.DateSelectionEvent.EventType; /** * Abstract base implementation of DateSelectionModel. Implements * notification, Calendar related properties and lower/upper bounds. * * @author Jeanette Winzenburg */ public abstract class AbstractDateSelectionModel implements DateSelectionModel { public static final SortedSet<Date> EMPTY_DATES = Collections.unmodifiableSortedSet(new TreeSet<Date>()); protected EventListenerMap listenerMap; protected boolean adjusting; protected Calendar calendar; protected Date upperBound; protected Date lowerBound; /** * the locale used by the calendar. <p> * NOTE: need to keep separately as a Calendar has no getter. */ protected Locale locale; /** * Instantiates a DateSelectionModel with default locale. */ public AbstractDateSelectionModel() { this(null); } /** * Instantiates a DateSelectionModel with the given locale. If the locale is * null, the Locale's default is used. * * PENDING JW: fall back to JComponent.getDefaultLocale instead? We use this * with components anyway? * * @param locale the Locale to use with this model, defaults to Locale.default() * if null. */ public AbstractDateSelectionModel(Locale locale) { this.listenerMap = new EventListenerMap(); setLocale(locale); } /** * {@inheritDoc} */ @Override public Calendar getCalendar() { return (Calendar) calendar.clone(); } /** * {@inheritDoc} */ @Override public int getFirstDayOfWeek() { return calendar.getFirstDayOfWeek(); } /** * {@inheritDoc} */ @Override public void setFirstDayOfWeek(final int firstDayOfWeek) { if (firstDayOfWeek == getFirstDayOfWeek()) return; calendar.setFirstDayOfWeek(firstDayOfWeek); fireValueChanged(EventType.CALENDAR_CHANGED); } /** * {@inheritDoc} */ @Override public int getMinimalDaysInFirstWeek() { return calendar.getMinimalDaysInFirstWeek(); } /** * {@inheritDoc} */ @Override public void setMinimalDaysInFirstWeek(int minimalDays) { if (minimalDays == getMinimalDaysInFirstWeek()) return; calendar.setMinimalDaysInFirstWeek(minimalDays); fireValueChanged(EventType.CALENDAR_CHANGED); } /** * {@inheritDoc} */ @Override public TimeZone getTimeZone() { return calendar.getTimeZone(); } /** * {@inheritDoc} */ @Override public void setTimeZone(TimeZone timeZone) { if (getTimeZone().equals(timeZone)) return; TimeZone oldTimeZone = getTimeZone(); calendar.setTimeZone(timeZone); adjustDatesToTimeZone(oldTimeZone); fireValueChanged(EventType.CALENDAR_CHANGED); } /** * Adjusts all stored dates to a new time zone. * This method is called after the change had been made. <p> * * This implementation resets all dates to null, clears everything. * Subclasses may override to really map to the new time zone. * * @param oldTimeZone the old time zone * */ protected void adjustDatesToTimeZone(TimeZone oldTimeZone) { clearSelection(); setLowerBound(null); setUpperBound(null); setUnselectableDates(EMPTY_DATES); } /** * {@inheritDoc} */ @Override public Locale getLocale() { return locale; } /** * {@inheritDoc} */ @Override public void setLocale(Locale locale) { if (locale == null) { locale = Locale.getDefault(); } if (locale.equals(getLocale())) return; this.locale = locale; if (calendar != null) { calendar = Calendar.getInstance(calendar.getTimeZone(), locale); } else { calendar = Calendar.getInstance(locale); } fireValueChanged(EventType.CALENDAR_CHANGED); } //------------------- utility methods /** * Returns the start of the day of the given date in this model's calendar. * NOTE: the calendar is changed by this operation. * * @param date the Date to get the start for. * @return the Date representing the start of the day of the input date. */ protected Date startOfDay(Date date) { return CalendarUtils.startOfDay(calendar, date); } /** * Returns the end of the day of the given date in this model's calendar. * NOTE: the calendar is changed by this operation. * * @param date the Date to get the start for. * @return the Date representing the end of the day of the input date. */ protected Date endOfDay(Date date) { return CalendarUtils.endOfDay(calendar, date); } /** * Returns a boolean indicating whether the given dates are on the same day in * the coordinates of the model's calendar. * * @param selected one of the dates to check, must not be null. * @param compare the other of the dates to check, must not be null. * @return true if both dates represent the same day in this model's calendar. */ protected boolean isSameDay(Date selected, Date compare) { return startOfDay(selected).equals(startOfDay(compare)); } //------------------- bounds /** * {@inheritDoc} */ @Override public Date getUpperBound() { return upperBound; } /** * {@inheritDoc} */ @Override public void setUpperBound(Date upperBound) { if (upperBound != null) { upperBound = getNormalizedDate(upperBound); } if (CalendarUtils.areEqual(upperBound, getUpperBound())) return; this.upperBound = upperBound; if (this.upperBound != null && !isSelectionEmpty()) { long justAboveUpperBoundMs = this.upperBound.getTime() + 1; removeSelectionInterval(new Date(justAboveUpperBoundMs), getLastSelectionDate()); } fireValueChanged(EventType.UPPER_BOUND_CHANGED); } /** * {@inheritDoc} */ @Override public Date getLowerBound() { return lowerBound; } /** * {@inheritDoc} */ @Override public void setLowerBound(Date lowerBound) { if (lowerBound != null) { lowerBound = getNormalizedDate(lowerBound); } if (CalendarUtils.areEqual(lowerBound, getLowerBound())) return; this.lowerBound = lowerBound; if (this.lowerBound != null && !isSelectionEmpty()) { // Remove anything below the lower bound long justBelowLowerBoundMs = this.lowerBound.getTime() - 1; removeSelectionInterval(getFirstSelectionDate(), new Date( justBelowLowerBoundMs)); } fireValueChanged(EventType.LOWER_BOUND_CHANGED); } /** * {@inheritDoc} */ @Override public boolean isAdjusting() { return adjusting; } /** * {@inheritDoc} */ @Override public void setAdjusting(boolean adjusting) { if (adjusting == isAdjusting()) return; this.adjusting = adjusting; fireValueChanged(adjusting ? EventType.ADJUSTING_STARTED : EventType.ADJUSTING_STOPPED); } //----------------- notification /** * {@inheritDoc} */ @Override public void addDateSelectionListener(DateSelectionListener l) { listenerMap.add(DateSelectionListener.class, l); } /** * {@inheritDoc} */ @Override public void removeDateSelectionListener(DateSelectionListener l) { listenerMap.remove(DateSelectionListener.class, l); } public List<DateSelectionListener> getDateSelectionListeners() { return listenerMap.getListeners(DateSelectionListener.class); } protected void fireValueChanged(DateSelectionEvent.EventType eventType) { List<DateSelectionListener> listeners = getDateSelectionListeners(); DateSelectionEvent e = null; for (DateSelectionListener listener : listeners) { if (e == null) { e = new DateSelectionEvent(this, eventType, isAdjusting()); } listener.valueChanged(e); } } }
3122a8af34578477bb09a9b38143938d847c360e
7fa9c6b0fa1d0726ae1cda0199716c811a1ea01b
/Crawler/data/WithUnauthenticatedMockUser.java
dfc55c57d2fb10ee3dde1c3e4eef9229b1432d95
[]
no_license
NayrozD/DD2476-Project
b0ca75799793d8ced8d4d3ba3c43c79bb84a72c0
94dfb3c0a470527b069e2e0fd9ee375787ee5532
refs/heads/master
2023-03-18T04:04:59.111664
2021-03-10T15:03:07
2021-03-10T15:03:07
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,124
java
2 https://raw.githubusercontent.com/Vondser/mmwms-antd/master/src/test/java/com/meimos/myapp/web/rest/WithUnauthenticatedMockUser.java package com.meimos.myapp.web.rest; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.test.context.support.WithSecurityContext; import org.springframework.security.test.context.support.WithSecurityContextFactory; @Target({ ElementType.METHOD, ElementType.TYPE }) @Retention(RetentionPolicy.RUNTIME) @WithSecurityContext(factory = WithUnauthenticatedMockUser.Factory.class) public @interface WithUnauthenticatedMockUser { class Factory implements WithSecurityContextFactory<WithUnauthenticatedMockUser> { @Override public SecurityContext createSecurityContext(WithUnauthenticatedMockUser annotation) { return SecurityContextHolder.createEmptyContext(); } } }
bdc6c76500d52f3cf844317677d9c780829de2ea
54e6529aa2ee0bb9ebbc0ff889d77f6882b6702b
/Mixtap_Piano_Roll-master/app/src/main/java/com/example/arturo/mixtap_piano_roll/Measure.java
d91a636e47d05631fc178afc671af9d22241f55a
[]
no_license
NMSU-UID/Mixtape
2b2006d8706995fe440d230e5a6e4f1691f87b6c
824a47ac42985b3780a7c05d8f6d28c031537493
refs/heads/master
2020-12-01T03:53:24.925525
2016-12-02T04:21:08
2016-12-02T04:56:10
67,736,948
0
0
null
2016-09-08T20:28:03
2016-09-08T20:14:20
null
UTF-8
Java
false
false
9,354
java
package com.example.arturo.mixtap_piano_roll; import android.content.Context; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Path; import android.util.AttributeSet; import android.util.Log; import android.view.MotionEvent; import android.view.View; /** * Created by Jose Ortiz. Modified on 11/30/2016 by Jose Ortiz */ /* Measure is a class that extends from View. It is responsible for making a View of a measure, Being able to calculate it's own measurements and draw itself. As of now, notes are drawn within this class. This class also holds a data structure defining the note head, and stems position within the measure. Measure Width: 360px Measure Height: 120px Note Interval on Y axis (of measure): 20px Note Interval on X axis (of measure): measureWidth/4 + padding */ public class Measure extends View { private Paint doodle= new Paint(); // paint object used to define attributes of a canvas private Path path = new Path(); // Path is used for drawing strokes (not used in real project) private Resources res = getResources(); // This is used to grab all resources from project. This includes drawables private Bitmap MeasureBitmap = BitmapFactory.decodeResource(res, R.drawable.measure); // This bitmap takes the Measure Drawable private Bitmap NoteBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.note_head); // This bitmap takes a Note Head Drawable private Bitmap LeftStemBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.stem_left); // This bitmap takes a left Note Stem Drawable private Bitmap RightStemBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.stem_right); // This bitmap takes a Right Note Stem Drawable private Bitmap QuaterRestBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.quarter_rest); // This bitmap takes a Right Note Stem Drawable private Bitmap SharpBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.sharp); // This bitmap takes a Right Note Stem Drawable private int MeasureBitmapWidth = MeasureBitmap.getWidth(); // This is used as a counter to know the total width of all measures as the measures increase private int MeasureBitmapHeight = MeasureBitmap.getHeight(); // This is the height of a single measure private int singleMeasureBitmapWidth = MeasureBitmap.getWidth(); // This is the width of a single measure private int currentPosition= 0; // currentPosition is used to keep track of what is the current measure the user is working with private int notes[]= {-1, -1, -1, -1, -1, -1, -1, -1}; // This is the main array of which the positions of each note is stored. This is initialized to -1 to represent no Note entered private boolean sharps[]= {false, false , false, false, false, false, false, false}; /* The following 3 methods are standard constructors for a View class */ public Measure(Context context) { super(context); init(null, 0); // init is used to initialize attributes } public Measure(Context context, AttributeSet attrs) { super(context, attrs); init(attrs, 0); } public Measure(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(attrs, defStyleAttr); } // init is used to initialize attributes private void init(AttributeSet attrs, int defStyleAttr) { doodle.setColor(Color.BLACK); doodle.setAntiAlias(true); doodle.setStyle(Paint.Style.STROKE); doodle.setStrokeWidth(2.0f); } // onMeasure is a method from the View Class that defines a views measurements We use this to make the View the exact size of a Measure. @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { //super.onMeasure(widthMeasureSpec,heightMeasureSpec); int desiredWidth = MeasureBitmapWidth; int desiredHeight = MeasureBitmapHeight; int widthMode = MeasureSpec.getMode(widthMeasureSpec); int widthSize = MeasureSpec.getSize(widthMeasureSpec); int heightMode = MeasureSpec.getMode(heightMeasureSpec); int heightSize = MeasureSpec.getSize(heightMeasureSpec); int width; int height; //Measure Width if (widthMode == MeasureSpec.EXACTLY) { //Must be this size width = widthSize; } else if (widthMode == MeasureSpec.AT_MOST) { //Can't be bigger than... width = Math.min(desiredWidth, widthSize); } else { //Be whatever you want width = desiredWidth; } //Measure Height if (heightMode == MeasureSpec.EXACTLY) { //Must be this size height = heightSize; } else if (heightMode == MeasureSpec.AT_MOST) { //Can't be bigger than... height = Math.min(desiredHeight, heightSize); } else { //Be whatever you want height = desiredHeight; } //MUST CALL THIS setMeasuredDimension(width, height); } // onDraw is a method from the View Class in which updates the view canvas @Override public void onDraw(Canvas canvas){ super.onDraw(canvas); canvas.drawPath(path, doodle); //This is the drawing tool, used for debugging only //This draws a single Measure canvas.drawBitmap(MeasureBitmap, currentPosition, 0, doodle); canvas.drawBitmap(MeasureBitmap, singleMeasureBitmapWidth, 0, doodle); addNotes(canvas, notes, sharps); //This is the main method that updates the Notes that are drawn on the View MeasureBitmapWidth += singleMeasureBitmapWidth; } //This is the main method that takes in a Canvas (to draw notes to) and an array that has note head/note stem position data public void addNotes(Canvas canvas, int notePosition[], boolean isSharp[]){ int j= singleMeasureBitmapWidth/4; // This is the space between each note int noteCounterPerMeasure=1; /* This loops throught the array and add the note to the appropriate position in the measure */ for(int i = 0; i < 8; i++) { /*if(noteCounterPerMeasure==4){ //MeasureBitmapWidth += singleMeasureBitmapWidth; //This is incrementing the Views width as needed //currentPosition+= singleMeasureBitmapWidth; canvas.drawBitmap(MeasureBitmap, singleMeasureBitmapWidth, 0, doodle); noteCounterPerMeasure=1; }*/ if(notePosition[i]<0) { // If the element contains negative numbers, this means that there is no note to be displayed canvas.drawBitmap(QuaterRestBitmap, (j * i) + (j / 2),0, doodle); // draws note stem continue; } else { noteCounterPerMeasure++; canvas.drawBitmap(NoteBitmap, (j * i) + (j / 2), notePosition[i], doodle); // This creates the Note Head if(isSharp[i]==true) canvas.drawBitmap(SharpBitmap, (j * i) + (j / 2) - NoteBitmap.getWidth(), notePosition[i] - 20, doodle); if(notePosition[i]>=120) // Position 120 is the A note, so if it is below the A note on the Measure, it draws a stem on the right side of the note head canvas.drawBitmap(RightStemBitmap, (j * i) + (j / 2),(notePosition[i] -(RightStemBitmap.getHeight())) + (NoteBitmap.getHeight()/2), doodle); // draws note stem else canvas.drawBitmap(LeftStemBitmap, (j * i) + (j / 2), notePosition[i] + (NoteBitmap.getWidth()/2), doodle); // if note head is above the B note, it draws a left note stem } } } /* Functin in progress. To add measure */ public void addMeasure(){ Canvas canvas = new Canvas(); canvas.drawBitmap(MeasureBitmap, currentPosition*singleMeasureBitmapWidth, 0, doodle); MeasureBitmapWidth = MeasureBitmapWidth + singleMeasureBitmapWidth; currentPosition++; } // this is a mutator function to change the note position array. This is structure that piano roll uses to change the notes. public void setNotes(int notePosition[], boolean isSharp[]){ for(int i= 0; i<notePosition.length; i++){ notes[i]= notePosition[i]; sharps[i] = isSharp[i]; } } /* ********************* FOR DEBUGGING PURPOSES ONLY ********************* This whole method is to track the position of path. then draws the line */ @Override public boolean onTouchEvent(MotionEvent motionEvent){ float x= motionEvent.getX(); float y= motionEvent.getY(); switch (motionEvent.getAction()){ case MotionEvent.ACTION_DOWN: path.moveTo(x,y); break; case MotionEvent.ACTION_UP: break; case MotionEvent.ACTION_MOVE: path.lineTo(x,y); break; } super.onTouchEvent(motionEvent); invalidate(); return true; } }
64e04f4a901345267404a8f8d4fae1ea94795727
736b5edc318f50713f0ecd433f2a162818ed432d
/src/net/Batalla2/Exercit.java
9dfe94e007a4559f52768f2d02760631535e79e5
[]
no_license
yoseef/Batalla
c1ba0817c8b2fd64cd4dfc267f80307f2dd9e990
757c3fb1a28a7c41b59a3b1ad192670faf3c0eac
refs/heads/master
2016-09-05T17:50:56.634350
2014-11-04T18:48:16
2014-11-04T18:48:16
null
0
0
null
null
null
null
UTF-8
Java
false
false
4,311
java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package net.Batalla2; import java.util.ArrayList; import java.util.Random; /** * * @author user */ public class Exercit { /** * Guarda tots el soldats. */ private final ArrayList<Soldat> exercit; /** * crea enters aleatoris. */ private final Random r; /** * necessitem calcluar la mida del camp per poder controlar els soldats. */ private final double canvasWidth; /** * indica si el soldat ha arribat el desti. */ private boolean hanArribat; /** * * @param midaCamp la mida del camp */ public Exercit(final double midaCamp) { exercit = new ArrayList<>(); r = new Random(); canvasWidth = midaCamp; hanArribat = true; } /** * * @param pos si volem un soldat especific apartir de la posicio * @return retorna el soldat de la posicio */ public final Soldat getObtenirSoldat(final int pos) { return exercit.get(pos); } /** * * @return la array amb tots els soldats. */ public final ArrayList<Soldat> getSoldats() { return exercit; } /** * * @param nouSoldat va afegint soldats a l'array */ public final void afegirSoldat(final Soldat nouSoldat) { exercit.add(nouSoldat); } /** * * @param numFiles fer la formacio apartir del numero de files */ public final void formarExercit(final int numFiles) { int[] files = new int[numFiles]; for (int i = 0; i < exercit.size(); i++) { int numAleat = r.nextInt(files.length); files[numAleat] += 1; } int count = 0; for (int i = 0; i < files.length; i++) { for (int j = 0; j < files[i]; j++) { if (count < exercit.size()) { double h = i * exercit.get(count).getHeight() + i * N15; double w; if (exercit.get(count).getbandol() > 0) { w = exercit.get(count).getWidth() * j; } else { double formEsque = canvasWidth - exercit.get(count).getWidth(); w = formEsque - (exercit.get(count).getWidth() * j); } exercit.get(count).formar(w, h); count++; } } } } /** * numero 15. */ private static final int N15 = 15; /** * * @return false si tots els soldats encara es poden moure i true si jan han * arribat i no poden moure. */ public final boolean atacar() { double desti; int totalMoguts = 0; for (int i = 0; i < exercit.size(); i++) { if (exercit.get(i).getbandol() > 0) { //dreta desti = canvasWidth - exercit.get(i).getWidth(); } else { //esquerra desti = 0; } totalMoguts += exercit.get(i).moure(desti); if (totalMoguts == 0) { hanArribat = true; } else { hanArribat = false; } } return hanArribat; } /** * * @param exOponent el seguent exercit amb el que es compara si han * xucat */ public final void comprovarMorts(final Exercit exOponent) { for (int i = 0; i < exercit.size(); i++) { for (int j = 0; j < exOponent.getSoldats().size(); j++) { if (exercit.get(i).intersecta(exOponent.getSoldats().get(j))) { exOponent.getObtenirSoldat(j).setImg("exp.png"); exOponent.getObtenirSoldat(j).borrarImatge(); exOponent.getSoldats().remove(j); } } } } /** * canvia la direccio de al soldat perque vagi en sentit contrari. */ public final void changeDireccio() { for (Soldat sldt : exercit) { int tmp = sldt.getbandol() * -1; sldt.setbandol(tmp); } } }
63c16be12261994815fad9a80a4abfa4dd2c564b
d1ecb935c32da8a2240c2eca6d8f934c0b233a82
/buruberi-core/src/main/java/is/hello/buruberi/bluetooth/errors/BondException.java
0dfbd180bf571874f8ac5ad7fe4ed69e5998c8ed
[ "Apache-2.0" ]
permissive
hello/android-buruberi
32cc4df10abb1ea7ad60649977a72f3f3a830083
40d8623830d68df3d8a510c59fcf107fddf61013
refs/heads/master
2021-01-11T10:05:40.929814
2016-03-03T00:48:42
2016-03-03T00:48:42
43,840,940
6
0
null
2016-03-03T00:48:43
2015-10-07T19:46:56
Java
UTF-8
Java
false
false
6,815
java
/* * Copyright 2015 Hello Inc. * Copyright (C) 2013 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 is.hello.buruberi.bluetooth.errors; import android.support.annotation.NonNull; import is.hello.buruberi.bluetooth.stacks.GattPeripheral; import is.hello.buruberi.bluetooth.stacks.OperationTimeout; import is.hello.buruberi.util.NonGuaranteed; /** * Indicates that the state of a peripheral bond could not be altered by Buruberi. */ public class BondException extends BuruberiException { /** * The reason for the bond alteration's failure. * <p> * This value may change between OS versions. */ public final int reason; public BondException(int reason) { super(getReasonString(reason)); this.reason = reason; } /** * @return {@code true} if {@link #REASON_REMOVED} is reported; {@code false} otherwise. * * @see #REASON_REMOVED for more info. */ @Override public boolean isInstabilityLikely() { return (reason == BondException.REASON_REMOVED); } //region Bonding Errors /** * The reason for a bond state change to have occurred. * <p> * This extra is not publicly exposed before Android Lollipop / API Level 21, * and is only partially public in API Level 21. See the SDK Android Lollipop * source for the BluetoothDevice class for more info. * * @see android.bluetooth.BluetoothDevice#ACTION_BOND_STATE_CHANGED */ @NonGuaranteed public static final String EXTRA_REASON = "android.bluetooth.device.extra.REASON"; /** * A bonding attempt failed for unknown reasons. Specific to Buruberi. */ public static final int REASON_UNKNOWN_FAILURE = -1; /** * A bonding attempt failed up front because the bond alteration APIs * changed between OS versions. Specific to Buruberi. * * @see GattPeripheral#removeBond(OperationTimeout) for more info. */ public static final int REASON_ANDROID_API_CHANGED = -2; /** * A bond alternation succeeded. */ @NonGuaranteed public static final int BOND_SUCCESS = 0; /** * A bond attempt failed because pins did not match, or remote device did * not respond to pin request in time */ @NonGuaranteed public static final int REASON_AUTH_FAILED = 1; /** * A bond attempt failed because the other side explicitly rejected * bonding */ @NonGuaranteed public static final int REASON_AUTH_REJECTED = 2; /** * A bond attempt failed because we canceled the bonding process */ @NonGuaranteed public static final int REASON_AUTH_CANCELED = 3; /** * A bond attempt failed because we could not contact the remote device */ @NonGuaranteed public static final int REASON_REMOTE_DEVICE_DOWN = 4; /** * A bond attempt failed because a discovery is in progress */ @NonGuaranteed public static final int REASON_DISCOVERY_IN_PROGRESS = 5; /** * A bond attempt failed because of authentication timeout */ @NonGuaranteed public static final int REASON_AUTH_TIMEOUT = 6; /** * A bond attempt failed because of repeated attempts */ @NonGuaranteed public static final int REASON_REPEATED_ATTEMPTS = 7; /** * A bond attempt failed because we received an Authentication Cancel * by remote end */ @NonGuaranteed public static final int REASON_REMOTE_AUTH_CANCELED = 8; /** * A bond attempt failed because the bond state of the peripheral is * different from what the phone expected. On some devices, encountering * this error will result in the bluetooth drivers breaking until restart. */ @NonGuaranteed public static final int REASON_REMOVED = 9; /** * Returns the corresponding constant name for a given {@code REASON_*} value. * * @see #REASON_UNKNOWN_FAILURE * @see #REASON_ANDROID_API_CHANGED * @see #BOND_SUCCESS * @see #REASON_AUTH_FAILED * @see #REASON_AUTH_REJECTED * @see #REASON_AUTH_CANCELED * @see #REASON_REMOTE_DEVICE_DOWN * @see #REASON_DISCOVERY_IN_PROGRESS * @see #REASON_AUTH_TIMEOUT * @see #REASON_REPEATED_ATTEMPTS * @see #REASON_REMOTE_AUTH_CANCELED * @see #REASON_REMOVED */ public static @NonNull String getReasonString(int reason) { switch (reason) { case BOND_SUCCESS: return "BOND_SUCCESS"; case REASON_AUTH_FAILED: return "REASON_AUTH_FAILED"; case REASON_AUTH_REJECTED: return "REASON_AUTH_REJECTED"; case REASON_AUTH_CANCELED: return "REASON_AUTH_CANCELED"; case REASON_REMOTE_DEVICE_DOWN: return "REASON_REMOTE_DEVICE_DOWN"; case REASON_DISCOVERY_IN_PROGRESS: return "REASON_DISCOVERY_IN_PROGRESS"; case REASON_AUTH_TIMEOUT: return "REASON_AUTH_TIMEOUT"; case REASON_REPEATED_ATTEMPTS: return "REASON_REPEATED_ATTEMPTS"; case REASON_REMOTE_AUTH_CANCELED: return "REASON_REMOTE_AUTH_CANCELED"; case REASON_REMOVED: return "REASON_REMOVED"; case REASON_ANDROID_API_CHANGED: return "REASON_ANDROID_API_CHANGED"; case REASON_UNKNOWN_FAILURE: default: return "REASON_UNKNOWN_FAILURE (" + reason + ")"; } } /** * Returns the corresponding constant name for a given {@code GattPeripheral#BOND_*} value. * * @see GattPeripheral#BOND_NONE * @see GattPeripheral#BOND_CHANGING * @see GattPeripheral#BOND_BONDED */ public static @NonNull String getBondStateString(int bondState) { switch (bondState) { case GattPeripheral.BOND_NONE: return "BOND_NONE"; case GattPeripheral.BOND_CHANGING: return "BOND_CHANGING"; case GattPeripheral.BOND_BONDED: return "BOND_BONDED"; default: return "UNKNOWN (" + bondState + ")"; } } //endregion }
96ea95c9eab45b47054a472b808e1ca4913dbdce
be8ecc5179de2d5b361079913f6b866bb679e161
/src/dto/dtoreply.java
4a39de8bafabb98819ace8168f23ea828fa20b41
[]
no_license
wolffly/test
887c8b36879d7aa87f364809e5be198a6592b33b
cca7d1b4804c88c649de29a92784e7603a5d43c0
refs/heads/master
2021-01-01T05:48:26.537039
2015-04-20T13:30:42
2015-04-20T13:30:42
34,261,116
0
0
null
null
null
null
UTF-8
Java
false
false
971
java
package dto; public class dtoreply { private int reply_id; private String user_name; private String reply_sign; private String replytime; private int user_id; private int post_id; public int getPost_id() { return post_id; } public void setPost_id(int postId) { post_id = postId; } public int getUser_id() { return user_id; } public void setUser_id(int userId) { user_id = userId; } public int getReply_id() { return reply_id; } public void setReply_id(int replyId) { reply_id = replyId; } public String getUser_name() { return user_name; } public void setUser_name(String userName) { user_name = userName; } public String getReply_sign() { return reply_sign; } public void setReply_sign(String replySign) { reply_sign = replySign; } public String getReplytime() { return replytime; } public void setReplytime(String replytime) { this.replytime = replytime; } }
[ "lf123123" ]
lf123123
ec92bd14a3cd4c3fadbe9c01104193f2d84ea8ec
bb450bef04f1fab24a03858343f3e8fd9c5061ee
/dependencies/JAVA_GAT/tests/src/examples20/LogicalFileExample.java
5d22552a89e78eda700e69c8eeccfe786a7765ee
[ "Apache-2.0" ]
permissive
bsc-wdc/compss
c02b1c6a611ed50d5f75716d35bd8201889ae9d8
5f7a31436d0e6f5acbeb66fa36ab8aad18dc4092
refs/heads/stable
2023-08-16T02:51:46.073185
2023-08-04T21:43:31
2023-08-04T21:43:31
123,949,037
39
21
Apache-2.0
2022-07-05T04:08:53
2018-03-05T16:44:51
Java
UTF-8
Java
false
false
3,882
java
package examples20; import java.io.IOException; import java.net.URISyntaxException; import org.gridlab.gat.GAT; import org.gridlab.gat.GATInvocationException; import org.gridlab.gat.GATObjectCreationException; import org.gridlab.gat.URI; import org.gridlab.gat.io.LogicalFile; public class LogicalFileExample { /** * This example shows the use of the LogicalFile object in JavaGAT * * This example requires three valid JavaGAT URIs. The first two URIs should * point to files which from the user's perspective are identical. The third * URI should point to a location where the logical file should be * replicated to. The replication will be done from the 'closest' file. * * @param args * a String array of size 3 with each element containing a * String representation of a valid URI. */ public static void main(String[] args) { if (args.length != 3) { System.out .println("\tUsage: bin/run_gat_app examples20.FileExample <location1> <location2> <location3> (where location is a valid JavaGAT URI)\n\n" + "\twhere:\n" + "\t\t<location1> <location2> point to the same file\n" + "\t\tthis example will replicate to <location3> from the closest\n"); System.exit(1); } try { new LogicalFileExample().start(new URI(args[0]), new URI(args[1]), new URI(args[2])); } catch (URISyntaxException e) { System.out.println(e); System.out .println("\tUsage: bin/run_gat_app examples20.FileExample <location1> <location2> <location3> (where location is a valid JavaGAT URI)\n\n" + "\twhere:\n" + "\t\t<location1> <location2> point to the same file\n" + "\t\tthis example will replicate to <location3> from the closest\n"); System.exit(1); } GAT.end(); } public void start(URI uri1, URI uri2, URI uri3) { LogicalFile file = null; try { file = GAT.createLogicalFile("myLogicalFile", LogicalFile.CREATE); } catch (GATObjectCreationException e) { System.err.println("Failed to create the logical file: " + e); return; } try { file.addURI(uri1); } catch (GATInvocationException e) { System.err.println("Failed to add uri: '" + uri1 + "' to logical file: " + e); return; } catch (IOException e) { System.err.println("Failed to add uri: '" + uri1 + "' to logical file: " + e); return; } try { file.addURI(uri2); } catch (GATInvocationException e) { System.err.println("Failed to add uri: '" + uri2 + "' to logical file: " + e); return; } catch (IOException e) { System.err.println("Failed to add uri: '" + uri2 + "' to logical file: " + e); return; } try { System.out.println("" + file.getClosestURI(uri3)); } catch (GATInvocationException e) { System.err.println("Failed to retrieve the closest uri for uri: '" + uri3 + "': " + e); return; } try { file.replicate(uri3); } catch (GATInvocationException e) { System.err.println("Failed to replicate to uri: '" + uri3 + "': " + e); return; } catch (IOException e) { System.err.println("Failed to replicate to uri: '" + uri3 + "': " + e); return; } } }
[ "cramonco@9ab3861e-6c05-4e1b-b5ef-99af60850597" ]
cramonco@9ab3861e-6c05-4e1b-b5ef-99af60850597
9fdecba700445f64575d45f415e3bac2220b8a1b
5b6566f3ebd88f1c4258b3c78fa2a33181d1ad2e
/src/test/java/com/example/demo/DemoApplicationTests.java
aac20df3ecf11f98197205aa0193d7e99bab271a
[]
no_license
amyxin/springbootdemo
aae6052527e61ff3e692c883c7159aa5cc35e832
be756be3d2f9c4e368e2db53be5761365499f64e
refs/heads/main
2023-03-06T16:46:41.867464
2021-02-19T09:14:28
2021-02-19T09:14:28
340,311,187
0
0
null
null
null
null
UTF-8
Java
false
false
277
java
package com.example.demo; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class DemoApplicationTests { @Test void contextLoads() { String test="test"; System.out.println(test); } }
58ce74193db15be596b23cf8d6c977eceb5886e2
0578f583e40499681668d3cf91a2d37a3f81fa2a
/ComputerBuilderFX/src/controller/CheckBuildController.java
f77ec238614b68a79e41f5addf8079474c29b0e7
[]
no_license
henrynguyen1/JavaFXAssign
665b6af5ed2e3c45c81b9364b375d3ab3e6e8e8c
cb0bb7665955e975d4cd7484fdd65d5365c842c1
refs/heads/master
2022-02-22T06:39:43.285315
2019-08-07T06:35:53
2019-08-07T06:35:53
200,978,603
0
0
null
null
null
null
UTF-8
Java
false
false
1,741
java
package controller; import au.edu.uts.ap.javafx.*; import javafx.scene.text.*; import javafx.scene.control.*; import javafx.stage.*; import javafx.beans.binding.*; import javafx.beans.property.*; import java.io.*; import java.text.*; import javafx.collections.*; import javafx.collections.transformation.*; import javafx.event.*; import javafx.fxml.FXML; import model.*; public class CheckBuildController extends Controller<Build>{ @FXML private Text buildPartsTxt; @FXML private Button okayBtn; public final Build getBuild() { return model; } @FXML private void initialize() { String buildMssg = ""; if (!getBuild().hasPartOfType("cpu")){ buildMssg += "The build is missing a CPU." + System.lineSeparator(); } if (!getBuild().hasPartOfType("motherboard")){ buildMssg += "The build is missing a motherboard." + System.lineSeparator(); } if (!getBuild().hasPartOfType("memory")){ buildMssg += "The build is missing RAM." + System.lineSeparator(); } if (!getBuild().hasPartOfType("case")){ buildMssg += "The build is missing a case." + System.lineSeparator(); } if (!getBuild().hasPartOfType("storage")){ buildMssg += "The build is missing storage." + System.lineSeparator(); } buildPartsTxt.textProperty().set(buildMssg); if (getBuild().isValid()){ buildPartsTxt.textProperty().set("The build is functional." + System.lineSeparator()); } } @FXML private void handleBuildOkay(ActionEvent event) throws Exception { stage.close(); } }
9c58bde83b22e9d8ef33fb8d983604cdf44c7f44
6015fbe95f706421892f65a0e1cfa504fb9a34ad
/src/main/java/opcode_/austinmod/advancements/CustomTrigger.java
7229e113760e9311a1b2a9883f04c3e0d61828e4
[]
no_license
nu-musketeers/austin-mod
37a214e970ceaa4586452972fc25190038690c98
50c958444f3756e072b05c99b38a6a992a5565a4
refs/heads/master
2020-07-06T14:56:22.337613
2019-08-19T00:01:53
2019-08-19T00:01:53
203,058,573
0
0
null
null
null
null
UTF-8
Java
false
false
7,413
java
/** Copyright (C) 2017 by jabelar This file is part of jabelar's Minecraft Forge modding examples; as such, you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. For a copy of the GNU General Public License see <http://www.gnu.org/licenses/>. */ package opcode_.austinmod.advancements; import java.util.ArrayList; import java.util.Map; import java.util.Set; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonObject; import net.minecraft.advancements.ICriterionTrigger; import net.minecraft.advancements.PlayerAdvancements; import net.minecraft.advancements.critereon.AbstractCriterionInstance; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.util.ResourceLocation; // TODO: Auto-generated Javadoc /** * This class is part of my simple custom advancement triggering tutorial. * See: http://jabelarminecraft.blogspot.com/p/minecraft-modding-custom-triggers-aka.html * * @author jabelar */ public class CustomTrigger implements ICriterionTrigger<CustomTrigger.Instance> { private final ResourceLocation RL; private final Map<PlayerAdvancements, CustomTrigger.Listeners> listeners = Maps.newHashMap(); /** * Instantiates a new custom trigger. * * @param parString the par string */ public CustomTrigger(String parString) { super(); RL = new ResourceLocation(parString); } /** * Instantiates a new custom trigger. * * @param parRL the par RL */ public CustomTrigger(ResourceLocation parRL) { super(); RL = parRL; } /* (non-Javadoc) * @see net.minecraft.advancements.ICriterionTrigger#getId() */ @Override public ResourceLocation getId() { return RL; } /* (non-Javadoc) * @see net.minecraft.advancements.ICriterionTrigger#addListener(net.minecraft.advancements.PlayerAdvancements, net.minecraft.advancements.ICriterionTrigger.Listener) */ @Override public void addListener(PlayerAdvancements playerAdvancementsIn, ICriterionTrigger.Listener<CustomTrigger.Instance> listener) { CustomTrigger.Listeners myCustomTrigger$listeners = listeners.get(playerAdvancementsIn); if (myCustomTrigger$listeners == null) { myCustomTrigger$listeners = new CustomTrigger.Listeners(playerAdvancementsIn); listeners.put(playerAdvancementsIn, myCustomTrigger$listeners); } myCustomTrigger$listeners.add(listener); } /* (non-Javadoc) * @see net.minecraft.advancements.ICriterionTrigger#removeListener(net.minecraft.advancements.PlayerAdvancements, net.minecraft.advancements.ICriterionTrigger.Listener) */ @Override public void removeListener(PlayerAdvancements playerAdvancementsIn, ICriterionTrigger.Listener<CustomTrigger.Instance> listener) { CustomTrigger.Listeners tameanimaltrigger$listeners = listeners.get(playerAdvancementsIn); if (tameanimaltrigger$listeners != null) { tameanimaltrigger$listeners.remove(listener); if (tameanimaltrigger$listeners.isEmpty()) { listeners.remove(playerAdvancementsIn); } } } /* (non-Javadoc) * @see net.minecraft.advancements.ICriterionTrigger#removeAllListeners(net.minecraft.advancements.PlayerAdvancements) */ @Override public void removeAllListeners(PlayerAdvancements playerAdvancementsIn) { listeners.remove(playerAdvancementsIn); } /** * Deserialize a ICriterionInstance of this trigger from the data in the JSON. * * @param json the json * @param context the context * @return the tame bird trigger. instance */ @Override public CustomTrigger.Instance deserializeInstance(JsonObject json, JsonDeserializationContext context) { return new CustomTrigger.Instance(getId()); } /** * Trigger. * * @param parPlayer the player */ public void trigger(EntityPlayerMP parPlayer) { CustomTrigger.Listeners tameanimaltrigger$listeners = listeners.get(parPlayer.getAdvancements()); if (tameanimaltrigger$listeners != null) { tameanimaltrigger$listeners.trigger(parPlayer); } } public static class Instance extends AbstractCriterionInstance { /** * Instantiates a new instance. * * @param parRL the par RL */ public Instance(ResourceLocation parRL) { super(parRL); } /** * Test. * * @return true, if successful */ public boolean test() { return true; } } static class Listeners { private final PlayerAdvancements playerAdvancements; private final Set<ICriterionTrigger.Listener<CustomTrigger.Instance>> listeners = Sets.newHashSet(); /** * Instantiates a new listeners. * * @param playerAdvancementsIn the player advancements in */ public Listeners(PlayerAdvancements playerAdvancementsIn) { playerAdvancements = playerAdvancementsIn; } /** * Checks if is empty. * * @return true, if is empty */ public boolean isEmpty() { return listeners.isEmpty(); } /** * Adds the listener. * * @param listener the listener */ public void add(ICriterionTrigger.Listener<CustomTrigger.Instance> listener) { listeners.add(listener); } /** * Removes the listener. * * @param listener the listener */ public void remove(ICriterionTrigger.Listener<CustomTrigger.Instance> listener) { listeners.remove(listener); } /** * Trigger. * * @param player the player */ public void trigger(EntityPlayerMP player) { ArrayList<ICriterionTrigger.Listener<CustomTrigger.Instance>> list = null; for (ICriterionTrigger.Listener<CustomTrigger.Instance> listener : listeners) { if (listener.getCriterionInstance().test()) { if (list == null) { list = Lists.newArrayList(); } list.add(listener); } } if (list != null) { for (ICriterionTrigger.Listener<CustomTrigger.Instance> listener1 : list) { listener1.grantCriterion(playerAdvancements); } } } } }
dc4ede67f734945ba4a0b41f562b93e1140c3ba1
0f886fd97e35218930f3076f187b193922820549
/src/test/java/com/baidu/statistics/login/svc/LoginTest.java
89fe3889e0be7dbd772e5727125e80ab8f7ff9c1
[]
no_license
EricGSX/BaiduTongjiClient
c8d609713d9d64eeeb25ffa029ba371521809788
68a4efdd770808d38a75f6f03ba3693d3e24a7f7
refs/heads/master
2021-01-15T22:18:42.659201
2015-11-04T02:16:47
2015-11-04T02:17:34
null
0
0
null
null
null
null
UTF-8
Java
false
false
878
java
package com.baidu.statistics.login.svc; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; import com.baidu.statistics.login.om.DoLoginResponse; public class LoginTest { private BaseLoginTest login; @Before public void loginInit() { login = new BaseLoginTest(); } @Test public void testPreLogin() throws Exception { Boolean ret = login.preLogin(); assertSame(ret, true); } @Test public void testDoLogin() throws Exception { if (login.preLogin()) { DoLoginResponse ret = login.doLogin(); assertNotNull(ret); } } @Test public void testDoLogout() throws Exception { if (!login.preLogin()) { return; } DoLoginResponse loginRetData = login.doLogin(); if (loginRetData == null) { return; } Boolean ret = login.doLogout(loginRetData.getUcid(), loginRetData.getSt()); assertSame(ret, true); } }
e5cea177ba2bb180a67b9dd633619186c5295d9d
5fd989728eabb7421e071b17fdc3ed741607545d
/src/main/java/com/restaurants/service/FileServiceImpl.java
bd0d7cf2afda7eefc13a1521143c5e8b44305bc1
[]
no_license
lfdel24/restaurantsapi
0533911d65c98a4d1f2636c68b40bf9d271fa258
0209270d17c905a5e455467b5829212bf48e91d8
refs/heads/main
2023-03-30T19:10:00.450887
2021-03-25T03:10:19
2021-03-25T03:10:19
348,446,802
0
0
null
null
null
null
UTF-8
Java
false
false
874
java
package com.restaurants.service; import java.io.File; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import org.springframework.core.io.Resource; import org.springframework.core.io.UrlResource; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; @Service public class FileServiceImpl implements IFileService { private final Path rootFolder = Paths.get("/home/leo/uploads"); @Override public void save(MultipartFile file) throws Exception { Files.copy(file.getInputStream(), this.rootFolder.resolve(file.getOriginalFilename())); } @Override public Resource load(String name) throws Exception { Path file = rootFolder.resolve(name); Resource resource = new UrlResource(file.toUri()); return resource; } }
bf9061ee787ce160c5a7ec597b71f5a5b0624343
93f59b248ed9369c6872c0d2ce16ae6491b88891
/src/main/java/com/imooc/service/ProductService.java
71ffc12367edae8da42f8ad158c55c02d98e9cf6
[]
no_license
qinqinma/sell
c9eec24e05a27e5a7dfaa92fca8982aca6d4dd6d
8ebf4a815908f471490a728f04564fa5e80926f5
refs/heads/master
2020-07-16T03:02:26.767749
2019-09-01T16:43:27
2019-09-01T16:43:27
205,704,749
1
0
null
null
null
null
UTF-8
Java
false
false
753
java
package com.imooc.service; import com.imooc.dataobject.ProductInfo; import com.imooc.dto.CartDTO; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import java.util.List; /** * @author MQQ * @title: ProductService * @projectName sell * @description: TODO * @date 2019/8/2917:51 */ public interface ProductService { ProductInfo findOne(String productId); /** * 查询所有在架商品列表 * @return */ List<ProductInfo> findUpAll(); Page<ProductInfo> findAll(Pageable pageable); ProductInfo save(ProductInfo productInfo); //加库存 void increaseStock(List<CartDTO> cartDTOList); //减库存 void decreaseStock(List<CartDTO> cartDTOList); }
d332e5639ed684bc45d83924ba3abac5d3d04912
c2d0c189087f3d9738b86503e853875595220931
/nav/src/main/java/com/bigzhao/andframe/nav/FragmentNav.java
4e766aba2545e046cb370337a0395682dd49cf17
[]
no_license
l741589/ZAndFrame
cc156a594ae70226f7234062e2f8994fcd18c5e6
1ff76cf53677fdf4727e0762890d7560dac8c5dc
refs/heads/master
2020-04-14T00:40:50.695894
2015-08-16T04:42:28
2015-08-16T04:42:28
37,644,877
1
0
null
null
null
null
UTF-8
Java
false
false
12,799
java
package com.bigzhao.andframe.nav; import android.app.Activity; import android.app.Fragment; import android.app.FragmentManager; import android.app.FragmentTransaction; import android.os.Build; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v4.app.FragmentActivity; import android.view.View; import java.io.FileDescriptor; import java.io.PrintWriter; /** * Created by Roy on 15-3-30. */ @SuppressWarnings("unused") public class FragmentNav{ private Nav nav; private Activity a; private FragmentManager fm; private android.support.v4.app.FragmentManager sfm; private FragmentTransaction ft; private android.support.v4.app.FragmentTransaction sft; private int containerViewId=R.id.fragment_container; private boolean fallback; private boolean doCompat(){ return fallback||Build.VERSION.SDK_INT<Nav.FRAGMENT_SUPPORT_VER; } FragmentNav(Nav nav,boolean fallback){ this.nav=nav; a=(Activity)nav.context; this.fallback=fallback; if (Build.VERSION.SDK_INT>=Nav.FRAGMENT_SUPPORT_VER) { fm = a.getFragmentManager(); } if (a instanceof FragmentActivity) { sfm = ((FragmentActivity) a).getSupportFragmentManager(); } } public android.support.v4.app.FragmentTransaction getFragmentTransactionS() { if (sft==null) sft=sfm.beginTransaction(); return sft; } public FragmentTransaction getFragmentTransaction() { if (ft==null) ft=fm.beginTransaction(); return ft; } public FragmentManager getFragmentManager() { return fm; } public android.support.v4.app.FragmentManager getFragmentManagerS() { return sfm; } public FragmentNav add(Fragment fragment) { getFragmentTransaction().add(containerViewId, fragment); return this; } public FragmentNav add(android.support.v4.app.Fragment fragment) { getFragmentTransactionS().add(containerViewId, fragment); return this; } public FragmentNav replace(Fragment fragment, String tag) { getFragmentTransaction().replace(containerViewId, fragment, tag); return this; } public FragmentNav replace(android.support.v4.app.Fragment fragment, String tag) { getFragmentTransactionS().replace(containerViewId, fragment, tag); return this; } public FragmentNav setCustomAnimations(int enter, int exit, int popEnter, int popExit) { if (doCompat()) getFragmentTransactionS().setCustomAnimations(enter, exit, popEnter, popExit); else getFragmentTransaction().setCustomAnimations(enter, exit, popEnter, popExit); return this; } public FragmentNav addToBackStack(String name) { if (doCompat()) getFragmentTransactionS().addToBackStack(name); else getFragmentTransaction().addToBackStack(name); return this; } public FragmentNav setBreadCrumbShortTitle(int res) { if (doCompat()) getFragmentTransactionS().setBreadCrumbShortTitle(res); else getFragmentTransaction().setBreadCrumbShortTitle(res); return this; } public FragmentNav replace(Fragment fragment) { getFragmentTransaction().replace(containerViewId, fragment); return this; } public FragmentNav replace(android.support.v4.app.Fragment fragment) { getFragmentTransactionS().replace(containerViewId, fragment); return this; } public FragmentNav hide(Fragment fragment) { getFragmentTransaction().hide(fragment); return this; } public FragmentNav hide(android.support.v4.app.Fragment fragment) { getFragmentTransactionS().hide(fragment); return this; } public FragmentNav disallowAddToBackStack() { if (doCompat()) getFragmentTransactionS().disallowAddToBackStack(); else getFragmentTransaction().disallowAddToBackStack(); return this; } public int commitAllowingStateLoss() { if (doCompat()) return getFragmentTransactionS().commitAllowingStateLoss(); return getFragmentTransaction().commitAllowingStateLoss(); } @SuppressWarnings("NewApi") public FragmentNav addSharedElement(View sharedElement, String name) { if (doCompat()) getFragmentTransactionS().addSharedElement(sharedElement, name); else getFragmentTransaction().addSharedElement(sharedElement, name); return this; } public FragmentNav show(Fragment fragment) { getFragmentTransaction().show(fragment); return this; } public FragmentNav show(android.support.v4.app.Fragment fragment) { getFragmentTransactionS().show(fragment); return this; } public FragmentNav setBreadCrumbTitle(int res) { if (doCompat()) getFragmentTransactionS().setBreadCrumbTitle(res); else getFragmentTransaction().setBreadCrumbTitle(res); return this; } public FragmentNav setTransition(int transit) { if (doCompat()) getFragmentTransactionS().setTransition(transit); else getFragmentTransaction().setTransition(transit); return this; } public boolean isAddToBackStackAllowed() { if (doCompat()) return getFragmentTransactionS().isAddToBackStackAllowed(); return getFragmentTransaction().isAddToBackStackAllowed(); } public FragmentNav add(Fragment fragment, String tag) { getFragmentTransaction().add(containerViewId, fragment, tag); return this; } public FragmentNav add(android.support.v4.app.Fragment fragment, String tag) { getFragmentTransactionS().add(containerViewId, fragment, tag); return this; } public FragmentNav setBreadCrumbShortTitle(CharSequence text) { if (doCompat()) getFragmentTransactionS().setBreadCrumbShortTitle(text); else getFragmentTransaction().setBreadCrumbShortTitle(text); return this; } public FragmentNav attach(Fragment fragment) { getFragmentTransaction().attach(fragment); return this; } public FragmentNav attach(android.support.v4.app.Fragment fragment) { getFragmentTransactionS().attach(fragment); return this; } public FragmentNav remove(Fragment fragment) { getFragmentTransaction().remove(fragment); return this; } public FragmentNav remove(android.support.v4.app.Fragment fragment) { getFragmentTransactionS().remove(fragment); return this; } public FragmentNav setCustomAnimations(int enter, int exit) { if (doCompat()) getFragmentTransactionS().setCustomAnimations(enter, exit); else getFragmentTransaction().setCustomAnimations(enter, exit); return this; } public FragmentNav setTransitionStyle(int styleRes) { if (doCompat()) getFragmentTransactionS().setTransitionStyle(styleRes); else getFragmentTransaction().setTransitionStyle(styleRes); return this; } public FragmentNav detach(Fragment fragment) { getFragmentTransaction().detach(fragment); return this; } public FragmentNav detach(android.support.v4.app.Fragment fragment) { getFragmentTransactionS().detach(fragment); return this; } public FragmentNav setBreadCrumbTitle(CharSequence text) { if (doCompat()) getFragmentTransactionS().setBreadCrumbTitle(text); else getFragmentTransaction().setBreadCrumbTitle(text); return this; } public Nav commit() { if (doCompat()) getFragmentTransactionS().commit(); else getFragmentTransaction().commit(); return nav; } //////////////////////////////////////////////////////////////////////////////////// public FragmentTransaction beginTransaction() { return getFragmentTransaction(); } public android.support.v4.app.FragmentTransaction beginTransactionS() { return getFragmentTransactionS(); } public void removeOnBackStackChangedListener(FragmentManager.OnBackStackChangedListener listener) { getFragmentManager().removeOnBackStackChangedListener(listener); } public void removeOnBackStackChangedListener(android.support.v4.app.FragmentManager.OnBackStackChangedListener listener) { getFragmentManagerS().removeOnBackStackChangedListener(listener); } public static void enableDebugLogging(boolean enabled) { FragmentManager.enableDebugLogging(enabled); } public boolean popBackStackImmediate(String name, int flags) { if (doCompat()) return getFragmentManagerS().popBackStackImmediate(name, flags); else return getFragmentManager().popBackStackImmediate(name, flags); } public void addOnBackStackChangedListener(FragmentManager.OnBackStackChangedListener listener) { getFragmentManager().addOnBackStackChangedListener(listener); } public void addOnBackStackChangedListener(android.support.v4.app.FragmentManager.OnBackStackChangedListener listener) { getFragmentManagerS().addOnBackStackChangedListener(listener); } public void putFragment(Bundle bundle, String key, Fragment fragment) { getFragmentManager().putFragment(bundle, key, fragment); } public void putFragment(Bundle bundle, String key, android.support.v4.app.Fragment fragment) { getFragmentManagerS().putFragment(bundle, key, fragment); } public void popBackStack(String name, int flags) { if (doCompat()) getFragmentManagerS().popBackStack(name, flags); else getFragmentManager().popBackStack(name, flags); } public boolean popBackStackImmediate(int id, int flags) { if (doCompat()) return getFragmentManagerS().popBackStackImmediate(id, flags); else return getFragmentManager().popBackStackImmediate(id, flags); } public void popBackStack() { if (doCompat()) getFragmentManagerS().popBackStack(); else getFragmentManager().popBackStack(); } public Fragment findFragmentById(int id) { return getFragmentManager().findFragmentById(id); } public android.support.v4.app.Fragment findFragmentByIdS(int id) { return getFragmentManagerS().findFragmentById(id); } public int getBackStackEntryCount() { if (doCompat()) return getFragmentManagerS().getBackStackEntryCount(); else return getFragmentManager().getBackStackEntryCount(); } public FragmentManager.BackStackEntry getBackStackEntryAt(int index) { return getFragmentManager().getBackStackEntryAt(index); } public android.support.v4.app.FragmentManager.BackStackEntry getBackStackEntryAtS(int index) { return getFragmentManagerS().getBackStackEntryAt(index); } public void invalidateOptionsMenu() { if (doCompat())a.invalidateOptionsMenu(); else getFragmentManager().invalidateOptionsMenu(); } public boolean executePendingTransactions() { if (doCompat()) return getFragmentManagerS().executePendingTransactions(); else return getFragmentManager().executePendingTransactions(); } public boolean popBackStackImmediate() { if (doCompat()) return getFragmentManagerS().popBackStackImmediate(); else return getFragmentManager().popBackStackImmediate(); } @SuppressWarnings("NewApi") public boolean isDestroyed() { if (doCompat()) return getFragmentManagerS().isDestroyed(); else return getFragmentManager().isDestroyed(); } public Fragment.SavedState saveFragmentInstanceState(Fragment f) { return getFragmentManager().saveFragmentInstanceState(f); } public android.support.v4.app.Fragment.SavedState saveFragmentInstanceState(android.support.v4.app.Fragment f) { return getFragmentManagerS().saveFragmentInstanceState(f); } public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) { if (doCompat()) getFragmentManagerS().dump(prefix, fd, writer, args); else getFragmentManager().dump(prefix, fd, writer, args); } public void popBackStack(int id, int flags) { if (doCompat()) getFragmentManagerS().popBackStack(id, flags); else getFragmentManager().popBackStack(id, flags); } public Fragment findFragmentByTag(String tag) { return getFragmentManager().findFragmentByTag(tag); } public android.support.v4.app.Fragment findFragmentByTagS(String tag) { return getFragmentManagerS().findFragmentByTag(tag); } public Fragment getFragment(Bundle bundle, String key) { return getFragmentManager().getFragment(bundle, key); } public android.support.v4.app.Fragment getFragmentS(Bundle bundle, String key) { return getFragmentManagerS().getFragment(bundle, key); } }
8c6de3bf533242c3c1bf4def8fada0d185ce20f4
3ac65d164cc74a1e11a5798a9796ade327a990c5
/kvstore/src/main/java/com/whiker/learn/kvstore/util/Util.java
2ecc4cb23c3ff6ecf8fe86dee7919cab51f78d4b
[]
no_license
leizton/learnjava
a6a5aacd7bf8c3f165ffbbacf894c2ee70059063
41b0da32615284729bcbe4ece2292242f28311fd
refs/heads/master
2021-05-07T05:32:56.166924
2019-04-24T12:50:51
2019-04-24T12:50:51
111,564,595
0
0
null
null
null
null
UTF-8
Java
false
false
2,405
java
package com.whiker.learn.kvstore.util; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.Closeable; import java.io.IOException; import java.nio.channels.Channel; import java.nio.channels.Selector; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.nio.charset.Charset; import java.util.concurrent.CountDownLatch; /** * Created by whiker on 2017/3/26. */ public class Util { private static final Logger logger = LoggerFactory.getLogger(Util.class); private static final Charset UTF8 = Charset.forName("UTF-8"); public static void waitLatch(CountDownLatch latch) { try { latch.await(); } catch (InterruptedException e) { logger.error("waitLatch be interrupted", e); } } public static void closeServerSocketChannel(ServerSocketChannel ssc) { if (ssc != null) { closeChannelAndSocket(ssc, ssc.socket(), "ServerSocketChannel"); } } public static void closeSocketChannel(SocketChannel sc) { if (sc != null) { closeChannelAndSocket(sc, sc.socket(), "SocketChannel"); } } private static void closeChannelAndSocket(Channel channel, Closeable socket, String channelType) { if (socket != null) { try { socket.close(); } catch (IOException e) { logger.error("close {}'s socket error", channelType, e); } } try { channel.close(); } catch (IOException e) { logger.error("close {} error", channelType, e); } } public static void closeSelector(Selector selector) { if (selector != null) { try { selector.close(); } catch (IOException e) { logger.error("close selector error", e); } } } public static byte[] strToBytes(String s) { if (s == null || s.length() == 0) { return new byte[0]; } return s.getBytes(UTF8); } public static String bytesToStr(byte[] bs) { return bytesToStr(bs, 0, bs.length); } public static String bytesToStr(byte[] bs, int offset, int length) { if (bs == null || bs.length == 0) { return ""; } return new String(bs, offset, length, UTF8); } }
dbfd67969a6dcb6f612fa68ab51166cd5ba24251
c04e2250e502d060e87c0b9ec1564c00303ecd4c
/git-api/src/main/java/com/hivescm/tms/api/dto/es/transport/component/TmsTransportDetailDTO.java
fa53eef6ff5a803bb06e2dbccd4a8390e40029ca
[]
no_license
newbigTech/git
152a52f9b88421d0dc59ba80f9b72f1480d259ce
bcccc20f3011a003740a0211a8d8a2322313f943
refs/heads/master
2020-04-28T08:29:06.981774
2018-08-24T07:07:02
2018-08-24T07:07:02
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,623
java
package com.hivescm.tms.api.dto.es.transport.component; import com.google.common.collect.Lists; import com.hivescm.tms.api.dto.es.transport.TransportGoodsDetailEsDTO; import com.hivescm.tms.api.dto.es.transport.TransportWaybillDetailEsDTO; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.ToString; import java.io.Serializable; import java.util.List; /** * 运输批次明细信息 * * @author 李洪春 * @since 2017/8/29 16:50 */ @Data @ToString public class TmsTransportDetailDTO implements Serializable { private static final long serialVersionUID = 2713552911429364262L; /** * 运输单运单信息 */ @ApiModelProperty("运输单运单信息") private TransportWaybillDetailEsDTO transportWaybillDetail; /** * 运输单货物明细列表 */ @ApiModelProperty("运输单货物明细列表") private List<TransportGoodsDetailEsDTO> transportGoodsDetailList; public TmsTransportDetailDTO() { } public TmsTransportDetailDTO(TransportWaybillDetailEsDTO transportWaybillDetail) { this.transportWaybillDetail = transportWaybillDetail; } // @ApiModelProperty("查询总条数") private Integer count = 0; /** * 添加货物信息 * * @param transportGoodsDetailEsDTO 货物信息 */ public void addTransportGoodsDetailDTO(TransportGoodsDetailEsDTO transportGoodsDetailEsDTO) { if (null == transportGoodsDetailList) { transportGoodsDetailList = Lists.newArrayList(); } transportGoodsDetailList.add(transportGoodsDetailEsDTO); } }
2303c6ed281d2c5e7fd5cc1556298b47b001e9ee
bf4ad0a2921886afbd1a9637ff6c811b216cbde4
/src/main/java/com/njq/nongfadai/test/DynamicProxyPerformanceTest.java
5d59d0187d49c664e63a3a1ef51d0ceb3a00a494
[]
no_license
jerrik123/BytecodeGenerator
1e5556767bbb5e669663762b2d6b876b02782196
7d9e8cccac02ed4f9efa31c2f6d48fbc0e6bd59b
refs/heads/master
2021-01-01T17:51:24.516481
2017-07-24T14:30:49
2017-07-24T14:30:49
98,178,914
1
0
null
null
null
null
UTF-8
Java
false
false
8,548
java
package com.njq.nongfadai.test; import java.lang.reflect.Field; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.text.DecimalFormat; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.FieldVisitor; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import javassist.ClassPool; import javassist.CtClass; import javassist.CtField; import javassist.CtNewConstructor; import javassist.CtNewMethod; import javassist.util.proxy.MethodHandler; import javassist.util.proxy.ProxyFactory; import javassist.util.proxy.ProxyObject; import net.sf.cglib.proxy.Enhancer; import net.sf.cglib.proxy.MethodInterceptor; import net.sf.cglib.proxy.MethodProxy; public class DynamicProxyPerformanceTest { public static void main(String[] args) throws Exception { CountService delegate = new CountServiceImpl(); long time = System.currentTimeMillis(); CountService jdkProxy = createJdkDynamicProxy(delegate); time = System.currentTimeMillis() - time; System.out.println("Create JDK Proxy: " + time + " ms"); printSeparateCharacter(); time = System.currentTimeMillis(); CountService cglibProxy = createCglibDynamicProxy(delegate); time = System.currentTimeMillis() - time; System.out.println("Create CGLIB Proxy: " + time + " ms"); printSeparateCharacter(); time = System.currentTimeMillis(); CountService javassistProxy = createJavassistDynamicProxy(delegate); time = System.currentTimeMillis() - time; System.out.println("Create JAVAASSIST Proxy: " + time + " ms"); printSeparateCharacter(); time = System.currentTimeMillis(); CountService javassistBytecodeProxy = createJavassistBytecodeDynamicProxy(delegate); time = System.currentTimeMillis() - time; System.out.println("Create JAVAASSIST Bytecode Proxy: " + time + " ms"); printSeparateCharacter(); time = System.currentTimeMillis(); CountService asmBytecodeProxy = createAsmBytecodeDynamicProxy(delegate); time = System.currentTimeMillis() - time; System.out.println("Create ASM Proxy: " + time + " ms"); System.out.println("***********************压力测试*************************"); for (int i = 0; i < 3; i++) { test(jdkProxy, "Run JDK Proxy: "); printSeparateCharacter(); test(cglibProxy, "Run CGLIB Proxy: "); printSeparateCharacter(); test(javassistProxy, "Run JAVAASSIST Proxy: "); printSeparateCharacter(); test(javassistBytecodeProxy, "Run JAVAASSIST Bytecode Proxy: "); printSeparateCharacter(); test(asmBytecodeProxy, "Run ASM Bytecode Proxy: "); System.out.println(); System.err.println("-----------------repeat again()-----------------"); System.out.println(); } } private static void printSeparateCharacter() { System.out.println(); System.out.println("======================================"); System.out.println(); } private static void test(CountService service, String label) throws Exception { service.count(); // warm up int count = 10000000; long time = System.currentTimeMillis(); for (int i = 0; i < count; i++) { service.count(); } time = System.currentTimeMillis() - time; System.out.println(label + time + " ms, " + new DecimalFormat().format(count * 1000 / time) + " t/s"); } private static CountService createJdkDynamicProxy(final CountService delegate) { CountService jdkProxy = (CountService) Proxy.newProxyInstance(ClassLoader.getSystemClassLoader(), new Class[] { CountService.class }, new JdkHandler(delegate)); return jdkProxy; } private static class JdkHandler implements InvocationHandler { final Object delegate; JdkHandler(Object delegate) { this.delegate = delegate; } public Object invoke(Object object, Method method, Object[] objects) throws Throwable { return method.invoke(delegate, objects); } } private static CountService createCglibDynamicProxy(final CountService delegate) throws Exception { Enhancer enhancer = new Enhancer(); enhancer.setCallback(new CglibCallback(delegate)); enhancer.setInterfaces(new Class[] { CountService.class }); CountService cglibProxy = (CountService) enhancer.create(); return cglibProxy; } private static class CglibCallback implements MethodInterceptor { final Object delegate; CglibCallback(Object delegate) { this.delegate = delegate; } public Object intercept(Object object, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable { return methodProxy.invoke(delegate, objects); } } private static CountService createJavassistDynamicProxy(final CountService delegate) throws Exception { ProxyFactory proxyFactory = new ProxyFactory(); proxyFactory.setInterfaces(new Class[] { CountService.class }); Class<?> proxyClass = proxyFactory.createClass(); CountService javassistProxy = (CountService) proxyClass.newInstance(); ((ProxyObject) javassistProxy).setHandler(new JavaAssistHandler(delegate)); return javassistProxy; } private static class JavaAssistHandler implements MethodHandler { final Object delegate; JavaAssistHandler(Object delegate) { this.delegate = delegate; } public Object invoke(Object self, Method m, Method proceed, Object[] args) throws Throwable { return m.invoke(delegate, args); } } private static CountService createJavassistBytecodeDynamicProxy(CountService delegate) throws Exception { ClassPool mPool = new ClassPool(true); CtClass mCtc = mPool.makeClass(CountService.class.getName() + "JavaassistProxy"); mCtc.addInterface(mPool.get(CountService.class.getName())); mCtc.addConstructor(CtNewConstructor.defaultConstructor(mCtc)); mCtc.addField(CtField.make("public " + CountService.class.getName() + " delegate;", mCtc)); mCtc.addMethod(CtNewMethod.make("public int count() { return delegate.count(); }", mCtc)); Class<?> pc = mCtc.toClass(); CountService bytecodeProxy = (CountService) pc.newInstance(); Field filed = bytecodeProxy.getClass().getField("delegate"); filed.set(bytecodeProxy, delegate); return bytecodeProxy; } private static CountService createAsmBytecodeDynamicProxy(CountService delegate) throws Exception { ClassWriter classWriter = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS); String className = CountService.class.getName() + "AsmProxy"; String classPath = className.replace('.', '/'); String interfacePath = CountService.class.getName().replace('.', '/'); classWriter.visit(Opcodes.V1_5, Opcodes.ACC_PUBLIC, classPath, null, "java/lang/Object", new String[] { interfacePath }); MethodVisitor initVisitor = classWriter.visitMethod(Opcodes.ACC_PUBLIC, "<init>", "()V", null, null); initVisitor.visitCode(); initVisitor.visitVarInsn(Opcodes.ALOAD, 0); initVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/Object", "<init>", "()V"); initVisitor.visitInsn(Opcodes.RETURN); initVisitor.visitMaxs(0, 0); initVisitor.visitEnd(); FieldVisitor fieldVisitor = classWriter.visitField(Opcodes.ACC_PUBLIC, "delegate", "L" + interfacePath + ";", null, null); fieldVisitor.visitEnd(); MethodVisitor methodVisitor = classWriter.visitMethod(Opcodes.ACC_PUBLIC, "count", "()I", null, null); methodVisitor.visitCode(); methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitFieldInsn(Opcodes.GETFIELD, classPath, "delegate", "L" + interfacePath + ";"); methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, interfacePath, "count", "()I"); methodVisitor.visitInsn(Opcodes.IRETURN); methodVisitor.visitMaxs(0, 0); methodVisitor.visitEnd(); classWriter.visitEnd(); byte[] code = classWriter.toByteArray(); CountService bytecodeProxy = (CountService) new ByteArrayClassLoader().getClass(className, code).newInstance(); Field filed = bytecodeProxy.getClass().getField("delegate"); filed.set(bytecodeProxy, delegate); return bytecodeProxy; } private static class ByteArrayClassLoader extends ClassLoader { public ByteArrayClassLoader() { super(ByteArrayClassLoader.class.getClassLoader()); } public synchronized Class<?> getClass(String name, byte[] code) { if (name == null) { throw new IllegalArgumentException(""); } return defineClass(name, code, 0, code.length); } } }
1666977955fa4bd2908253b4b6685420044bbe2e
0db0728b17e34ae1fe5a5d2273f9632a0c4ad115
/day15/src/instanceInnerEx/InstanceInnerTest01.java
7c3b746ab53eaf8470ed3319311cb3927065d6fd
[]
no_license
kiekk/study-java
db4739b42993dbdb593ef9494ba60f56f122b5ed
bb1c4ad38a1b810c03826911b6ca7b6b6abfff2e
refs/heads/master
2023-02-08T23:10:22.738744
2020-12-31T06:24:38
2020-12-31T06:24:38
null
0
0
null
null
null
null
UHC
Java
false
false
1,054
java
package instanceInnerEx; /* 이너클래스 -인스턴스 이너 클래스 -이너(내부) 클래스가 잇는데, 그 이너 클래스도 멤버입니다. -그 멤버는 필드나 메서드가 아니라, 클래스인 멤버입니다. -따라서 클래스인 멤버(이너 클래스)는 인스턴스를 만든 후, 내부 클래스의 필드에 접근해야 합니다. */ class Outer{ int x = 10; //outer의 x void fct() { //outer의 fct() System.out.println(x); } class Inner{ int y = 10; void fct_y() { System.out.println(y); System.out.println("외부 클래스 x : " +x); } } //Inner클래스에서 Outer의 멤버들에 직접 접근이 가능합니다. } public class InstanceInnerTest01 { public static void main(String[] args) { Outer out = new Outer(); Outer.Inner innerObj = out.new Inner(); //내부 클래스 타입 선언은 .을 통해서 구체화 되어야 합니다. //이름이 같은 일반 클래스와 중복될 수 있기 때문 System.out.println(innerObj.y); innerObj.fct_y(); } }
16e81add95984d60820350096bdf8aca83e31b9a
c81ff1ad77c970130d7aea281910eb389e70d0d9
/Exp_8/Bank.java
cfd948faa48ce472f1dbfb20eacfd936aec940d5
[]
no_license
SomnathShintre91/Java
601cb198c30f4f5bcd16d9331e0587b7237e1de3
9296ff95310ffe031932f1d39fd72afa7799af55
refs/heads/master
2023-03-29T14:50:31.072468
2021-03-30T14:03:12
2021-03-30T14:03:12
278,625,523
0
0
null
null
null
null
UTF-8
Java
false
false
523
java
public interface Bank { public static final int permanentpassword = 9359; public abstract double balanceEnquery(); public abstract double withdraw(double withdrawAmount) throws LowBalanceException, NegetiveNumberException; public abstract String transfer(int password, double transferAmount, BankAccount to) throws LowBalanceException, NegetiveNumberException, PasswordMismatchException; public abstract void deposit(double depositAmount) throws NegetiveNumberException; }
e5f50ef4afdab55270f2b207b6da7e5f10ff6472
47ca68cfb7bb6838bf5b24021122908c7c5cd8d6
/skstructure/src/main/java/com/skstructure/modules/retrofit2/http/OPTIONS.java
c03a9228b784daa4db30bd7de4461aec77740a40
[]
no_license
ShuKeW/SKStructure
352b2730668989aa6c5fab0addac5c413a89dd1d
f2a5bf56fe9d6fc17a36643982e06f29023db9ef
refs/heads/master
2020-04-15T10:24:28.222175
2019-01-09T06:56:46
2019-01-09T06:56:46
164,594,656
4
1
null
null
null
null
UTF-8
Java
false
false
1,423
java
/* * Copyright (C) 2015 Square, 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.skstructure.modules.retrofit2.http; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; import okhttp3.HttpUrl; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.RetentionPolicy.RUNTIME; /** Make an OPTIONS request. */ @Documented @Target(METHOD) @Retention(RUNTIME) public @interface OPTIONS { /** * A relative or absolute path, or full URL of the endpoint. This value is optional if the first * parameter of the method is annotated with {@link Url @Url}. * <p> * See {@linkplain com.skstructure.modules.retrofit2.Retrofit.Builder#baseUrl(HttpUrl) base URL} for details of how * this is resolved against a base URL to create the full endpoint URL. */ String value() default ""; }
ca02ac72098cecdca5a4fc0a4b7dc4126233aa0e
2e5494a28d0315e31a7eb31bb10cd2b9821b8bc2
/src/main/java/nl/kolkos/domoticz/dashboard/domoticz/repositories/HeaterRepository.java
4eebcbc89467e9e244d5694bcc44e2d2a6a3bc93
[ "MIT" ]
permissive
kolkos/domoticz.dashboard
a7675363c00e6ba77cf11d7ada361aabe7e36484
369798d95ac29d7b2dc8b2bbbc490a6a166c4ede
refs/heads/master
2023-04-30T14:32:25.596505
2020-02-21T14:34:55
2020-02-21T14:34:55
220,426,529
0
0
MIT
2023-04-14T17:54:48
2019-11-08T08:56:34
Java
UTF-8
Java
false
false
251
java
package nl.kolkos.domoticz.dashboard.domoticz.repositories; import nl.kolkos.domoticz.dashboard.domoticz.entities.Heater; import javax.transaction.Transactional; @Transactional public interface HeaterRepository extends DeviceRepository<Heater> { }
8feaf3eda3a2646493a1d9670726e44212540087
ffdbd487e1ea5e15a9b64b4dd007655e21c6e52a
/smartsoft_spring/src/main/java/com/smartsoft/test/repositories/ClientRepository.java
1a44002d1731adaca8f724a6aaad3599f5ce8c1c
[]
no_license
dmedinao11/smartsoft_test
57ecec05143c4c2f90d86f2226f1aa14449740d1
50c1941dfd0cbd1d26ca8b44846b73af19f35b6e
refs/heads/main
2023-08-31T08:33:25.811543
2021-10-29T00:17:14
2021-10-29T00:17:14
null
0
0
null
null
null
null
UTF-8
Java
false
false
338
java
package com.smartsoft.test.repositories; import com.smartsoft.test.models.Client; import org.springframework.data.repository.CrudRepository; import java.util.List; import java.util.Optional; public interface ClientRepository extends CrudRepository<Client, Long> { List<Client> findAll(); Optional<Client> findById(Long id); }
9d9ebd5a528ee6f673d6faa1aa0d0eed67160577
b473c2f1ccf7b67e3d061a2d11e669c33982e7bf
/apache-batik/sources/org/apache/batik/bridge/EmbededExternalResourceSecurity.java
7a45d167602f8c76d62844b76049c396f0f76d54
[ "Apache-2.0" ]
permissive
eGit/appengine-awt
4ab046498bad79eddf1f7e74728bd53dc0044526
4262657914eceff1fad335190613a272cc60b940
refs/heads/master
2021-01-01T15:36:07.658506
2015-08-26T11:40:24
2015-08-26T11:40:24
41,421,915
0
0
null
null
null
null
UTF-8
Java
false
false
2,873
java
/* 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.batik.bridge; import org.apache.batik.util.ParsedURL; /** * This implementation of the <tt>ExternalResourceSecurity</tt> interface only * allows external resources embeded in the document, i.e., externalResources * embeded with the data protocol. * * @author <a href="mailto:[email protected]">Vincent Hardy</a> * @version $Id: EmbededExternalResourceSecurity.java 662002 2008-05-31 11:22:50Z cam $ */ public class EmbededExternalResourceSecurity implements ExternalResourceSecurity { public static final String DATA_PROTOCOL = "data"; /** * Message when trying to load a external resource that is not embeded * in the document. */ public static final String ERROR_EXTERNAL_RESOURCE_NOT_EMBEDED = "EmbededExternalResourceSecurity.error.external.resource.not.embeded"; /** * The exception is built in the constructor and thrown if * not null and the checkLoadExternalResource method is called. */ protected SecurityException se; /** * Controls whether the externalResource should be loaded or not. * * @throws SecurityException if the externalResource should not be loaded. */ public void checkLoadExternalResource(){ if (se != null) { throw se; } } /** * @param externalResourceURL url for the externalResource, as defined in * the externalResource's xlink:href attribute. If that * attribute was empty, then this parameter should * be null */ public EmbededExternalResourceSecurity(ParsedURL externalResourceURL){ if ( externalResourceURL == null || !DATA_PROTOCOL.equals(externalResourceURL.getProtocol()) ) { se = new SecurityException (Messages.formatMessage(ERROR_EXTERNAL_RESOURCE_NOT_EMBEDED, new Object[]{externalResourceURL})); } } }
857990043f9183bba6f59e5b020abf376ade0509
d9fd9de6d33a2ca9443d72b1361165d42a17fe28
/SpringCloudDemo/cloud_modules/itdj-upms-server/src/main/java/com/itdj/admin/mapper/SysDeptMapper.java
ad19f65e4517c7f7de1b7bdc141678f27cfd359f
[]
no_license
mingtin1/springCloud-itdj
6c4818fdbf4c92feb48573b5f63efc1230199cbd
13797651feee11aaa79145003790ddb6616d8791
refs/heads/master
2020-04-01T13:44:23.445900
2019-01-15T08:08:32
2019-01-15T08:08:32
153,265,406
0
0
null
null
null
null
UTF-8
Java
false
false
1,406
java
/* * Copyright (c) 2018-2025, djj All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * Neither the name of the pig4cloud.com developer nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * Author: djj ([email protected]) */ package com.itdj.admin.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.itdj.admin.model.entity.SysDept; import java.util.List; /** * <p> * 部门管理 Mapper 接口 * </p> * * @author djj * @since 2018-01-20 */ public interface SysDeptMapper extends BaseMapper<SysDept> { /** * 关联dept——relation * * @param delFlag 删除标记 * @return 数据列表 */ List<SysDept> selectDeptDtoList(String delFlag); /** * 删除部门关系表数据 * @param id 部门ID */ void deleteDeptRealtion(Integer id); }
960293c4aa97f56186953b4f3bae7594ea95be22
cb67755debd4ea35e90d31704c18be8318be5849
/app/src/main/java/cjx/liyueyun/viewpagerdemo/viewpager/NoScrollViewPager.java
4668d019fc4d6f600cbc70cdb7691e4a244afcfd
[]
no_license
caijianxiong/ViewPagerDemo
d3b2200744baf00f7a04ffb719a42536a7a76d8b
7d6121b26d286db7336a4d34c0a80a8487bfb2fe
refs/heads/master
2020-08-29T10:42:01.454596
2019-10-29T08:31:31
2019-10-29T08:31:31
218,008,854
6
0
null
null
null
null
UTF-8
Java
false
false
1,468
java
package cjx.liyueyun.viewpagerdemo.viewpager; import android.content.Context; import android.support.v4.view.ViewPager; import android.util.AttributeSet; import android.view.FocusFinder; import android.view.View; /** * Created by SongJie on 10/23 0023. * 设置禁止左右键滑动 */ public class NoScrollViewPager extends ViewPager { private final String TAG = this.getClass().getSimpleName(); public NoScrollViewPager(Context context, AttributeSet attrs) { super(context, attrs); } public NoScrollViewPager(Context context) { super(context); } @Override public boolean arrowScroll(int direction) { View currentFocused = findFocus(); if (currentFocused == this) currentFocused = null; boolean handled = false; View nextFocused = FocusFinder.getInstance().findNextFocus(this, currentFocused, direction); if (nextFocused != null && nextFocused != currentFocused) { if (direction == View.FOCUS_LEFT) { handled = false; } else if (direction == View.FOCUS_RIGHT) { handled = false; } } else if (direction == FOCUS_LEFT || direction == FOCUS_BACKWARD) {//17 or 1 handled = true; } else if (direction == FOCUS_RIGHT || direction == FOCUS_FORWARD) {//66 or 2 handled = true; } return handled; // return super.arrowScroll(direction); } }
05b3f8a89b6ba5798493dead4770a7bdeb14aea1
08f6a91b35764decfba3814f5703cc738cbb1a33
/BandaDeInstrumentos/src/bandadeinstrumentos/Chelo.java
9ba2cabbb15feabab0a11440d4fe98455d852c3b
[]
no_license
JoaquinAguilar/Java_Practices
f794867a2b4c225ba2bbdae0c7101bb8a870f79e
41b09c24607d04711877e9fd604652efc686d4ed
refs/heads/main
2023-02-20T03:38:56.927353
2021-01-26T00:19:14
2021-01-26T00:19:14
332,917,411
0
0
null
null
null
null
UTF-8
Java
false
false
82
java
package bandadeinstrumentos; public class Chelo extends Instrumento{ }
40d4da6acbf4aec80f96a9ff78aab8d978d2b494
cd4196462c2c3accbb658e4399db2fa1f26ad2a1
/src/main/java/com/hao/util/ImportExcelUtil.java
bea44207ac89b129ea80eca9b8a62c4a25cee247
[]
no_license
wuhao1123/myUtil
2b6cdd79f50e6d2603890981ceec51e80d81c772
204774aae9b5dfc91b7d50ced8cc3f1031244d24
refs/heads/master
2021-04-27T02:35:42.183472
2018-03-17T01:04:29
2018-03-17T01:04:29
122,698,277
1
0
null
null
null
null
UTF-8
Java
false
false
10,790
java
package com.hao.util; import java.io.File; import java.io.FileInputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.hao.util.base.StringUtil; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFDataFormatter; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import com.hao.util.base.ValidateException; /** * 类ImportExcelUtil.java的实现描述:excel导入处理分析数据 * * @author 吴昊 2018年3月17日09:01:15 */ public class ImportExcelUtil { /** * 批量导入的最小数据条数:1 */ private static final int IMPORT_MIN_ROW_NO = 1; /** * 批量导入的最小工作组个数:1 */ private static final int IMPORT_MIN_SHEET_NO = 1; /** * 批量导入的最大工作组个数:1 */ private static final int IMPORT_MAX_SHEET_NO = 1; /** * 批量导入开始读取的行号:3,索引是2 */ private static final int READ_START_ROW_NO = 2; /** * 批量导入开始读取的列号:2 */ private static final int READ_START_COLUMN_NO = 2; /** * 说明方法描述:分析处理excel数据,返回list * * @param excelPath * @param importMaxRowNo 允许导入的数据量(行数) * @return * @throws Exception * @throws ValidateException * @time 2018年3月17日09:01:24 * @author 吴昊 */ public static List<Map<Integer, Object>> dealDataForExcel(String fileName, File file, int importMaxRowNo) throws Exception, ValidateException { if (StringUtil.isBlank(fileName)) { throw new ValidateException("FUL0007"); } String suffix = fileName.substring(fileName.lastIndexOf(".") + 1); if (StringUtil.isBlank(suffix)) { throw new ValidateException("FUL0013"); } // 判断格式是否合法 List<Map<Integer, Object>> list = null; if (StringUtil.equals(suffix, "xls")) { list = dealDataForXls(file, importMaxRowNo); } else if (StringUtil.equals(suffix, "xlsx")) { list = dealDataForXlsx(file, importMaxRowNo); } else { throw new ValidateException("FUL0013"); } return list; } /** * 分析excel的内容,2007以下的版本xlsx * * @param path * @return */ private static List<Map<Integer, Object>> dealDataForXlsx(File file, int importMaxRowNo) throws Exception, ValidateException { List<Map<Integer, Object>> list = new ArrayList<Map<Integer, Object>>(); // 工作簿 XSSFWorkbook hwb = null; hwb = new XSSFWorkbook(new FileInputStream(file)); if (hwb != null) { // 循环读取所有sheet int sheetCount = hwb.getNumberOfSheets(); if (sheetCount < IMPORT_MIN_SHEET_NO) { throw new ValidateException("FUL0014"); } for (int sheetIndex = 0; sheetIndex < IMPORT_MAX_SHEET_NO; sheetIndex++) { // 获取到第sheetIndex个sheet中数据 XSSFSheet sheet = hwb.getSheetAt(sheetIndex); if (sheet != null) { int totalRowNo = sheet.getLastRowNum() - 1; if (totalRowNo < IMPORT_MIN_ROW_NO) { throw new ValidateException("FUL0014"); } if (totalRowNo > importMaxRowNo) { throw new ValidateException("批量导入每次最多只能导入" + importMaxRowNo + "条数据"); } for (int i = READ_START_ROW_NO; i < sheet.getLastRowNum(); i++) {// 第三行开始取值,第一行为标题行 XSSFRow row = sheet.getRow(i); // 获取到第i列的行数据(表格行) if (row != null) { Map<Integer, Object> map = new HashMap<Integer, Object>(); for (int j = READ_START_COLUMN_NO - 1; j < row.getLastCellNum(); j++) {// 从第二列开始取值,第一列为序号 XSSFCell cell = row.getCell(j); // 获取到第j行的数据(单元格) if (cell != null) { String cellValue = ""; if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC || cell.getCellType() == HSSFCell.CELL_TYPE_FORMULA) { HSSFDataFormatter dataFormatter = new HSSFDataFormatter(); cellValue = dataFormatter.formatCellValue(cell); } else { cell.setCellType(XSSFCell.CELL_TYPE_STRING); cellValue = cell.getStringCellValue(); } if (StringUtil.isNotBlank(cellValue)) { // 解决1234.0 去掉后面的.0 String[] item = cellValue.split("[.]"); if (1 < item.length && "0".equals(item[1])) { cellValue = item[0]; } map.put(j, cellValue); } } // else { // log.info("解析数据---------->第" + (i + 1) + "行,第" + j + "个单元格值为:空"); // } } if (map != null && map.size() > 0) { list.add(map); } } } } } } if (list == null || list.size() == 0) { throw new ValidateException("FUL0014"); } return list; } /** * 分析excel的内容,2007以上的版本xls * * @param path * @return */ private static List<Map<Integer, Object>> dealDataForXls(File file, int importMaxRowNo) throws Exception, ValidateException { List<Map<Integer, Object>> list = new ArrayList<Map<Integer, Object>>(); // 工作簿 HSSFWorkbook hwb = null; hwb = new HSSFWorkbook(new FileInputStream(file)); if (hwb != null) { // 循环读取所有sheet int sheetCount = hwb.getNumberOfSheets(); if (sheetCount < IMPORT_MIN_SHEET_NO) { throw new ValidateException("FUL0014"); } for (int sheetIndex = 0; sheetIndex < IMPORT_MAX_SHEET_NO; sheetIndex++) { // 获取到第sheetIndex个sheet中数据 HSSFSheet sheet = hwb.getSheetAt(sheetIndex); if (sheet != null) { int totalRowNo = sheet.getLastRowNum() - 1; if (totalRowNo < IMPORT_MIN_ROW_NO) { throw new ValidateException("FUL0014"); } if (totalRowNo > importMaxRowNo) { // log.info("批量导入每次最多只能导入" + importMaxRowNo + "条数据"); throw new ValidateException("批量导入每次最多只能导入" + importMaxRowNo + "条数据"); } for (int i = READ_START_ROW_NO; i <= totalRowNo; i++) {// 第三行开始取值,第一行为标题行 HSSFRow row = sheet.getRow(i); // 获取到第i列的行数据(表格行) if (row != null) { Map<Integer, Object> map = new HashMap<Integer, Object>(); for (int j = READ_START_COLUMN_NO - 1; j < row.getLastCellNum(); j++) {// 从第二列开始取值,第一列为序号 HSSFCell cell = row.getCell(j); // 获取到第j行的数据(单元格) if (cell != null) { String cellValue = ""; if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC || cell.getCellType() == HSSFCell.CELL_TYPE_FORMULA) { HSSFDataFormatter dataFormatter = new HSSFDataFormatter(); cellValue = dataFormatter.formatCellValue(cell); } else { cell.setCellType(XSSFCell.CELL_TYPE_STRING); cellValue = cell.getStringCellValue(); } // log.info("解析数据---------->第" + (i + 1) + "行,第" + j + "个单元格值为:" + cellValue); if (StringUtil.isNotBlank(cellValue)) { // 解决1234.0 去掉后面的.0 String[] item = cellValue.split("[.]"); if (1 < item.length && "0".equals(item[1])) { cellValue = item[0]; } map.put(j, cellValue); } } // else { // log.info("解析数据---------->第" + (i + 1) + "行,第" + j + "个单元格值为:空"); // } } if (map != null && map.size() > 0) { list.add(map); } } } } } } if (list == null || list.size() == 0) { throw new ValidateException("FUL0014"); } return list; } }
[ "wuhao135798462" ]
wuhao135798462
628ab26f889a6317f0994be748d72e179847f51c
c0630011b46eca7e9644d884fe162c2e009a87f7
/javav2/example_code/kms/src/main/java/com/example/kms/ListAliases.java
95838460eead0435ca721e0569b6916062830750
[ "Apache-2.0", "CC-BY-NC-SA-4.0" ]
permissive
BrentAtAWS/aws-doc-sdk-examples
6e5c7ea2dca3b26f207088627ffe35f3d411524c
79adcbb48c63729b100bd6b5745d74494d4c1559
refs/heads/main
2022-08-19T08:31:32.861516
2022-07-22T17:57:21
2022-07-22T17:57:21
427,142,303
0
0
Apache-2.0
2021-11-11T21:02:37
2021-11-11T21:02:37
null
UTF-8
Java
false
false
2,471
java
//snippet-sourcedescription:[ListAliases.java demonstrates how to get a list of AWS Key Management Service (AWS KMS) aliases.] //snippet-keyword:[AWS SDK for Java v2] //snippet-keyword:[Code Sample] //snippet-service:[AWS Key Management Service] //snippet-sourcetype:[full-example] //snippet-sourcedate:[05/18/2022] /* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ package com.example.kms; // snippet-start:[kms.java2_list_aliases.import] import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.kms.KmsClient; import software.amazon.awssdk.services.kms.model.AliasListEntry; import software.amazon.awssdk.services.kms.model.KmsException; import software.amazon.awssdk.services.kms.model.ListAliasesRequest; import software.amazon.awssdk.services.kms.model.ListAliasesResponse; import java.util.List; // snippet-end:[kms.java2_list_aliases.import] /** * Before running this Java V2 code example, set up your development environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class ListAliases { public static void main(String[] args) { Region region = Region.US_WEST_2; KmsClient kmsClient = KmsClient.builder() .region(region) .credentialsProvider(ProfileCredentialsProvider.create()) .build(); listAllAliases(kmsClient); kmsClient.close(); } // snippet-start:[kms.java2_list_aliases.main] public static void listAllAliases( KmsClient kmsClient) { try { ListAliasesRequest aliasesRequest = ListAliasesRequest.builder() .limit(15) .build(); ListAliasesResponse aliasesResponse = kmsClient.listAliases(aliasesRequest) ; List<AliasListEntry> aliases = aliasesResponse.aliases(); for (AliasListEntry alias: aliases) { System.out.println("The alias name is: "+alias.aliasName()); } } catch (KmsException e) { System.err.println(e.getMessage()); System.exit(1); } } // snippet-end:[kms.java2_list_aliases.main] }
6a083d84cd5ea608c4e5737eafde1f9aa2c3b89e
ee19c2fff19caddf0210496da6d8640a509dc911
/app/src/androidTest/java/com/example/elvira/helloworld/ApplicationTest.java
fcde0b3e4fe6c4b0d7db90818af787a2da63aa5d
[]
no_license
ElviraLee/HelloWorld
916b16ac3094789dd56bb6049ebfb2be7ad47934
4cc2e11d3f98d7b85ee60bf8498da787be9cc06a
refs/heads/master
2021-01-17T19:52:19.903849
2016-07-27T03:40:22
2016-07-27T03:40:22
64,207,906
0
0
null
null
null
null
UTF-8
Java
false
false
360
java
package com.example.elvira.helloworld; import android.app.Application; import android.test.ApplicationTestCase; /** * <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a> */ public class ApplicationTest extends ApplicationTestCase<Application> { public ApplicationTest() { super(Application.class); } }
[ "Elvira Lee" ]
Elvira Lee
2e3d7bc4cc0de7ff2f91b0bed21f55fccd42bcea
3f655ad097dde073d28c304e07cf16ca8cc1af43
/src/AdditionDynInput.java
e697dcb2ffcacd64fdb99f21f03f769f9710fd58
[]
no_license
Muralidhargoudediga/JavaClass
a927f784aa8aa7633dc564f462fc1858caadc6f0
969de356377a416bb14ceec367a7f09c74f9a3ca
refs/heads/master
2020-04-25T11:59:49.242067
2019-03-20T18:08:02
2019-03-20T18:11:29
172,763,921
0
0
null
null
null
null
UTF-8
Java
false
false
675
java
import java.util.Scanner; public class AdditionDynInput { int a; int b; //Initialization purpose public AdditionDynInput(int x, int y){ //Constructor a = x; b = y; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Please enter a value : "); int x = sc.nextInt(); System.out.println("Please enter b value : "); int y = sc.nextInt(); AdditionDynInput addition = new AdditionDynInput(x, y); int c = addition.add(); show(c); sc.close(); } static void show(int c) { System.out.println("Addition is : " + c); } public int add() { return this.a+this.b; } }
35e8cf85861df44acf9872484c6b9c4b9d8d8222
5cf97055ef6c0f61f1fa58b70b12ec55bdf319f7
/WindowUtils.java
66080eac46353ef8c42e4989a7b56e8acccd5e02
[]
no_license
ysnows/androidUtils
337d1656a4c81f8ee8404655eb48f7f4303a23f1
8528e872e706f9e078f8ff8a9947ea97b2b9d890
refs/heads/master
2021-01-11T09:33:26.527573
2017-01-01T02:06:05
2017-01-01T02:06:05
77,762,546
2
0
null
null
null
null
UTF-8
Java
false
false
4,398
java
package ysnows.myapplication; import android.app.Activity; import android.app.ActivityManager; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.graphics.PixelFormat; import android.net.Uri; import android.os.Build; import android.provider.Settings; import android.view.Gravity; import android.view.WindowManager; import java.util.ArrayList; import java.util.List; /** * Created by xianguangjin on 2017/1/1. */ public class WindowUtils { private static WindowManager mWindowManager; private static FloatWindowSmallView smallWindow; private static WindowManager.LayoutParams smallWindowParams; private static float float_width; /** * 创建一个小悬浮窗。初始位置为屏幕的右部中间位置。 * * @param context 必须为应用程序的Context. */ public static void createSmallWindow(Context context) { WindowManager windowManager = getWindowManager(context); int screenWidth = windowManager.getDefaultDisplay().getWidth(); int screenHeight = windowManager.getDefaultDisplay().getHeight(); float_width = context.getResources().getDimensionPixelSize(R.dimen.float_width); if (smallWindow == null) { smallWindow = new FloatWindowSmallView(context); if (smallWindowParams == null) { smallWindowParams = new WindowManager.LayoutParams(); smallWindowParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT; smallWindowParams.format = PixelFormat.RGBA_8888; smallWindowParams.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE; smallWindowParams.gravity = Gravity.LEFT | Gravity.TOP; smallWindowParams.width = (int) float_width; smallWindowParams.height = (int) float_width; smallWindowParams.x = screenWidth; smallWindowParams.y = screenHeight / 2; } smallWindow.setParams(smallWindowParams); windowManager.addView(smallWindow, smallWindowParams); } } /** * 如果WindowManager还未创建,则创建一个新的WindowManager返回。否则返回当前已创建的WindowManager。 * * @param context 必须为应用程序的Context. * @return WindowManager的实例,用于控制在屏幕上添加或移除悬浮窗。 */ private static WindowManager getWindowManager(Context context) { if (mWindowManager == null) { mWindowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); } return mWindowManager; } /** * @param activity 检查覆盖其他应用权限 */ public static void checkDrawOverlay(Activity activity) { if (Build.VERSION.SDK_INT >= 23) { if (!Settings.canDrawOverlays(activity)) { Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + activity.getPackageName())); activity.startActivityForResult(intent, 1234); } } } /** * 判断当前界面是否是桌面 */ public static boolean isHome(Context context) { ActivityManager mActivityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); List<ActivityManager.RunningTaskInfo> rti = mActivityManager.getRunningTasks(1); return getHomes(context).contains(rti.get(0).topActivity.getPackageName()); } /** * 获得属于桌面的应用的应用包名称 * * @return 返回包含所有包名的字符串列表 */ public static List<String> getHomes(Context context) { List<String> names = new ArrayList<String>(); PackageManager packageManager = context.getPackageManager(); Intent intent = new Intent(Intent.ACTION_MAIN); intent.addCategory(Intent.CATEGORY_HOME); List<ResolveInfo> resolveInfo = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY); for (ResolveInfo ri : resolveInfo) { names.add(ri.activityInfo.packageName); } return names; } }
62b5bad0b5324c6dda2265cbf6eb95ffb9aa7bb2
217d8acdf1480c83f368a34cff1512cfe83b8db0
/src/main/java/pl/sda/quiz_app/Models/Answer.java
c23d09233e70cdfdfcddab7cb42dc708229e5efb
[]
no_license
Gnidus/quiz_app
69514595cd8f71a36d2abc9d32faa9d4831e6858
f2fd76135da86f6a1974e45ecbb0cb2ab42d7f6e
refs/heads/master
2020-08-05T04:41:54.977727
2019-10-07T18:12:04
2019-10-07T18:12:04
212,399,892
0
0
null
null
null
null
UTF-8
Java
false
false
368
java
package pl.sda.quiz_app.Models; import lombok.Data; import lombok.NoArgsConstructor; import javax.persistence.*; @Entity @Data @NoArgsConstructor public class Answer { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; private String content; private boolean correct; @ManyToOne private Question question; }
99abd3df2d1ad4a3ec2fbde0d73ea2a47191cd60
7abff576a8ee9eb1a5093deb79d5fd6b9d02ff8e
/arbi-micro-third-service/src/main/java/com/zyxy/service/micro/third/client/ruilian/webservice/CancelReceiptStockVO.java
2860fe1e04f1d928ca802b4c9f164558dc33be72
[]
no_license
xdis/parent
54b894308c237e1e16277b32b5622082a39cb56a
e7cf1b8ce6396127b6e9d88f3533b2c23ff90db8
refs/heads/master
2020-03-28T19:42:16.724284
2018-08-21T06:35:23
2018-08-21T06:35:23
null
0
0
null
null
null
null
UTF-8
Java
false
false
12,566
java
/** * CancelReceiptStockVO.java * * This file was auto-generated from WSDL * by the Apache Axis 1.4 Apr 22, 2006 (06:55:48 PDT) WSDL2Java emitter. */ package com.zyxy.service.micro.third.client.ruilian.webservice; public class CancelReceiptStockVO extends com.zyxy.service.micro.third.client.ruilian.webservice.GenericVO implements java.io.Serializable { private java.lang.String endNO; private int pieceCount; private java.lang.String procTM; private double recedePrice; private java.lang.String receiverName; private java.lang.String rtNO; private java.lang.String startNO; private java.lang.String stockHouseName; private java.lang.String unitNO; public CancelReceiptStockVO() { } public CancelReceiptStockVO( java.lang.String loginKey, java.lang.String endNO, int pieceCount, java.lang.String procTM, double recedePrice, java.lang.String receiverName, java.lang.String rtNO, java.lang.String startNO, java.lang.String stockHouseName, java.lang.String unitNO) { super( loginKey); this.endNO = endNO; this.pieceCount = pieceCount; this.procTM = procTM; this.recedePrice = recedePrice; this.receiverName = receiverName; this.rtNO = rtNO; this.startNO = startNO; this.stockHouseName = stockHouseName; this.unitNO = unitNO; } /** * Gets the endNO value for this CancelReceiptStockVO. * * @return endNO */ public java.lang.String getEndNO() { return endNO; } /** * Sets the endNO value for this CancelReceiptStockVO. * * @param endNO */ public void setEndNO(java.lang.String endNO) { this.endNO = endNO; } /** * Gets the pieceCount value for this CancelReceiptStockVO. * * @return pieceCount */ public int getPieceCount() { return pieceCount; } /** * Sets the pieceCount value for this CancelReceiptStockVO. * * @param pieceCount */ public void setPieceCount(int pieceCount) { this.pieceCount = pieceCount; } /** * Gets the procTM value for this CancelReceiptStockVO. * * @return procTM */ public java.lang.String getProcTM() { return procTM; } /** * Sets the procTM value for this CancelReceiptStockVO. * * @param procTM */ public void setProcTM(java.lang.String procTM) { this.procTM = procTM; } /** * Gets the recedePrice value for this CancelReceiptStockVO. * * @return recedePrice */ public double getRecedePrice() { return recedePrice; } /** * Sets the recedePrice value for this CancelReceiptStockVO. * * @param recedePrice */ public void setRecedePrice(double recedePrice) { this.recedePrice = recedePrice; } /** * Gets the receiverName value for this CancelReceiptStockVO. * * @return receiverName */ public java.lang.String getReceiverName() { return receiverName; } /** * Sets the receiverName value for this CancelReceiptStockVO. * * @param receiverName */ public void setReceiverName(java.lang.String receiverName) { this.receiverName = receiverName; } /** * Gets the rtNO value for this CancelReceiptStockVO. * * @return rtNO */ public java.lang.String getRtNO() { return rtNO; } /** * Sets the rtNO value for this CancelReceiptStockVO. * * @param rtNO */ public void setRtNO(java.lang.String rtNO) { this.rtNO = rtNO; } /** * Gets the startNO value for this CancelReceiptStockVO. * * @return startNO */ public java.lang.String getStartNO() { return startNO; } /** * Sets the startNO value for this CancelReceiptStockVO. * * @param startNO */ public void setStartNO(java.lang.String startNO) { this.startNO = startNO; } /** * Gets the stockHouseName value for this CancelReceiptStockVO. * * @return stockHouseName */ public java.lang.String getStockHouseName() { return stockHouseName; } /** * Sets the stockHouseName value for this CancelReceiptStockVO. * * @param stockHouseName */ public void setStockHouseName(java.lang.String stockHouseName) { this.stockHouseName = stockHouseName; } /** * Gets the unitNO value for this CancelReceiptStockVO. * * @return unitNO */ public java.lang.String getUnitNO() { return unitNO; } /** * Sets the unitNO value for this CancelReceiptStockVO. * * @param unitNO */ public void setUnitNO(java.lang.String unitNO) { this.unitNO = unitNO; } private java.lang.Object __equalsCalc = null; public synchronized boolean equals(java.lang.Object obj) { if (!(obj instanceof CancelReceiptStockVO)) return false; CancelReceiptStockVO other = (CancelReceiptStockVO) obj; if (obj == null) return false; if (this == obj) return true; if (__equalsCalc != null) { return (__equalsCalc == obj); } __equalsCalc = obj; boolean _equals; _equals = super.equals(obj) && ((this.endNO==null && other.getEndNO()==null) || (this.endNO!=null && this.endNO.equals(other.getEndNO()))) && this.pieceCount == other.getPieceCount() && ((this.procTM==null && other.getProcTM()==null) || (this.procTM!=null && this.procTM.equals(other.getProcTM()))) && this.recedePrice == other.getRecedePrice() && ((this.receiverName==null && other.getReceiverName()==null) || (this.receiverName!=null && this.receiverName.equals(other.getReceiverName()))) && ((this.rtNO==null && other.getRtNO()==null) || (this.rtNO!=null && this.rtNO.equals(other.getRtNO()))) && ((this.startNO==null && other.getStartNO()==null) || (this.startNO!=null && this.startNO.equals(other.getStartNO()))) && ((this.stockHouseName==null && other.getStockHouseName()==null) || (this.stockHouseName!=null && this.stockHouseName.equals(other.getStockHouseName()))) && ((this.unitNO==null && other.getUnitNO()==null) || (this.unitNO!=null && this.unitNO.equals(other.getUnitNO()))); __equalsCalc = null; return _equals; } private boolean __hashCodeCalc = false; public synchronized int hashCode() { if (__hashCodeCalc) { return 0; } __hashCodeCalc = true; int _hashCode = super.hashCode(); if (getEndNO() != null) { _hashCode += getEndNO().hashCode(); } _hashCode += getPieceCount(); if (getProcTM() != null) { _hashCode += getProcTM().hashCode(); } _hashCode += new Double(getRecedePrice()).hashCode(); if (getReceiverName() != null) { _hashCode += getReceiverName().hashCode(); } if (getRtNO() != null) { _hashCode += getRtNO().hashCode(); } if (getStartNO() != null) { _hashCode += getStartNO().hashCode(); } if (getStockHouseName() != null) { _hashCode += getStockHouseName().hashCode(); } if (getUnitNO() != null) { _hashCode += getUnitNO().hashCode(); } __hashCodeCalc = false; return _hashCode; } // Type metadata private static org.apache.axis.description.TypeDesc typeDesc = new org.apache.axis.description.TypeDesc(CancelReceiptStockVO.class, true); static { typeDesc.setXmlType(new javax.xml.namespace.QName("http://vo.webservices.gfmis.todaytech.com", "CancelReceiptStockVO")); org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("endNO"); elemField.setXmlName(new javax.xml.namespace.QName("", "endNO")); elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string")); elemField.setNillable(true); typeDesc.addFieldDesc(elemField); elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("pieceCount"); elemField.setXmlName(new javax.xml.namespace.QName("", "pieceCount")); elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "int")); elemField.setNillable(false); typeDesc.addFieldDesc(elemField); elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("procTM"); elemField.setXmlName(new javax.xml.namespace.QName("", "procTM")); elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string")); elemField.setNillable(true); typeDesc.addFieldDesc(elemField); elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("recedePrice"); elemField.setXmlName(new javax.xml.namespace.QName("", "recedePrice")); elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "double")); elemField.setNillable(false); typeDesc.addFieldDesc(elemField); elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("receiverName"); elemField.setXmlName(new javax.xml.namespace.QName("", "receiverName")); elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string")); elemField.setNillable(true); typeDesc.addFieldDesc(elemField); elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("rtNO"); elemField.setXmlName(new javax.xml.namespace.QName("", "rtNO")); elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string")); elemField.setNillable(true); typeDesc.addFieldDesc(elemField); elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("startNO"); elemField.setXmlName(new javax.xml.namespace.QName("", "startNO")); elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string")); elemField.setNillable(true); typeDesc.addFieldDesc(elemField); elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("stockHouseName"); elemField.setXmlName(new javax.xml.namespace.QName("", "stockHouseName")); elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string")); elemField.setNillable(true); typeDesc.addFieldDesc(elemField); elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("unitNO"); elemField.setXmlName(new javax.xml.namespace.QName("", "unitNO")); elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string")); elemField.setNillable(true); typeDesc.addFieldDesc(elemField); } /** * Return type metadata object */ public static org.apache.axis.description.TypeDesc getTypeDesc() { return typeDesc; } /** * Get Custom Serializer */ public static org.apache.axis.encoding.Serializer getSerializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.BeanSerializer( _javaType, _xmlType, typeDesc); } /** * Get Custom Deserializer */ public static org.apache.axis.encoding.Deserializer getDeserializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.BeanDeserializer( _javaType, _xmlType, typeDesc); } }
6788e782fe2dd6fd57924da5c684f8202805e31f
a1780458ec351ac03e1d77f4425c4cdbba38f013
/dbflute-jdk15-example/src/main/java/com/example/dbflute/spring/dbflute/cbean/cq/bs/BsVendor$DollarCQ.java
fcb841aa6eba50a1f5967e52375e5dd0d395a99c
[]
no_license
seasarorg/dbflute-jdk15
4ed513486277c5f79ed2de5ff4a6eeeaaf84e0ff
ee920d7580d89725ded68c958b6788da0d574bd2
refs/heads/master
2018-12-28T05:27:19.388357
2014-01-18T11:49:23
2014-01-18T11:49:23
null
0
0
null
null
null
null
UTF-8
Java
false
false
10,656
java
/* * Copyright(c) DBFlute TestCo.,TestLtd. All Rights Reserved. */ package com.example.dbflute.spring.dbflute.cbean.cq.bs; import java.util.Map; import org.seasar.dbflute.cbean.*; import org.seasar.dbflute.cbean.cvalue.ConditionValue; import org.seasar.dbflute.cbean.sqlclause.SqlClause; import org.seasar.dbflute.exception.IllegalConditionBeanOperationException; import com.example.dbflute.spring.dbflute.cbean.cq.ciq.*; import com.example.dbflute.spring.dbflute.cbean.*; import com.example.dbflute.spring.dbflute.cbean.cq.*; /** * The base condition-query of VENDOR_$_DOLLAR. * @author DBFlute(AutoGenerator) */ public class BsVendor$DollarCQ extends AbstractBsVendor$DollarCQ { // =================================================================================== // Attribute // ========= protected Vendor$DollarCIQ _inlineQuery; // =================================================================================== // Constructor // =========== public BsVendor$DollarCQ(ConditionQuery childQuery, SqlClause sqlClause, String aliasName, int nestLevel) { super(childQuery, sqlClause, aliasName, nestLevel); } // =================================================================================== // InlineView/OrClause // =================== /** * Prepare InlineView query. <br /> * {select ... from ... left outer join (select * from VENDOR_$_DOLLAR) where FOO = [value] ...} * <pre> * cb.query().queryMemberStatus().<span style="color: #FD4747">inline()</span>.setFoo...; * </pre> * @return The condition-query for InlineView query. (NotNull) */ public Vendor$DollarCIQ inline() { if (_inlineQuery == null) { _inlineQuery = xcreateCIQ(); } _inlineQuery.xsetOnClause(false); return _inlineQuery; } protected Vendor$DollarCIQ xcreateCIQ() { Vendor$DollarCIQ ciq = xnewCIQ(); ciq.xsetBaseCB(_baseCB); return ciq; } protected Vendor$DollarCIQ xnewCIQ() { return new Vendor$DollarCIQ(xgetReferrerQuery(), xgetSqlClause(), xgetAliasName(), xgetNestLevel(), this); } /** * Prepare OnClause query. <br /> * {select ... from ... left outer join VENDOR_$_DOLLAR on ... and FOO = [value] ...} * <pre> * cb.query().queryMemberStatus().<span style="color: #FD4747">on()</span>.setFoo...; * </pre> * @return The condition-query for OnClause query. (NotNull) * @throws IllegalConditionBeanOperationException When this condition-query is base query. */ public Vendor$DollarCIQ on() { if (isBaseQuery()) { throw new IllegalConditionBeanOperationException("OnClause for local table is unavailable!"); } Vendor$DollarCIQ inlineQuery = inline(); inlineQuery.xsetOnClause(true); return inlineQuery; } // =================================================================================== // Query // ===== protected ConditionValue _vendor$DollarId; public ConditionValue getVendor$DollarId() { if (_vendor$DollarId == null) { _vendor$DollarId = nCV(); } return _vendor$DollarId; } protected ConditionValue getCValueVendor$DollarId() { return getVendor$DollarId(); } /** * Add order-by as ascend. <br /> * VENDOR_$_DOLLAR_ID: {PK, NotNull, INTEGER(10)} * @return this. (NotNull) */ public BsVendor$DollarCQ addOrderBy_Vendor$DollarId_Asc() { regOBA("VENDOR_$_DOLLAR_ID"); return this; } /** * Add order-by as descend. <br /> * VENDOR_$_DOLLAR_ID: {PK, NotNull, INTEGER(10)} * @return this. (NotNull) */ public BsVendor$DollarCQ addOrderBy_Vendor$DollarId_Desc() { regOBD("VENDOR_$_DOLLAR_ID"); return this; } protected ConditionValue _vendor$DollarName; public ConditionValue getVendor$DollarName() { if (_vendor$DollarName == null) { _vendor$DollarName = nCV(); } return _vendor$DollarName; } protected ConditionValue getCValueVendor$DollarName() { return getVendor$DollarName(); } /** * Add order-by as ascend. <br /> * VENDOR_$_DOLLAR_NAME: {VARCHAR(32)} * @return this. (NotNull) */ public BsVendor$DollarCQ addOrderBy_Vendor$DollarName_Asc() { regOBA("VENDOR_$_DOLLAR_NAME"); return this; } /** * Add order-by as descend. <br /> * VENDOR_$_DOLLAR_NAME: {VARCHAR(32)} * @return this. (NotNull) */ public BsVendor$DollarCQ addOrderBy_Vendor$DollarName_Desc() { regOBD("VENDOR_$_DOLLAR_NAME"); return this; } // =================================================================================== // SpecifiedDerivedOrderBy // ======================= /** * Add order-by for specified derived column as ascend. * <pre> * cb.specify().derivedPurchaseList().max(new SubQuery&lt;PurchaseCB&gt;() { * public void query(PurchaseCB subCB) { * subCB.specify().columnPurchaseDatetime(); * } * }, <span style="color: #FD4747">aliasName</span>); * <span style="color: #3F7E5E">// order by [alias-name] asc</span> * cb.<span style="color: #FD4747">addSpecifiedDerivedOrderBy_Asc</span>(<span style="color: #FD4747">aliasName</span>); * </pre> * @param aliasName The alias name specified at (Specify)DerivedReferrer. (NotNull) * @return this. (NotNull) */ public BsVendor$DollarCQ addSpecifiedDerivedOrderBy_Asc(String aliasName) { registerSpecifiedDerivedOrderBy_Asc(aliasName); return this; } /** * Add order-by for specified derived column as descend. * <pre> * cb.specify().derivedPurchaseList().max(new SubQuery&lt;PurchaseCB&gt;() { * public void query(PurchaseCB subCB) { * subCB.specify().columnPurchaseDatetime(); * } * }, <span style="color: #FD4747">aliasName</span>); * <span style="color: #3F7E5E">// order by [alias-name] desc</span> * cb.<span style="color: #FD4747">addSpecifiedDerivedOrderBy_Desc</span>(<span style="color: #FD4747">aliasName</span>); * </pre> * @param aliasName The alias name specified at (Specify)DerivedReferrer. (NotNull) * @return this. (NotNull) */ public BsVendor$DollarCQ addSpecifiedDerivedOrderBy_Desc(String aliasName) { registerSpecifiedDerivedOrderBy_Desc(aliasName); return this; } // =================================================================================== // Union Query // =========== protected void reflectRelationOnUnionQuery(ConditionQuery baseQueryAsSuper, ConditionQuery unionQueryAsSuper) { } // =================================================================================== // Foreign Query // ============= // =================================================================================== // ScalarCondition // =============== protected Map<String, Vendor$DollarCQ> _scalarConditionMap; public Map<String, Vendor$DollarCQ> getScalarCondition() { return _scalarConditionMap; } public String keepScalarCondition(Vendor$DollarCQ subQuery) { if (_scalarConditionMap == null) { _scalarConditionMap = newLinkedHashMap(); } String key = "subQueryMapKey" + (_scalarConditionMap.size() + 1); _scalarConditionMap.put(key, subQuery); return "scalarCondition." + key; } // =================================================================================== // MyselfExists // ============ protected Map<String, Vendor$DollarCQ> _myselfExistsMap; public Map<String, Vendor$DollarCQ> getMyselfExists() { return _myselfExistsMap; } public String keepMyselfExists(Vendor$DollarCQ subQuery) { if (_myselfExistsMap == null) { _myselfExistsMap = newLinkedHashMap(); } String key = "subQueryMapKey" + (_myselfExistsMap.size() + 1); _myselfExistsMap.put(key, subQuery); return "myselfExists." + key; } // =================================================================================== // MyselfInScope // ============= protected Map<String, Vendor$DollarCQ> _myselfInScopeMap; public Map<String, Vendor$DollarCQ> getMyselfInScope() { return _myselfInScopeMap; } public String keepMyselfInScope(Vendor$DollarCQ subQuery) { if (_myselfInScopeMap == null) { _myselfInScopeMap = newLinkedHashMap(); } String key = "subQueryMapKey" + (_myselfInScopeMap.size() + 1); _myselfInScopeMap.put(key, subQuery); return "myselfInScope." + key; } // =================================================================================== // Very Internal // ============= // very internal (for suppressing warn about 'Not Use Import') protected String xCB() { return Vendor$DollarCB.class.getName(); } protected String xCQ() { return Vendor$DollarCQ.class.getName(); } protected String xMap() { return Map.class.getName(); } }
a8a8f6687d4653d3db549d50bcc59f3bd5e236ac
163d4c4fe4f189f25fd9ef35c868970b0ad5b7c0
/src/main/java/com/assignments/service/users/DemographicService.java
9c62a3ca808522706280a4a0d7c94782b2bbfd24
[]
no_license
Saaligha/Assignment7
070eed3b9a1cc6377a0bcae185bf757a493d391a
e071bbeace0e2a954f6e8eebbf6c139eda908da0
refs/heads/master
2022-05-31T03:22:37.850513
2019-10-20T15:22:46
2019-10-20T15:22:46
183,959,682
0
0
null
null
null
null
UTF-8
Java
false
false
249
java
package za.ac.cput.service.users; import za.ac.cput.domain.users.Demographic; import za.ac.cput.service.IService; import java.util.Set; public interface DemographicService extends IService<Demographic, String> { Set<Demographic> getAll(); }
493b4bd5c6a30d8ebee89aa07e97fb8528b7a4de
1661886bc7ec4e827acdd0ed7e4287758a4ccc54
/srv_unip_pub/src/main/java/com/sa/unip/app/srv/common/ctrlmodel/DataSyncInDefaultDRBarModel.java
bfb61af7d16b7fdd19d7e79e35c7670d9b6e32d1
[ "MIT" ]
permissive
zhanght86/iBizSys_unip
baafb4a96920e8321ac6a1b68735bef376b50946
a22b15ebb069c6a7432e3401bdd500a3ca37250e
refs/heads/master
2020-04-25T21:20:23.830300
2018-01-26T06:08:28
2018-01-26T06:08:28
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,671
java
/** * iBizSys 5.0 机器人生产代码(不要直接修改当前代码) * http://www.ibizsys.net */ package com.sa.unip.app.srv.common.ctrlmodel; import java.util.ArrayList; import java.util.List; import net.ibizsys.paas.util.StringHelper; import net.ibizsys.paas.web.AjaxActionResult; import net.ibizsys.paas.web.WebContext; import net.ibizsys.paas.util.GlobalContext; import net.ibizsys.paas.core.IDEDataSetCond; import net.ibizsys.paas.core.DEDataSetCond; import net.ibizsys.paas.core.DEDataSetFetchContext; import net.ibizsys.paas.db.DBFetchResult; import net.ibizsys.paas.web.WebContext; import net.ibizsys.paas.util.DataTypeHelper; import net.ibizsys.paas.data.IDataObject; import net.ibizsys.paas.datamodel.DataItemModel; import net.ibizsys.paas.datamodel.DataItemParamModel; import net.ibizsys.paas.entity.EntityFieldError; import net.ibizsys.paas.entity.EntityError; import net.ibizsys.paas.demodel.IDataEntityModel; import net.ibizsys.paas.demodel.DEModelGlobal; import net.ibizsys.paas.control.drctrl.DRCtrlItem; import net.ibizsys.paas.control.drctrl.DRCtrlRootItem; /** * 实体[数据同步接收队列]数据关系栏[drbar]部件模型 */ public class DataSyncInDefaultDRBarModel extends net.ibizsys.paas.ctrlmodel.DRBarModelBase { public DataSyncInDefaultDRBarModel() { super(); } @Override protected void onInit() throws Exception { super.onInit(); } private net.ibizsys.psrt.srv.common.demodel.DataSyncInDEModel dataSyncInDEModel; protected net.ibizsys.psrt.srv.common.demodel.DataSyncInDEModel getDataSyncInDEModel() { if(this.dataSyncInDEModel==null) { try { this.dataSyncInDEModel = (net.ibizsys.psrt.srv.common.demodel.DataSyncInDEModel)DEModelGlobal.getDEModel("net.ibizsys.psrt.srv.common.demodel.DataSyncInDEModel"); } catch(Exception ex) { } } return this.dataSyncInDEModel; } @Override public IDataEntityModel getDEModel() { return this.getDataSyncInDEModel(); } /** * 准备数据关系根节点 * @param drCtrlRootItem * @throws Exception */ @Override protected void onPrepareRootItem(DRCtrlRootItem drCtrlRootItem) throws Exception { //添加 数据同步接收队列 DRCtrlItem drCtrlItem0 = drCtrlRootItem.addItem("form",""); drCtrlItem0.setText("数据同步接收队列"); drCtrlItem0.setDRViewId(""); drCtrlItem0.setExpanded(true); drCtrlItem0.setTextLanResTag(""); drCtrlItem0.setIconPath(""); drCtrlItem0.setIconCls(""); drCtrlItem0.setEnableMode("ALL"); } }
30ca9ddaa4900b1201ff1346bef15f71ea891ae8
cc109222071be2d7286b60ae823cdedd6916a735
/Ticketing_Management_System/src/com/tolo/tabcs/server/action/AddBranchAction.java
514f122b9b46c695cd9d1aa019eeac00e62adb3a
[]
no_license
2724869229/Ticket-management-System
e0283d9978aae504dc198ab8d91cd7d60012d114
e49ce2c9e4dc82d84387cb81acdd7e99855d0fcd
refs/heads/master
2021-05-30T09:57:45.102094
2014-08-31T05:09:29
2014-08-31T05:09:29
null
0
0
null
null
null
null
UTF-8
Java
false
false
659
java
package com.tolo.tabcs.server.action; import com.tolo.tabcs.common.entity.Branch; import com.tolo.tabcs.common.pro.Request; import com.tolo.tabcs.common.pro.Response; import com.tolo.tabcs.server.dao.BranchDao; import com.tolo.tabcs.server.daoimp.BranchDaoImp; import com.tolo.tabcs.server.service.ServerAction; /** * 添加营业网点 * * @author hyj * */ public class AddBranchAction extends ServerAction { public void doAction(Request req, Response res) { Branch branch = (Branch) req.getData("添加网点"); BranchDao branchdao = new BranchDaoImp(); boolean r = branchdao.addBranch(branch); res.addData("添加网点状态", r); } }
a5ae3fde385246979239b43a81edb89bf3b46312
999b17d0eef77578819d66865138f36a0f4c2ef0
/src/main/java/com/stock/mgmt/database/LoginDAO.java
fdff9b7828697a129abfe05699e7b02e411e296a
[]
no_license
sleshatuladhar/StockManagement
b18afc506c3111da04c159542a7e2644e2b6569f
cd3940dedc69f54019c04b228d6d6e7c00cbc4c0
refs/heads/master
2020-04-07T13:27:52.019385
2018-11-20T15:17:04
2018-11-20T15:17:04
158,408,442
0
0
null
null
null
null
UTF-8
Java
false
false
2,576
java
package com.stock.mgmt.database; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import com.stock.mgmt.entity.User; public class LoginDAO { private static final String VALIDATE_QUERY = "SELECT count(*) FROM `user` " + ""; public static boolean validate(String username, String password) { Connection con = DatabaseConnector.getConnection(); Statement statement; try { statement = con.createStatement(); ResultSet result = statement.executeQuery( VALIDATE_QUERY + " where username='" + username + "' and password='" + password + "'"); result.next(); int count = result.getInt(1); if (count == 1) { return true; } } catch (SQLException e) { e.printStackTrace(); } return false; } public static void register(User user) { Connection con = DatabaseConnector.getConnection(); StringBuilder builder = new StringBuilder(); builder.append(" INSERT INTO user "); builder.append(" (name, address_id, phone_number, email, dob, username, password )"); builder.append(" VALUES ( "); builder.append("'"); builder.append(user.getName()); builder.append("', "); builder.append("'"); builder.append(user.getAddressId()); builder.append("', "); builder.append("'"); builder.append(user.getPhone()); builder.append("', "); builder.append("'"); builder.append(user.getEmail()); builder.append("',"); DateFormat dateFormat = new SimpleDateFormat("yyyy-mm-dd"); //to convert Date to String, use format method of SimpleDateFormat class. String strDate = dateFormat.format(user.getDob()); builder.append("'"); builder.append(strDate); builder.append("',"); builder.append("'"); builder.append(user.getUsername()); builder.append("',"); builder.append("'"); builder.append(user.getPassword()); builder.append("' )"); String query = builder.toString(); System.out.println(query); Statement statement; try { statement = con.createStatement(); statement.executeUpdate(query); } catch (SQLException e) { e.printStackTrace(); } } /*public static void main(String[] args) { User user = new User(); user.setAddressId("1"); user.setDob(new Date()); user.setEmail("[email protected]"); user.setName("Milan"); user.setUsername("milan"); user.setPassword("sdfdsf"); user.setPhone("9878767776"); new LoginDAO().register(user); }*/ }
46c3f98280a203eabd282382a0b07c4987260c02
ce8b7326331a775c27e92575cb17bf0a4a019d99
/AlchemistAppFW/plugins/cordova-plugin-local-notification/src/android/notification/Notification.java
a35c0e2b445caa37cba71e5be805bb6beaf541bc
[ "Apache-2.0" ]
permissive
mtsthibau/AlchemistAppFW
7bc999d909e77869ef8abf1a997eae2d57a45d62
53378aba35ea727d26301c1a9c9c583cf2bc1890
refs/heads/master
2021-11-04T17:02:29.569399
2019-04-28T00:32:20
2019-04-28T00:32:20
61,774,068
1
0
null
null
null
null
UTF-8
Java
false
false
12,392
java
/* * Apache 2.0 License * * Copyright (c) Sebastian Katzer 2017 * * This file contains Original Code and/or Modifications of Original Code * as defined in and that are subject to the Apache License * Version 2.0 (the 'License'). You may not use this file except in * compliance with the License. Please obtain a copy of the License at * http://opensource.org/licenses/Apache-2.0/ and read it before using this * file. * * The Original Code and all software distributed under the License are * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. * Please see the License for the specific language governing rights and * limitations under the License. */ package de.appplant.cordova.plugin.notification; import android.app.AlarmManager; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.service.notification.StatusBarNotification; import android.support.v4.app.NotificationCompat; import android.support.v4.util.ArraySet; import android.support.v4.util.Pair; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Set; import static android.app.AlarmManager.RTC; import static android.app.AlarmManager.RTC_WAKEUP; import static android.app.PendingIntent.FLAG_CANCEL_CURRENT; import static android.support.v4.app.NotificationManagerCompat.IMPORTANCE_MAX; import static android.support.v4.app.NotificationManagerCompat.IMPORTANCE_MIN; /** * Wrapper class around OS notification class. Handles basic operations * like show, delete, cancel for a single local notification instance. */ public final class Notification { // Used to differ notifications by their life cycle state public enum Type { ALL, SCHEDULED, TRIGGERED } // Extra key for the id public static final String EXTRA_ID = "NOTIFICATION_ID"; // Extra key for the update flag public static final String EXTRA_UPDATE = "NOTIFICATION_UPDATE"; // Key for private preferences static final String PREF_KEY_ID = "NOTIFICATION_ID"; // Key for private preferences private static final String PREF_KEY_PID = "NOTIFICATION_PID"; // Application context passed by constructor private final Context context; // Notification options passed by JS private final Options options; // Builder with full configuration private final NotificationCompat.Builder builder; /** * Constructor * * @param context Application context. * @param options Parsed notification options. * @param builder Pre-configured notification builder. */ Notification (Context context, Options options, NotificationCompat.Builder builder) { this.context = context; this.options = options; this.builder = builder; } /** * Constructor * * @param context Application context. * @param options Parsed notification options. */ public Notification(Context context, Options options) { this.context = context; this.options = options; this.builder = null; } /** * Get application context. */ public Context getContext () { return context; } /** * Get notification options. */ public Options getOptions () { return options; } /** * Get notification ID. */ public int getId () { return options.getId(); } /** * If it's a repeating notification. */ private boolean isRepeating () { return getOptions().getTrigger().has("every"); } /** * Notification type can be one of triggered or scheduled. */ public Type getType () { StatusBarNotification[] toasts = getNotMgr().getActiveNotifications(); int id = getId(); for (StatusBarNotification toast : toasts) { if (toast.getId() == id) { return Type.TRIGGERED; } } return Type.SCHEDULED; } /** * Schedule the local notification. * * @param request Set of notification options. * @param receiver Receiver to handle the trigger event. */ void schedule(Request request, Class<?> receiver) { List<Pair<Date, Intent>> intents = new ArrayList<Pair<Date, Intent>>(); Set<String> ids = new ArraySet<String>(); AlarmManager mgr = getAlarmMgr(); do { Date date = request.getTriggerDate(); if (date == null) continue; Intent intent = new Intent(context, receiver) .setAction(PREF_KEY_ID + request.getIdentifier()) .putExtra(Notification.EXTRA_ID, options.getId()) .putExtra(Request.EXTRA_OCCURRENCE, request.getOccurrence()); ids.add(intent.getAction()); intents.add(new Pair<Date, Intent>(date, intent)); } while (request.moveNext()); if (intents.isEmpty()) return; persist(ids); Intent last = intents.get(intents.size() - 1).second; last.putExtra(Request.EXTRA_LAST, true); for (Pair<Date, Intent> pair : intents) { Date date = pair.first; long time = date.getTime(); Intent intent = pair.second; if (!date.after(new Date()) && trigger(intent, receiver)) continue; PendingIntent pi = PendingIntent.getBroadcast( context, 0, intent, FLAG_CANCEL_CURRENT); try { switch (options.getPriority()) { case IMPORTANCE_MIN: mgr.setExact(RTC, time, pi); break; case IMPORTANCE_MAX: mgr.setExactAndAllowWhileIdle(RTC_WAKEUP, time, pi); break; default: mgr.setExact(RTC_WAKEUP, time, pi); break; } } catch (Exception ignore) { // Samsung devices have a known bug where a 500 alarms limit // can crash the app } } } /** * Trigger local notification specified by options. * * @param intent The intent to broadcast. * @param cls The broadcast class. */ private boolean trigger (Intent intent, Class<?> cls) { BroadcastReceiver receiver; try { receiver = (BroadcastReceiver) cls.newInstance(); } catch (InstantiationException e) { return false; } catch (IllegalAccessException e) { return false; } receiver.onReceive(context, intent); return true; } /** * Clear the local notification without canceling repeating alarms. */ public void clear() { getNotMgr().cancel(getId()); if (isRepeating()) return; unpersist(); } /** * Cancel the local notification. * * Create an intent that looks similar, to the one that was registered * using schedule. Making sure the notification id in the action is the * same. Now we can search for such an intent using the 'getService' * method and cancel it. */ public void cancel() { SharedPreferences prefs = getPrefs(PREF_KEY_PID); String id = options.getIdentifier(); Set<String> actions = prefs.getStringSet(id, null); unpersist(); getNotMgr().cancel(options.getId()); if (actions == null) return; for (String action : actions) { Intent intent = new Intent(action); PendingIntent pi = PendingIntent.getBroadcast( context, 0, intent, 0); if (pi != null) { getAlarmMgr().cancel(pi); } } } /** * Present the local notification to user. */ public void show() { if (builder == null) return; grantPermissionToPlaySoundFromExternal(); getNotMgr().notify(getId(), builder.build()); } /** * Update the notification properties. * * @param updates The properties to update. * @param receiver Receiver to handle the trigger event. */ void update (JSONObject updates, Class<?> receiver) { mergeJSONObjects(updates); persist(null); if (getType() != Type.TRIGGERED) return; Intent intent = new Intent(context, receiver) .setAction(PREF_KEY_ID + options.getId()) .putExtra(Notification.EXTRA_ID, options.getId()) .putExtra(Notification.EXTRA_UPDATE, true); trigger(intent, receiver); } /** * Encode options to JSON. */ public String toString() { JSONObject dict = options.getDict(); JSONObject json = new JSONObject(); try { json = new JSONObject(dict.toString()); } catch (JSONException e) { e.printStackTrace(); } return json.toString(); } /** * Persist the information of this notification to the Android Shared * Preferences. This will allow the application to restore the notification * upon device reboot, app restart, retrieve notifications, aso. * * @param ids List of intent actions to persist. */ private void persist (Set<String> ids) { String id = options.getIdentifier(); SharedPreferences.Editor editor; editor = getPrefs(PREF_KEY_ID).edit(); editor.putString(id, options.toString()); editor.apply(); if (ids == null) return; editor = getPrefs(PREF_KEY_PID).edit(); editor.putStringSet(id, ids); editor.apply(); } /** * Remove the notification from the Android shared Preferences. */ private void unpersist () { String[] keys = { PREF_KEY_ID, PREF_KEY_PID }; String id = options.getIdentifier(); SharedPreferences.Editor editor; for (String key : keys) { editor = getPrefs(key).edit(); editor.remove(id); editor.apply(); } } /** * Since Android 7 the app will crash if an external process has no * permission to access the referenced sound file. */ private void grantPermissionToPlaySoundFromExternal() { if (builder == null) return; String sound = builder.getExtras().getString(Options.EXTRA_SOUND); Uri soundUri = Uri.parse(sound); context.grantUriPermission( "com.android.systemui", soundUri, Intent.FLAG_GRANT_READ_URI_PERMISSION); } /** * Merge two JSON objects. */ private void mergeJSONObjects (JSONObject updates) { JSONObject dict = options.getDict(); Iterator it = updates.keys(); while (it.hasNext()) { try { String key = (String)it.next(); dict.put(key, updates.opt(key)); } catch (JSONException e) { e.printStackTrace(); } } } /** * Shared private preferences for the application. */ private SharedPreferences getPrefs (String key) { return context.getSharedPreferences(key, Context.MODE_PRIVATE); } /** * Notification manager for the application. */ private NotificationManager getNotMgr () { return (NotificationManager) context .getSystemService(Context.NOTIFICATION_SERVICE); } /** * Alarm manager for the application. */ private AlarmManager getAlarmMgr () { return (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); } }
a57b109fb27891582c3d877ba6bcc49e75d28d46
8ead90decf9c9d24134eb74f8738772e601725fe
/src/HeatIndexDisplay.java
9da58be7fc3cafdf4072aeb3f620b6d58f2ef15c
[]
no_license
JonnyFucker/DesignPattern-Observer
8e64538cfda67553755b01049c921b6f51993bdf
6d010440a7351acd192173f196a1ebb89b4208ba
refs/heads/master
2021-04-15T16:19:16.764675
2016-07-09T15:48:18
2016-07-09T15:48:18
62,956,601
0
0
null
null
null
null
UTF-8
Java
false
false
1,068
java
public class HeatIndexDisplay implements Observer, DisplayElement { float heatIndex = 0.0f; private Subject weatherData; public HeatIndexDisplay(Subject weatherData) { this.weatherData = weatherData; weatherData.registerObserver(this); } public void update(float t, float rh, float pressure) { heatIndex = computeHeatIndex(t, rh); display(); } private float computeHeatIndex(float t, float rh) { float index = (float)((16.923 + (0.185212 * t) + (5.37941 * rh) - (0.100254 * t * rh) + (0.00941695 * (t * t)) + (0.00728898 * (rh * rh)) + (0.000345372 * (t * t * rh)) - (0.000814971 * (t * rh * rh)) + (0.0000102102 * (t * t * rh * rh)) - (0.000038646 * (t * t * t)) + (0.0000291583 * (rh * rh * rh)) + (0.00000142721 * (t * t * t * rh)) + (0.000000197483 * (t * rh * rh * rh)) - (0.0000000218429 * (t * t * t * rh * rh)) + 0.000000000843296 * (t * t * rh * rh * rh)) - (0.0000000000481975 * (t * t * t * rh * rh * rh))); return index; } public void display() { System.out.println("Heat index is " + heatIndex); } }
e325a7d1e1ef0c5ace1a8b98aedf36d1869ab202
b280a34244a58fddd7e76bddb13bc25c83215010
/scmv6/core-base-public/src/main/java/com/smate/core/base/pub/dao/pdwh/PdwhFullTextImageDao.java
98641464b94805d033259f934d3f97f50621703b
[]
no_license
hzr958/myProjects
910d7b7473c33ef2754d79e67ced0245e987f522
d2e8f61b7b99a92ffe19209fcda3c2db37315422
refs/heads/master
2022-12-24T16:43:21.527071
2019-08-16T01:46:18
2019-08-16T01:46:18
202,512,072
2
3
null
2022-12-16T05:31:05
2019-08-15T09:21:04
Java
UTF-8
Java
false
false
1,636
java
package com.smate.core.base.pub.dao.pdwh; import java.math.BigDecimal; import org.springframework.stereotype.Repository; import com.smate.core.base.pub.model.pdwh.PdwhFullTextImage; import com.smate.core.base.utils.data.PdwhHibernateDao; /** * * @author LIJUN * */ @Repository public class PdwhFullTextImageDao extends PdwhHibernateDao<PdwhFullTextImage, Long> { public PdwhFullTextImage getPubFulltextByFiledId(Long fulltextFileId) { String hql = "from PdwhFullTextImage t where t.fileId=:fulltextFileId"; return (PdwhFullTextImage) super.createQuery(hql).setParameter("fulltextFileId", fulltextFileId).uniqueResult(); } /** * 获取全文图片地址 * * @param pubId * @return */ public String getPubFulltextImage(Long pubId) { // cnki全文不显示 String hqlSourceDb = "select count(1) from PdwhPubSourceDb t where t.pubId =:pubId and t.cnki = 1"; Long count = (Long) super.createQuery(hqlSourceDb).setParameter("pubId", pubId).uniqueResult(); if (count >= 1) { return null; } String hql = "select t.imagePath from PdwhFullTextImage t where t.pubId=:pubId"; return (String) super.createQuery(hql).setParameter("pubId", pubId).uniqueResult(); } /** * 记录是否存在 * * @param pdwhPubId * @return */ public boolean isExist(Long pubId) { String hql = " select count(1) from PdwhFullTextImage t where t.pubId=:pdwhPubId"; BigDecimal count = (BigDecimal) super.createQuery(hql).setParameter("pubId", pubId).uniqueResult(); if (count.intValue() > 0) { return true; } else { return false; } } }
eb569191552819b18f394ade07ee31043f601c52
2d8daca2f394423e00b772fe3563d5d47b365826
/learn-modules/learn-store/learn-store-shoppingcart/learn-store-shoppingcart-dao/src/main/java/me/own/learn/store/shoppingcart/po/ShoppingCart.java
7e435a67938658253022e755a9a7425d129faacf
[]
no_license
xudongye/learn
07601d1f57cf52ff63a70d83f30670e38fc9cb77
dd88d68cf45014f68210c24982b994d21dd850cc
refs/heads/master
2022-07-12T23:47:06.073893
2020-04-17T09:23:38
2020-04-17T09:23:45
181,639,796
0
0
null
2022-06-25T07:28:37
2019-04-16T07:41:27
Java
UTF-8
Java
false
false
1,253
java
package me.own.learn.store.shoppingcart.po; import me.own.commons.base.model.BaseEntity; import javax.persistence.*; @Entity @Table(name = "learn_store_shoppingcart") public class ShoppingCart extends BaseEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private Long customerId; private Long productId; private Integer quantity; //添加到购物车初始单价 private Double sourceUnitPrice; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getCustomerId() { return customerId; } public void setCustomerId(Long customerId) { this.customerId = customerId; } public Long getProductId() { return productId; } public void setProductId(Long productId) { this.productId = productId; } public Integer getQuantity() { return quantity; } public void setQuantity(Integer quantity) { this.quantity = quantity; } public Double getSourceUnitPrice() { return sourceUnitPrice; } public void setSourceUnitPrice(Double sourceUnitPrice) { this.sourceUnitPrice = sourceUnitPrice; } }
d8d440ac7901c45026f183e1998b70577de444e4
4f7df07fe61d6ce30c113068853b7d88565a73e0
/src/main/java/kiba/plasmids/items/ItemMedKit.java
1191eefd15cd5d92d0e7a43ae10e4fdb8e363ceb
[]
no_license
sekwah41/Practical-Plasmids
5126d2957e86adbcb29278f0730e2ec0b647daca
c293af2ef34c7c1c37fa088788f4cce2abaccab5
refs/heads/master
2023-04-07T02:33:25.974150
2016-11-14T17:36:21
2016-11-14T17:36:21
73,733,939
1
0
null
2023-04-04T01:40:33
2016-11-14T18:19:47
Java
UTF-8
Java
false
false
1,028
java
package kiba.plasmids.items; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.MobEffects; import net.minecraft.item.ItemStack; import net.minecraft.potion.PotionEffect; import net.minecraft.util.ActionResult; import net.minecraft.util.EnumHand; import net.minecraft.world.World; public class ItemMedKit extends BaseItem { public ItemMedKit() { super("med_kit"); this.setMaxDamage(10); } @Override public ActionResult<ItemStack> onItemRightClick(ItemStack itemStackIn, World worldIn, EntityPlayer playerIn, EnumHand hand) { if (itemStackIn.getItemDamage() == 10) { playerIn.addPotionEffect(new PotionEffect(MobEffects.INSTANT_HEALTH, 1, 3, false, false)); --itemStackIn.stackSize; } else playerIn.addPotionEffect(new PotionEffect(MobEffects.INSTANT_HEALTH, 1, 3, false, false)); itemStackIn.damageItem(+1, playerIn); return super.onItemRightClick(itemStackIn, worldIn, playerIn, hand); } }
58d478f484bdcd31861676876f14aa424c5f8de0
cd1e60af5201413ddbdaa56c58e1d0600bc4af35
/ask/kuaida-main/src/main/java/com/izhubo/web/vo/AppLiveListVO.java
c540fd90ab9630ae8224b762b9285c113d9e06e6
[]
no_license
franywhy/projects
6b3fe268709c7239536da802e57f9f1630688061
965b2b0938f8c3620299b52055035f522559fa5c
refs/heads/master
2020-04-18T01:14:13.551295
2019-01-23T02:49:00
2019-01-23T02:49:00
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,151
java
package com.izhubo.web.vo; import com.wordnik.swagger.annotations.ApiModelProperty; public class AppLiveListVO { @ApiModelProperty(value = "_id") private int _id; @ApiModelProperty(value = "是否預約 0:還沒預約 1:已經預約") private int live_reservation_state; @ApiModelProperty(value = "直播间显示状态 0:尚未开始 1 :即将开始(开始半小时之前) 2:直播中 3:已经结束") private int live_state; @ApiModelProperty(value = "直播间显示状态 字符") private int live_state_text; @ApiModelProperty(value = "直播间标题") private String live_title; @ApiModelProperty(value = "直播间banner地址") private String live_banner_url; @ApiModelProperty(value = "直播间时间描述") private String live_time_detail; @ApiModelProperty(value = "直播开始时间长整型") private Long live_start_time; @ApiModelProperty(value = "直播结束时间长整型") private Long live_end_time; @ApiModelProperty(value = "直播房间号") private String live_num; @ApiModelProperty(value = "直播id") private String live_id; @ApiModelProperty(value = "直播域名") private String live_domain; public int getLive_reservation_state() { return live_reservation_state; } public void setLive_reservation_state(int live_reservation_state) { this.live_reservation_state = live_reservation_state; } public int getLive_state() { return live_state; } public void setLive_state(int live_state) { this.live_state = live_state; } public void set_id(int _id) { this._id = _id; } public int get_id() { return this._id; } public String getLive_title() { return live_title; } public void setLive_title(String live_title) { this.live_title = live_title; } public String getLive_time_detail() { return live_time_detail; } public void setLive_time_detail(String live_time_detail) { this.live_time_detail = live_time_detail; } public Long getLive_start_time() { return live_start_time; } public void setLive_start_time(Long live_start_time) { this.live_start_time = live_start_time; } public Long getLive_end_time() { return live_end_time; } public void setLive_end_time(Long live_end_time) { this.live_end_time = live_end_time; } public String getLive_num() { return live_num; } public void setLive_num(String live_num) { this.live_num = live_num; } public String getLive_id() { return live_id; } public void setLive_id(String live_id) { this.live_id = live_id; } public String getLive_domain() { return live_domain; } public void setLive_domain(String live_domain) { this.live_domain = live_domain; } public String getLive_banner_url() { return live_banner_url; } public void setLive_banner_url(String live_banner_url) { this.live_banner_url = live_banner_url; } public int getLive_state_text() { return live_state_text; } public void setLive_state_text(int live_state_text) { this.live_state_text = live_state_text; } }