code_snippet
stringlengths
92
2.48k
score
float64
1.83
4.89
/** * Closes all panels, changes the background and shows the main menu. */ public void returnToTitle() { // TODO: check if the GUI object knows that we're not // inGame. (Retrieve value of GUI::inGame.) If GUI thinks // we're still in the game then log an error because at this // point the GUI should have been informed. closeMenus(); removeInGameComponents(); showMainPanel();
4.14876
/** subsequent imports override earlier ones */ public void importPackage(String name) { if(importedPackages == null) importedPackages = new Vector(); // If it exists, remove it and add it at the end (avoid memory leak) if ( importedPackages.contains( name ) ) importedPackages.remove( name ); importedPackages.addElement(name);
3.933884
if(dataServiceId.compareTo(cmpDataServiceId) != 0) { return false; } String country = getCountry(); String cmpCountry = cmp.getCountry();
4
public void filter(Filter filter) throws NoTestsRemainException { for (Iterator<Method> iter= fTestMethods.iterator(); iter.hasNext();) { Method method= iter.next(); if (!filter.shouldRun(methodDescription(method))) iter.remove(); } if (fTestMethods.isEmpty()) throw new NoTestsRemainException();
2.768595
/* fredt - in FK constraints column lists for iColMain and iColRef have identical sets to visible columns of iMain and iRef respectively but the order of columns can be different and must be preserved */ core.mainColArray = mainCols; core.colLen = core.mainColArray.length; core.refColArray = refCols;
3.942149
/** * Adds a message to the list of messages that need to be displayed on the GUI. * @param message The message to add. */ public synchronized void addMessage(GUIMessage message) { if (getMessageCount() == MESSAGE_COUNT) { messages.remove(0); } messages.add(message); freeColClient.getCanvas().repaint(0, 0, getWidth(), getHeight());
3.603306
private static final boolean jjCanMove_1(int hiByte, int i1, int i2, long l1, long l2) { switch(hiByte) { case 0: return ((jjbitVec0[i2] & l2) != 0L); default : if ((jjbitVec1[i1] & l1) != 0L) return true; return false;
2.644628
private static Date correctTimeZone(final Date date) { Date ret=date; if(java.util.TimeZone.getDefault().useDaylightTime()){ if(java.util.TimeZone.getDefault().inDaylightTime(date)) ret.setTime(date.getTime()+1*60*60*1000); } return ret;
2.876033
@Override public String getMessage() { StringBuilder builder= new StringBuilder(); if (fMessage != null) builder.append(fMessage); builder.append("arrays first differed at element ");
3.231405
String getStateString() { int state = getState(); switch (state) { case DATABASE_CLOSING : return "DATABASE_CLOSING"; case DATABASE_ONLINE : return "DATABASE_ONLINE";
4.289256
public boolean displayTileCursor(Tile tile, int canvasX, int canvasY) { if (currentMode == ViewMode.VIEW_TERRAIN_MODE) { Position selectedTilePos = gui.getSelectedTile(); if (selectedTilePos == null) return false; if (selectedTilePos.getX() == tile.getX() && selectedTilePos.getY() == tile.getY()) { TerrainCursor cursor = gui.getCursor();
3.355372
private final int jjMoveStringLiteralDfa18_0(long old1, long active1, long old2, long active2) { if (((active1 &= old1) | (active2 &= old2)) == 0L) return jjStartNfa_0(16, 0L, old1, old2); try { curChar = input_stream.readChar(); } catch(java.io.IOException e) { jjStopStringLiteralDfa_0(17, 0L, active1, active2);
2.090909
/** * Get the List of all available Channels * * @return All available Channels */ public ElgatoChannel[] getAvailableChannels() { ArrayList<ElgatoChannel> list = new ArrayList<ElgatoChannel>(); String res = null; try { res = mAppleScript.executeScript(CHANNELLIST);
3.363636
private Method getParametersMethod() throws Exception { for (Method each : fKlass.getMethods()) { if (Modifier.isStatic(each.getModifiers())) { Annotation[] annotations= each.getAnnotations(); for (Annotation annotation : annotations) { if (annotation.annotationType() == Parameters.class) return each; } } } throw new Exception("No public static parameters method on class " + getName());
2.355372
Node r = x.getRight(); if (r != null) { x = r; Node l = x.getLeft();
4.07438
InGameInputHandler inGameInputHandler = freeColClient.getInGameInputHandler(); freeColClient.getClient().setMessageHandler(inGameInputHandler); gui.setInGame(true);
3.190083
/** * Applies this action. * * @param e The <code>ActionEvent</code>. */ public void actionPerformed(ActionEvent e) { final Game game = freeColClient.getGame(); final Map map = game.getMap(); Parameters p = showParametersDialog();
3.809917
public ActionMenu getButtonAction() { AbstractAction action = new AbstractAction() { public void actionPerformed(ActionEvent evt) { showDialog(); } }; action.putValue(Action.NAME, mLocalizer.msg("CapturePlugin", "Capture Plugin")); action.putValue(Action.SMALL_ICON, createImageIcon("mimetypes", "video-x-generic", 16));
2.909091
Description description= Description.createSuiteDescription(name); int n= ts.testCount(); for (int i= 0; i < n; i++) description.addChild(makeDescription(ts.testAt(i)));
3.008264
if (expression.exprType != VALUE && expression.exprType != COLUMN && expression.exprType != FUNCTION && expression.exprType != ALTERNATIVE && expression.exprType != CASEWHEN && expression.exprType != CONVERT) { StringBuffer temp = new StringBuffer(); ddl = temp.append('(').append(ddl).append(')').toString(); } return ddl;
2.958678
private synchronized void purgeOldMessagesFromMessagesToIgnore(int thisTurn) { List<String> keysToRemove = new ArrayList<String>(); for (Entry<String, Integer> entry : messagesToIgnore.entrySet()) { if (entry.getValue().intValue() < thisTurn - 1) { if (logger.isLoggable(Level.FINER)) { logger.finer("Removing old model message with key " + entry.getKey() + " from ignored messages."); } keysToRemove.add(entry.getKey());
2.132231
@Override public void runTest(final Test test, final TestResult result) { Thread t = new Thread() { @Override public void run() { try { // inlined due to limitation in VA/Java //ActiveTestSuite.super.runTest(test, result); test.run(result); } finally { ActiveTestSuite.this.runFinished(); } } }; t.start(); }
4.222222
/** * ...as the moon sets over the early morning Merlin, Oregon * mountains, our intrepid adventurers type... */ static public Test createTest(Class<?> theClass, String name) { Constructor<?> constructor; try { constructor = getTestConstructor(theClass); } catch (NoSuchMethodException e) { return warning("Class " + theClass.getName() + " has no public constructor TestCase(String name) or TestCase()"); } Object test; try { if (constructor.getParameterTypes().length == 0) { test = constructor.newInstance(new Object[0]); if (test instanceof TestCase) { ((TestCase) test).setName(name); } } else { test = constructor.newInstance(new Object[]{name}); } } catch (InstantiationException e) { return (warning("Cannot instantiate test case: " + name + " (" + exceptionToString(e) + ")")); } catch (InvocationTargetException e) { return (warning("Exception in constructor: " + name + " (" + exceptionToString(e.getTargetException()) + ")")); } catch (IllegalAccessException e) { return (warning("Cannot access test case: " + name + " (" + exceptionToString(e) + ")")); } return (Test) test; }
3.555556
/** * Provides serialization support. * * @param stream the input stream (<code>null</code> not permitted). * * @throws IOException if there is an I/O error. * @throws ClassNotFoundException if there is a classpath problem. */ private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); this.titlePaint = SerialUtilities.readPaint(stream); this.subtitlePaint = SerialUtilities.readPaint(stream); this.chartBackgroundPaint = SerialUtilities.readPaint(stream); this.legendBackgroundPaint = SerialUtilities.readPaint(stream); this.legendItemPaint = SerialUtilities.readPaint(stream); this.plotBackgroundPaint = SerialUtilities.readPaint(stream); this.plotOutlinePaint = SerialUtilities.readPaint(stream); this.labelLinkPaint = SerialUtilities.readPaint(stream); this.baselinePaint = SerialUtilities.readPaint(stream); this.domainGridlinePaint = SerialUtilities.readPaint(stream); this.rangeGridlinePaint = SerialUtilities.readPaint(stream); this.crosshairPaint = SerialUtilities.readPaint(stream); this.axisLabelPaint = SerialUtilities.readPaint(stream); this.tickLabelPaint = SerialUtilities.readPaint(stream); this.itemLabelPaint = SerialUtilities.readPaint(stream); this.shadowPaint = SerialUtilities.readPaint(stream); this.thermometerPaint = SerialUtilities.readPaint(stream); this.wallPaint = SerialUtilities.readPaint(stream); this.errorIndicatorPaint = SerialUtilities.readPaint(stream); this.gridBandPaint = SerialUtilities.readPaint(stream); this.gridBandAlternatePaint = SerialUtilities.readPaint(stream); }
3.555556
/** * Constructs a panel that displays the specified chart. * * @param chart the chart. */ public ChartPanel(JFreeChart chart) { this( chart, DEFAULT_WIDTH, DEFAULT_HEIGHT, DEFAULT_MINIMUM_DRAW_WIDTH, DEFAULT_MINIMUM_DRAW_HEIGHT, DEFAULT_MAXIMUM_DRAW_WIDTH, DEFAULT_MAXIMUM_DRAW_HEIGHT, DEFAULT_BUFFER_USED, true, // properties true, // save true, // print true, // zoom true // tooltips ); }
4.333333
/** * static initializer, register all appropriate notations. */ static void init() { NotationProviderFactory2 npf = NotationProviderFactory2.getInstance(); NotationName name = /*Notation.findNotation("Java");*/ Notation.makeNotation( "Java", null, ResourceLoaderWrapper.lookupIconResource("JavaNotation")); npf.addNotationProvider( NotationProviderFactory2.TYPE_NAME, name, ModelElementNameNotationJava.class); npf.addNotationProvider( NotationProviderFactory2.TYPE_ATTRIBUTE, name, AttributeNotationJava.class); npf.addNotationProvider( NotationProviderFactory2.TYPE_OPERATION, name, OperationNotationJava.class); npf.addNotationProvider( NotationProviderFactory2.TYPE_ASSOCIATION_END_NAME, name, AssociationEndNameNotationJava.class); npf.addNotationProvider( NotationProviderFactory2.TYPE_ASSOCIATION_NAME, name, AssociationNameNotationJava.class); }
4
/** * {@inheritDoc} * * Overridden to find the start of a line-end. */ public boolean addChar(char c) { if (c == '\n') { hasLf = true; return true; } if (c == '\r') { hasCr = true; return true; } return false; }
4.555556
/** * Loads the bundle (if not already loaded). * * @param name The name of the bundle to load. */ private static void loadBundle(String name) { if (bundles.containsKey(name)) { return; } String resource = BUNDLES_PATH + "." + name; ResourceBundle bundle = null; try { LOG.debug("Loading " + resource); bundle = ResourceBundle.getBundle(resource, Locale.getDefault()); } catch (MissingResourceException e1) { LOG.debug("Resource " + resource + " not found in the default class loader."); Iterator iter = classLoaders.iterator(); while (iter.hasNext()) { ClassLoader cl = (ClassLoader) iter.next(); try { LOG.debug("Loading " + resource + " from " + cl); bundle = ResourceBundle.getBundle(resource, Locale.getDefault(), cl); break; } catch (MissingResourceException e2) { LOG.debug("Resource " + resource + " not found in " + cl); } } } bundles.put(name, bundle); }
3
protected synchronized String evalToString( Object self, String expr, String sep) throws ExpansionException { _scratchBindings.put("self", self); java.util.List values = eval(_scratchBindings, expr); _strBuf.setLength(0); Iterator iter = values.iterator(); while (iter.hasNext()) { Object v = iter.next(); if (Model.getFacade().isAModelElement(v)) { v = Model.getFacade().getName(v); if ("".equals(v)) { v = Translator.localize("misc.name.anon"); } } if (Model.getFacade().isAExpression(v)) { v = Model.getFacade().getBody(v); if ("".equals(v)) { v = "(unspecified)"; } } if (!"".equals(v)) { _strBuf.append(v); if (iter.hasNext()) { _strBuf.append(sep); } } } return _strBuf.toString(); }
3.111111
/** * Notify all listeners that have registered interest for * notification on this event type. The event instance * is lazily created using the parameters passed into * the fire method. * @see EventListenerList */ public void fireTreeStructureChanged( Object source, Object[] path, int[] childIndices, Object[] children) { // Guaranteed to return a non-null array Object[] listeners = listenerList.getListenerList(); TreeModelEvent e = null; // Process the listeners last to first, notifying // those that are interested in this event for (int i = listeners.length - 2; i >= 0; i -= 2) { if (listeners[i] == TreeModelListener.class) { // Lazily create the event: if (e == null) e = new TreeModelEvent( source, path, childIndices, children); ((TreeModelListener) listeners[i + 1]).treeStructureChanged(e); } } }
3.777778
private void myDoubleClick(Object src) { Object sel = null; Diagram d = null; if (src == resultsTable) { int row = resultsTable.getSelectionModel().getMinSelectionIndex(); if (row < 0) { return; } sel = results.elementAt(row); d = (Diagram) diagrams.elementAt(row); } else if (src == relatedTable) { int row = relatedTable.getSelectionModel().getMinSelectionIndex(); if (row < 0) { return; } numJumpToRelated++; sel = related.elementAt(row); } if (d != null) { LOG.debug("go " + sel + " in " + d.getName()); TargetManager.getInstance().setTarget(d); } TargetManager.getInstance().setTarget(sel); }
3.222222
public void propertyChange(PropertyChangeEvent evt) { // the project changed if (evt.getPropertyName() .equals(ProjectManager.CURRENT_PROJECT_PROPERTY_NAME)) { Project p = (Project) evt.getNewValue(); if (p != null) { titleHandler.buildTitle(p.getName(), null); //Designer.TheDesigner.getToDoList().removeAllElements(); Designer.setCritiquingRoot(p); // update all panes TargetManager.getInstance().setTarget(p.getInitialTarget()); } } }
4
public void testFailure() { String expected = expected(new String[]{".F", "Time: 0", "Failures here", "", "FAILURES!!!", "Tests run: 1, Failures: 1, Errors: 0", ""}); ResultPrinter printer = new TestResultPrinter(new PrintStream(output)) { @Override public void printFailures(TestResult result) { getWriter().println("Failures here"); } }; runner.setPrinter(printer); TestSuite suite = new TestSuite(); suite.addTest(new TestCase() { @Override public void runTest() { throw new AssertionFailedError(); } }); runner.doRun(suite); assertEquals(expected, output.toString()); }
3.333333
private Object createTestUsingFieldInjection() throws Exception { List<FrameworkField> annotatedFieldsByParameter = getAnnotatedFieldsByParameter(); if (annotatedFieldsByParameter.size() != fParameters.length) { throw new Exception("Wrong number of parameters and @Parameter fields." + " @Parameter fields counted: " + annotatedFieldsByParameter.size() + ", available parameters: " + fParameters.length + "."); } Object testClassInstance = getTestClass().getJavaClass().newInstance(); for (FrameworkField each : annotatedFieldsByParameter) { Field field = each.getField(); Parameter annotation = field.getAnnotation(Parameter.class); int index = annotation.value(); try { field.set(testClassInstance, fParameters[index]); } catch (IllegalArgumentException iare) { throw new Exception(getTestClass().getName() + ": Trying to set " + field.getName() + " with the value " + fParameters[index] + " that is not the right type (" + fParameters[index].getClass().getSimpleName() + " instead of " + field.getType().getSimpleName() + ").", iare); } } return testClassInstance; }
3.555556
@Override protected void validateFields(List<Throwable> errors) { super.validateFields(errors); if (fieldsAreAnnotated()) { List<FrameworkField> annotatedFieldsByParameter = getAnnotatedFieldsByParameter(); int[] usedIndices = new int[annotatedFieldsByParameter.size()]; for (FrameworkField each : annotatedFieldsByParameter) { int index = each.getField().getAnnotation(Parameter.class).value(); if (index < 0 || index > annotatedFieldsByParameter.size() - 1) { errors.add( new Exception("Invalid @Parameter value: " + index + ". @Parameter fields counted: " + annotatedFieldsByParameter.size() + ". Please use an index between 0 and " + (annotatedFieldsByParameter.size() - 1) + ".") ); } else { usedIndices[index]++; } } for (int index = 0; index < usedIndices.length; index++) { int numberOfUse = usedIndices[index]; if (numberOfUse == 0) { errors.add(new Exception("@Parameter(" + index + ") is never used.")); } else if (numberOfUse > 1) { errors.add(new Exception("@Parameter(" + index + ") is used more than once (" + numberOfUse + ").")); } } } }
3.555556
String[] parseOptions(String[] args) { for (int i = 0; i != args.length; ++i) { String arg = args[i]; try { if (arg.equals("--")) { return copyArray(args, i + 1, args.length); } else if (arg.startsWith("--")) { if (arg.startsWith("--filter=") || arg.equals("--filter")) { String filterSpec; if (arg.equals("--filter")) { ++i; if (i < args.length) { filterSpec = args[i]; } else { parserErrors.add(new CommandLineParserError(arg + " value not specified")); break; } } else { filterSpec = arg.substring(arg.indexOf('=') + 1); } filter = filter.intersect(FilterFactories.createFilterFromFilterSpec( createSuiteDescription(arg), filterSpec)); } else { parserErrors.add(new CommandLineParserError("JUnit knows nothing about the " + arg + " option")); } } else { return copyArray(args, i, args.length); } } catch (FilterFactory.FilterNotCreatedException e) { parserErrors.add(e); } } return new String[]{}; }
2.666667
private static Set<String> buildHintsSet() { HashSet<String> hints = new HashSet<String>(); hints.add( HINT_TIMEOUT ); hints.add( SPEC_HINT_TIMEOUT ); hints.add( HINT_COMMENT ); hints.add( HINT_FETCH_SIZE ); hints.add( HINT_CACHE_REGION ); hints.add( HINT_CACHEABLE ); hints.add( HINT_READONLY ); hints.add( HINT_CACHE_MODE ); hints.add( HINT_FLUSH_MODE ); hints.add( HINT_NATIVE_LOCKMODE ); hints.add( HINT_FETCHGRAPH ); hints.add( HINT_LOADGRAPH ); return java.util.Collections.unmodifiableSet( hints ); }
4.444444
@Test public void testHiLoAlgorithm() { session = (SessionImpl) sessionFactory.openSession(); ((Session)session).beginTransaction(); // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // initially sequence should be uninitialized assertEquals( 0L, extractSequenceValue( (session) ) ); // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // historically the hilo generators skipped the initial block of values; // so the first generated id value is maxlo + 1, here be 4 Long generatedValue = (Long) generator.generate( session, null ); assertEquals( 1L, generatedValue.longValue() ); // which should also perform the first read on the sequence which should set it to its "start with" value (1) assertEquals( 1L, extractSequenceValue( (session) ) ); // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ generatedValue = (Long) generator.generate( session, null ); assertEquals( 2L, generatedValue.longValue() ); assertEquals( 2L, extractSequenceValue( (session) ) ); // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ generatedValue = (Long) generator.generate( session, null ); assertEquals( 3L, generatedValue.longValue() ); assertEquals( 3L, extractSequenceValue( (session) ) ); // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ generatedValue = (Long) generator.generate( session, null ); assertEquals( 4L, generatedValue.longValue() ); assertEquals( 4L, extractSequenceValue( (session) ) ); // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ generatedValue = (Long) generator.generate( session, null ); assertEquals( 5L, generatedValue.longValue() ); assertEquals( 5L, extractSequenceValue( (session) ) ); ((Session)session).getTransaction().commit(); ((Session)session).close(); }
3.666667
/** * Constructs a PostgresPlusDialect */ public PostgresPlusDialect() { super(); registerFunction( "ltrim", new StandardSQLFunction( "ltrim" ) ); registerFunction( "rtrim", new StandardSQLFunction( "rtrim" ) ); registerFunction( "soundex", new StandardSQLFunction( "soundex" ) ); registerFunction( "sysdate", new NoArgSQLFunction( "sysdate", StandardBasicTypes.DATE, false ) ); registerFunction( "rowid", new NoArgSQLFunction( "rowid", StandardBasicTypes.LONG, false ) ); registerFunction( "rownum", new NoArgSQLFunction( "rownum", StandardBasicTypes.LONG, false ) ); registerFunction( "instr", new StandardSQLFunction( "instr", StandardBasicTypes.INTEGER ) ); registerFunction( "lpad", new StandardSQLFunction( "lpad", StandardBasicTypes.STRING ) ); registerFunction( "replace", new StandardSQLFunction( "replace", StandardBasicTypes.STRING ) ); registerFunction( "rpad", new StandardSQLFunction( "rpad", StandardBasicTypes.STRING ) ); registerFunction( "translate", new StandardSQLFunction( "translate", StandardBasicTypes.STRING ) ); registerFunction( "substring", new StandardSQLFunction( "substr", StandardBasicTypes.STRING ) ); registerFunction( "coalesce", new NvlFunction() ); registerFunction( "atan2", new StandardSQLFunction( "atan2", StandardBasicTypes.FLOAT ) ); registerFunction( "mod", new StandardSQLFunction( "mod", StandardBasicTypes.INTEGER ) ); registerFunction( "nvl", new StandardSQLFunction( "nvl" ) ); registerFunction( "nvl2", new StandardSQLFunction( "nvl2" ) ); registerFunction( "power", new StandardSQLFunction( "power", StandardBasicTypes.FLOAT ) ); registerFunction( "add_months", new StandardSQLFunction( "add_months", StandardBasicTypes.DATE ) ); registerFunction( "months_between", new StandardSQLFunction( "months_between", StandardBasicTypes.FLOAT ) ); registerFunction( "next_day", new StandardSQLFunction( "next_day", StandardBasicTypes.DATE ) ); }
4
/** * Constructs a Oracle8iDialect */ public Oracle8iDialect() { super(); registerCharacterTypeMappings(); registerNumericTypeMappings(); registerDateTimeTypeMappings(); registerLargeObjectTypeMappings(); registerReverseHibernateTypeMappings(); registerFunctions(); registerDefaultProperties(); }
4
/** * Constructs a InterbaseDialect */ public InterbaseDialect() { super(); registerColumnType( Types.BIT, "smallint" ); registerColumnType( Types.BIGINT, "numeric(18,0)" ); registerColumnType( Types.SMALLINT, "smallint" ); registerColumnType( Types.TINYINT, "smallint" ); registerColumnType( Types.INTEGER, "integer" ); registerColumnType( Types.CHAR, "char(1)" ); registerColumnType( Types.VARCHAR, "varchar($l)" ); registerColumnType( Types.FLOAT, "float" ); registerColumnType( Types.DOUBLE, "double precision" ); registerColumnType( Types.DATE, "date" ); registerColumnType( Types.TIME, "time" ); registerColumnType( Types.TIMESTAMP, "timestamp" ); registerColumnType( Types.VARBINARY, "blob" ); registerColumnType( Types.NUMERIC, "numeric($p,$s)" ); registerColumnType( Types.BLOB, "blob" ); registerColumnType( Types.CLOB, "blob sub_type 1" ); registerColumnType( Types.BOOLEAN, "smallint" ); registerFunction( "concat", new VarArgsSQLFunction( StandardBasicTypes.STRING, "(","||",")" ) ); registerFunction( "current_date", new NoArgSQLFunction( "current_date", StandardBasicTypes.DATE, false ) ); getDefaultProperties().setProperty( Environment.STATEMENT_BATCH_SIZE, NO_BATCH ); }
3.888889
/** * Constructs a SybaseASE157Dialect */ public SybaseASE157Dialect() { super(); registerFunction( "create_locator", new SQLFunctionTemplate( StandardBasicTypes.BINARY, "create_locator(?1, ?2)" ) ); registerFunction( "locator_literal", new SQLFunctionTemplate( StandardBasicTypes.BINARY, "locator_literal(?1, ?2)" ) ); registerFunction( "locator_valid", new SQLFunctionTemplate( StandardBasicTypes.BOOLEAN, "locator_valid(?1)" ) ); registerFunction( "return_lob", new SQLFunctionTemplate( StandardBasicTypes.BINARY, "return_lob(?1, ?2)" ) ); registerFunction( "setdata", new SQLFunctionTemplate( StandardBasicTypes.BOOLEAN, "setdata(?1, ?2, ?3)" ) ); registerFunction( "charindex", new SQLFunctionTemplate( StandardBasicTypes.INTEGER, "charindex(?1, ?2, ?3)" ) ); }
4
public String extractConstraintName(SQLException sqle) { try { final int sqlState = Integer.valueOf( JdbcExceptionHelper.extractSqlState( sqle ) ); switch (sqlState) { // CHECK VIOLATION case 23514: return extractUsingTemplate( "violates check constraint \"","\"", sqle.getMessage() ); // UNIQUE VIOLATION case 23505: return extractUsingTemplate( "violates unique constraint \"","\"", sqle.getMessage() ); // FOREIGN KEY VIOLATION case 23503: return extractUsingTemplate( "violates foreign key constraint \"","\"", sqle.getMessage() ); // NOT NULL VIOLATION case 23502: return extractUsingTemplate( "null value in column \"","\" violates not-null constraint", sqle.getMessage() ); // TODO: RESTRICT VIOLATION case 23001: return null; // ALL OTHER default: return null; } } catch (NumberFormatException nfe) { return null; } }
4.555556
@Test @TestForIssue(jiraKey = "HHH-8007") public void testGetLimitStringSelectingMultipleColumnsFromSeveralTables() { final String query = "select t1.*, t2.* from tab1 t1, tab2 t2 where t1.ref = t2.ref order by t1.id desc"; assertEquals( "WITH query AS (SELECT inner_query.*, ROW_NUMBER() OVER (ORDER BY CURRENT_TIMESTAMP) as __hibernate_row_nr__ FROM ( " + "select TOP(?) t1.*, t2.* from tab1 t1, tab2 t2 where t1.ref = t2.ref order by t1.id desc ) inner_query ) " + "SELECT * FROM query WHERE __hibernate_row_nr__ >= ? AND __hibernate_row_nr__ < ?", dialect.buildLimitHandler( query, toRowSelection( 1, 3 ) ).getProcessedSql() ); }
3.222222
@Test public void testInsertLimitWithForUpdateAndWithClauses() { final int limit = 50; final int offset = 200; final String input = "select c11 as col1, c12 as col2, c13 as col13 from t1 where flight_id between 'AA1111' and 'AA1112' for update of c11,c13 with rr"; final String expected = "select c11 as col1, c12 as col2, c13 as col13 from t1 where flight_id between 'AA1111' and 'AA1112' offset " + offset + " rows fetch next " + limit + " rows only for update of c11,c13 with rr"; final String actual = new LocalDerbyDialect().getLimitString( input, offset, limit ); assertEquals( expected, actual ); }
3.666667
/** * Constructs a FrontBaseDialect */ public FrontBaseDialect() { super(); registerColumnType( Types.BIT, "bit" ); registerColumnType( Types.BIGINT, "longint" ); registerColumnType( Types.SMALLINT, "smallint" ); registerColumnType( Types.TINYINT, "tinyint" ); registerColumnType( Types.INTEGER, "integer" ); registerColumnType( Types.CHAR, "char(1)" ); registerColumnType( Types.VARCHAR, "varchar($l)" ); registerColumnType( Types.FLOAT, "float" ); registerColumnType( Types.DOUBLE, "double precision" ); registerColumnType( Types.DATE, "date" ); registerColumnType( Types.TIME, "time" ); registerColumnType( Types.TIMESTAMP, "timestamp" ); registerColumnType( Types.VARBINARY, "bit varying($l)" ); registerColumnType( Types.NUMERIC, "numeric($p,$s)" ); registerColumnType( Types.BLOB, "blob" ); registerColumnType( Types.CLOB, "clob" ); }
4.222222
@Test public void testSqlTrimFunction() { String fragment = "trim( col )"; String template = Template.renderWhereStringTemplate( fragment, Template.TEMPLATE, DIALECT, FUNCTION_REGISTRY ); assertEquals( "trim(" + Template.TEMPLATE + ".col)", template ); fragment = "trim( from col )"; template = Template.renderWhereStringTemplate( fragment, Template.TEMPLATE, DIALECT, FUNCTION_REGISTRY ); assertEquals( "trim(from " + Template.TEMPLATE + ".col)", template ); fragment = "trim( both from col )"; template = Template.renderWhereStringTemplate( fragment, Template.TEMPLATE, DIALECT, FUNCTION_REGISTRY ); assertEquals( "trim(both from " + Template.TEMPLATE + ".col)", template ); fragment = "trim( leading from col )"; template = Template.renderWhereStringTemplate( fragment, Template.TEMPLATE, DIALECT, FUNCTION_REGISTRY ); assertEquals( "trim(leading from " + Template.TEMPLATE + ".col)", template ); fragment = "trim( TRAILING from col )"; template = Template.renderWhereStringTemplate( fragment, Template.TEMPLATE, DIALECT, FUNCTION_REGISTRY ); assertEquals( "trim(TRAILING from " + Template.TEMPLATE + ".col)", template ); fragment = "trim( 'b' from col )"; template = Template.renderWhereStringTemplate( fragment, Template.TEMPLATE, DIALECT, FUNCTION_REGISTRY ); assertEquals( "trim('b' from " + Template.TEMPLATE + ".col)", template ); fragment = "trim( both 'b' from col )"; template = Template.renderWhereStringTemplate( fragment, Template.TEMPLATE, DIALECT, FUNCTION_REGISTRY ); assertEquals( "trim(both 'b' from " + Template.TEMPLATE + ".col)", template ); }
3.222222
private void considerExplicitFieldAndPropertyAccess() { for ( XProperty property : fieldAccessMap.values() ) { Access access = property.getAnnotation( Access.class ); if ( access == null ) { continue; } // see "2.3.2 Explicit Access Type" of JPA 2 spec // the access type for this property is explicitly set to AccessType.FIELD, hence we have to // use field access for this property even if the default access type for the class is AccessType.PROPERTY AccessType accessType = AccessType.getAccessStrategy( access.value() ); if (accessType == AccessType.FIELD) { propertyAccessMap.put(property.getName(), property); } else { LOG.debug( "Placing @Access(AccessType.FIELD) on a field does not have any effect." ); } } for ( XProperty property : propertyAccessMap.values() ) { Access access = property.getAnnotation( Access.class ); if ( access == null ) { continue; } AccessType accessType = AccessType.getAccessStrategy( access.value() ); // see "2.3.2 Explicit Access Type" of JPA 2 spec // the access type for this property is explicitly set to AccessType.PROPERTY, hence we have to // return use method access even if the default class access type is AccessType.FIELD if (accessType == AccessType.PROPERTY) { fieldAccessMap.put(property.getName(), property); } else { LOG.debug( "Placing @Access(AccessType.PROPERTY) on a field does not have any effect." ); } } }
3.777778
private static Ejb3DiscriminatorColumn processDiscriminatorProperties(XClass clazzToProcess, Mappings mappings, InheritanceState inheritanceState, EntityBinder entityBinder) { Ejb3DiscriminatorColumn discriminatorColumn = null; javax.persistence.DiscriminatorColumn discAnn = clazzToProcess.getAnnotation( javax.persistence.DiscriminatorColumn.class ); DiscriminatorType discriminatorType = discAnn != null ? discAnn.discriminatorType() : DiscriminatorType.STRING; org.hibernate.annotations.DiscriminatorFormula discFormulaAnn = clazzToProcess.getAnnotation( org.hibernate.annotations.DiscriminatorFormula.class ); if ( !inheritanceState.hasParents() ) { discriminatorColumn = Ejb3DiscriminatorColumn.buildDiscriminatorColumn( discriminatorType, discAnn, discFormulaAnn, mappings ); } if ( discAnn != null && inheritanceState.hasParents() ) { LOG.invalidDiscriminatorAnnotation( clazzToProcess.getName() ); } String discrimValue = clazzToProcess.isAnnotationPresent( DiscriminatorValue.class ) ? clazzToProcess.getAnnotation( DiscriminatorValue.class ).value() : null; entityBinder.setDiscriminatorValue( discrimValue ); DiscriminatorOptions discriminatorOptions = clazzToProcess.getAnnotation( DiscriminatorOptions.class ); if ( discriminatorOptions != null) { entityBinder.setForceDiscriminator( discriminatorOptions.force() ); entityBinder.setInsertableDiscriminator( discriminatorOptions.insert() ); } return discriminatorColumn; }
2.333333
private static boolean isEntityClassType(XClass clazzToProcess, AnnotatedClassType classType) { if ( AnnotatedClassType.EMBEDDABLE_SUPERCLASS.equals( classType ) //will be processed by their subentities || AnnotatedClassType.NONE.equals( classType ) //to be ignored || AnnotatedClassType.EMBEDDABLE.equals( classType ) //allow embeddable element declaration ) { if ( AnnotatedClassType.NONE.equals( classType ) && clazzToProcess.isAnnotationPresent( org.hibernate.annotations.Entity.class ) ) { LOG.missingEntityAnnotation( clazzToProcess.getName() ); } return false; } if ( !classType.equals( AnnotatedClassType.ENTITY ) ) { throw new AnnotationException( "Annotated class should have a @javax.persistence.Entity, @javax.persistence.Embeddable or @javax.persistence.EmbeddedSuperclass annotation: " + clazzToProcess .getName() ); } return true; }
3.666667
public void redefineColumnName(String columnName, String propertyName, boolean applyNamingStrategy) { if ( applyNamingStrategy ) { if ( StringHelper.isEmpty( columnName ) ) { if ( propertyName != null ) { mappingColumn.setName( mappings.getObjectNameNormalizer().normalizeIdentifierQuoting( mappings.getNamingStrategy().propertyToColumnName( propertyName ) ) ); } //Do nothing otherwise } else { columnName = mappings.getObjectNameNormalizer().normalizeIdentifierQuoting( columnName ); columnName = mappings.getNamingStrategy().columnName( columnName ); columnName = mappings.getObjectNameNormalizer().normalizeIdentifierQuoting( columnName ); mappingColumn.setName( columnName ); } } else { if ( StringHelper.isNotEmpty( columnName ) ) { mappingColumn.setName( mappings.getObjectNameNormalizer().normalizeIdentifierQuoting( columnName ) ); } } }
3.444444
private static void parseFilter(Element filterElement, Filterable filterable, Mappings model) { final String name = filterElement.attributeValue( "name" ); String condition = filterElement.getTextTrim(); if ( StringHelper.isEmpty(condition) ) { condition = filterElement.attributeValue( "condition" ); } //TODO: bad implementation, cos it depends upon ordering of mapping doc // fixing this requires that Collection/PersistentClass gain access // to the Mappings reference from Configuration (or the filterDefinitions // map directly) sometime during Configuration.build // (after all the types/filter-defs are known and before building // persisters). if ( StringHelper.isEmpty(condition) ) { condition = model.getFilterDefinition(name).getDefaultFilterCondition(); } if ( condition==null) { throw new MappingException("no filter condition found for filter: " + name); } Iterator aliasesIterator = filterElement.elementIterator("aliases"); java.util.Map<String, String> aliasTables = new HashMap<String, String>(); while (aliasesIterator.hasNext()){ Element alias = (Element) aliasesIterator.next(); aliasTables.put(alias.attributeValue("alias"), alias.attributeValue("table")); } LOG.debugf( "Applying filter [%s] as [%s]", name, condition ); String autoAliasInjectionText = filterElement.attributeValue("autoAliasInjection"); boolean autoAliasInjection = StringHelper.isEmpty(autoAliasInjectionText) ? true : Boolean.parseBoolean(autoAliasInjectionText); filterable.addFilter(name, condition, autoAliasInjection, aliasTables, null); }
3.222222
/** * Retrieves a PropertyAccessor instance based on the given property definition and * entity mode. * * @param property The property for which to retrieve an accessor. * @param mode The mode for the resulting entity. * @return An appropriate accessor. * @throws MappingException */ public static PropertyAccessor getPropertyAccessor(AttributeBinding property, EntityMode mode) throws MappingException { //TODO: this is temporary in that the end result will probably not take a Property reference per-se. if ( null == mode || EntityMode.POJO.equals( mode ) ) { return getPojoPropertyAccessor( property.getPropertyAccessorName() ); } else if ( EntityMode.MAP.equals( mode ) ) { return getDynamicMapPropertyAccessor(); } else { throw new MappingException( "Unknown entity mode [" + mode + "]" ); } }
4.333333
/** * Execute given <tt>PreparedStatement</tt>, advance to the first result and return SQL <tt>ResultSet</tt>. */ protected final ResultSet getResultSet( final PreparedStatement st, final RowSelection selection, final LimitHandler limitHandler, final boolean autodiscovertypes, final SessionImplementor session) throws SQLException, HibernateException { try { ResultSet rs = session.getTransactionCoordinator().getJdbcCoordinator().getResultSetReturn().extract( st ); rs = wrapResultSetIfEnabled( rs , session ); if ( !limitHandler.supportsLimitOffset() || !LimitHelper.useLimit( limitHandler, selection ) ) { advance( rs, selection ); } if ( autodiscovertypes ) { autoDiscoverTypes( rs ); } return rs; } catch ( SQLException sqle ) { session.getTransactionCoordinator().getJdbcCoordinator().release( st ); throw sqle; } }
4
/** * Generate a select list of columns containing all properties of the entity classes */ protected final String selectString(List associations) throws MappingException { if ( associations.size()==0 ) { return ""; } else { StringBuilder buf = new StringBuilder( associations.size() * 100 ); int entityAliasCount=0; int collectionAliasCount=0; for ( int i=0; i<associations.size(); i++ ) { OuterJoinableAssociation join = (OuterJoinableAssociation) associations.get(i); OuterJoinableAssociation next = (i == associations.size() - 1) ? null : ( OuterJoinableAssociation ) associations.get( i + 1 ); final Joinable joinable = join.getJoinable(); final String entitySuffix = ( suffixes == null || entityAliasCount >= suffixes.length ) ? null : suffixes[entityAliasCount]; final String collectionSuffix = ( collectionSuffixes == null || collectionAliasCount >= collectionSuffixes.length ) ? null : collectionSuffixes[collectionAliasCount]; final String selectFragment = joinable.selectFragment( next == null ? null : next.getJoinable(), next == null ? null : next.getRHSAlias(), join.getRHSAlias(), entitySuffix, collectionSuffix, join.getJoinType()==JoinType.LEFT_OUTER_JOIN ); if (selectFragment.trim().length() > 0) { buf.append(", ").append(selectFragment); } if ( joinable.consumesEntityAlias() ) entityAliasCount++; if ( joinable.consumesCollectionAlias() && join.getJoinType()==JoinType.LEFT_OUTER_JOIN ) collectionAliasCount++; } return buf.toString(); } }
2.555556
@Test public void testProperties() throws Exception { final Properties props = new Properties(); props.put("rpt.1.hibernate.dialect", "org.hibernate.dialect.DerbyDialect"); props.put("rpt.2.hibernate.connection.driver_class", "org.apache.derby.jdbc.ClientDriver"); props.put("rpt.3.hibernate.connection.url", "jdbc:derby://localhost:1527/db/reports.db"); props.put("rpt.4.hibernate.connection.username", "sa"); props.put("rpt.5.hibernate.connection.password_enc", "76f271db3661fd50082e68d4b953fbee"); props.put("rpt.6.hibernate.connection.password_enc", "76f271db3661fd50082e68d4b953fbee"); props.put("hibernate.connection.create", "true"); final Properties outputProps = ConnectionProviderInitiator.getConnectionProperties( props ); Assert.assertEquals( 1, outputProps.size() ); Assert.assertEquals( "true", outputProps.get( "create" ) ); }
4.222222
public boolean equals(Table table) { if (null == table) { return false; } if (this == table) { return true; } return isQuoted() ? name.equals(table.getName()) : name.equalsIgnoreCase(table.getName()) && ((schema == null && table.getSchema() != null) ? false : (schema == null) ? true : isSchemaQuoted() ? schema.equals(table.getSchema()) : schema.equalsIgnoreCase(table.getSchema())) && ((catalog == null && table.getCatalog() != null) ? false : (catalog == null) ? true : isCatalogQuoted() ? catalog.equals(table.getCatalog()) : catalog.equalsIgnoreCase(table.getCatalog())); }
2.222222
public int getSqlTypeCode(Mapping mapping) throws MappingException { org.hibernate.type.Type type = getValue().getType(); try { int sqlTypeCode = type.sqlTypes( mapping )[getTypeIndex()]; if ( getSqlTypeCode() != null && getSqlTypeCode() != sqlTypeCode ) { throw new MappingException( "SQLType code's does not match. mapped as " + sqlTypeCode + " but is " + getSqlTypeCode() ); } return sqlTypeCode; } catch ( Exception e ) { throw new MappingException( "Could not determine type for column " + name + " of type " + type.getClass().getName() + ": " + e.getClass().getName(), e ); } }
3.777778
/** * Provides serialization support. * * @param stream the output stream. * * @throws IOException if there is an I/O error. */ private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); SerialUtilities.writeShape(this.legendItemShape, stream); SerialUtilities.writePaint(this.seriesPaint, stream); SerialUtilities.writePaint(this.baseSeriesPaint, stream); SerialUtilities.writePaint(this.seriesOutlinePaint, stream); SerialUtilities.writePaint(this.baseSeriesOutlinePaint, stream); SerialUtilities.writeStroke(this.seriesOutlineStroke, stream); SerialUtilities.writeStroke(this.baseSeriesOutlineStroke, stream); SerialUtilities.writePaint(this.labelPaint, stream); SerialUtilities.writePaint(this.axisLinePaint, stream); SerialUtilities.writeStroke(this.axisLineStroke, stream); }
4.222222
/** * Tests another object for equality with this object. * * @param obj the object to test (<code>null</code> permitted). * * @return A boolean. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof PinNeedle)) { return false; } if (!super.equals(obj)) { return false; } return true; }
4.777778
/** * Tests this dataset for equality with an arbitrary object. * * @param obj the object (<code>null</code> permitted). * * @return A boolean. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof CategoryDataset)) { return false; } CategoryDataset that = (CategoryDataset) obj; if (!getRowKeys().equals(that.getRowKeys())) { return false; } if (!getColumnKeys().equals(that.getColumnKeys())) { return false; } int rowCount = getRowCount(); int colCount = getColumnCount(); for (int r = 0; r < rowCount; r++) { for (int c = 0; c < colCount; c++) { Number v1 = getValue(r, c); Number v2 = that.getValue(r, c); if (v1 == null) { if (v2 != null) { return false; } } else if (!v1.equals(v2)) { return false; } } } return true; }
4.222222
/** * Returns the minimum and maximum values for the dataset's range * (y-values), assuming that the series in one category are stacked. * * @param dataset the dataset (<code>null</code> not permitted). * @param base the base value for the bars. * * @return The range (<code>null</code> if the dataset contains no values). */ public static Range findStackedRangeBounds(CategoryDataset dataset, double base) { ParamChecks.nullNotPermitted(dataset, "dataset"); Range result = null; double minimum = Double.POSITIVE_INFINITY; double maximum = Double.NEGATIVE_INFINITY; int categoryCount = dataset.getColumnCount(); for (int item = 0; item < categoryCount; item++) { double positive = base; double negative = base; int seriesCount = dataset.getRowCount(); for (int series = 0; series < seriesCount; series++) { Number number = dataset.getValue(series, item); if (number != null) { double value = number.doubleValue(); if (value > 0.0) { positive = positive + value; } if (value < 0.0) { negative = negative + value; // '+', remember value is negative } } } minimum = Math.min(minimum, negative); maximum = Math.max(maximum, positive); } if (minimum <= maximum) { result = new Range(minimum, maximum); } return result; }
4.111111
/** * Tests the equality of this object against an arbitrary Object. * <P> * This method will return true ONLY if the object is a Second object * representing the same second as this instance. * * @param obj the object to compare (<code>null</code> permitted). * * @return <code>true</code> if second and minute of this and the object * are the same. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof Second)) { return false; } Second that = (Second) obj; if (this.second != that.second) { return false; } if (this.minute != that.minute) { return false; } if (this.hour != that.hour) { return false; } if (!this.day.equals(that.day)) { return false; } return true; }
4.666667
private void handleFireEvent(ArgoEvent event, ArgoEventListener listener) { if (event.getEventType() == ArgoEventTypes.ANY_EVENT) { if (listener instanceof ArgoModuleEventListener) { handleFireModuleEvent((ArgoModuleEvent) event, (ArgoModuleEventListener) listener); } if (listener instanceof ArgoNotationEventListener) { handleFireNotationEvent((ArgoNotationEvent) event, (ArgoNotationEventListener) listener); } } else { if (event.getEventType() >= ArgoEventTypes.ANY_MODULE_EVENT && event.getEventType() < ArgoEventTypes.LAST_MODULE_EVENT) { if (listener instanceof ArgoModuleEventListener) { handleFireModuleEvent((ArgoModuleEvent) event, (ArgoModuleEventListener) listener); } } if (event.getEventType() >= ArgoEventTypes.ANY_NOTATION_EVENT && event.getEventType() < ArgoEventTypes.LAST_NOTATION_EVENT) { if (listener instanceof ArgoNotationEventListener) { handleFireNotationEvent((ArgoNotationEvent) event, (ArgoNotationEventListener) listener); } } if (event.getEventType() >= ArgoEventTypes.ANY_GENERATOR_EVENT && event.getEventType() < ArgoEventTypes.LAST_GENERATOR_EVENT) { if (listener instanceof ArgoGeneratorEventListener) { handleFireGeneratorEvent((ArgoGeneratorEvent) event, (ArgoGeneratorEventListener) listener); } } } }
2.888889
/** * Find an element in the list. * * This is a little more complex than the simple lookup since it might be * that we are indexing with a class and the list contains interfaces. * * Since the hashtable lookup is a lot faster than the linear search we * add the result of the linear search to the hashtable so that the next * time we need not do it. * * @return Checklist or null if noone exist. * @param cls the class to lookup. */ private static Checklist lookupChecklist(Class cls) { if (lists.contains(cls)) { return (Checklist) lists.get(cls); } // Now lets search Enumeration enumeration = lists.keys(); while (enumeration.hasMoreElements()) { Object clazz = enumeration.nextElement(); Class[] intfs = cls.getInterfaces(); for (int i = 0; i < intfs.length; i++) { if (intfs[i].equals(clazz)) { // We found it! Checklist chlist = (Checklist) lists.get(clazz); // Enter the class to speed up the next search. lists.put(cls, chlist); return chlist; } } } return null; }
4
/** * @return a list of all the types */ public static Vector getTypes() { if (types == null) { types = new Vector(); types.addElement(new KnowledgeTypeNode(Critic.KT_DESIGNERS)); types.addElement(new KnowledgeTypeNode(Critic.KT_CORRECTNESS)); types.addElement(new KnowledgeTypeNode(Critic.KT_COMPLETENESS)); types.addElement(new KnowledgeTypeNode(Critic.KT_CONSISTENCY)); types.addElement(new KnowledgeTypeNode(Critic.KT_SYNTAX)); types.addElement(new KnowledgeTypeNode(Critic.KT_SEMANTICS)); types.addElement(new KnowledgeTypeNode(Critic.KT_OPTIMIZATION)); types.addElement(new KnowledgeTypeNode(Critic.KT_PRESENTATION)); types.addElement(new KnowledgeTypeNode(Critic.KT_ORGANIZATIONAL)); types.addElement(new KnowledgeTypeNode(Critic.KT_EXPERIENCIAL)); types.addElement(new KnowledgeTypeNode(Critic.KT_TOOL)); } return types; }
4.333333
public void toDoItemsRemoved(ToDoListEvent tde) { LOG.debug("toDoItemRemoved"); Vector items = tde.getToDoItems(); int nItems = items.size(); ToDoList list = Designer.theDesigner().getToDoList(); //source? Object[] path = new Object[2]; path[0] = Designer.theDesigner().getToDoList(); Enumeration elems = list.getPosters().elements(); while (elems.hasMoreElements()) { Poster p = (Poster) elems.nextElement(); boolean anyInPoster = false; for (int i = 0; i < nItems; i++) { ToDoItem item = (ToDoItem) items.elementAt(i); Poster post = item.getPoster(); if (post == p) { anyInPoster = true; break; } } if (!anyInPoster) { continue; } path[1] = p; fireTreeStructureChanged(path); } }
3.333333
public void updateListener(PropertyChangeListener listener, Object modelElement, PropertyChangeEvent pce) { Object obj = pce.getSource(); if ((obj == modelElement) && "stereotype".equals(pce.getPropertyName())) { if (pce instanceof AddAssociationEvent && Model.getFacade().isAStereotype(pce.getNewValue())) { // new stereotype addElementListener( listener, pce.getNewValue(), new String[] {"name", "remove"}); } if (pce instanceof RemoveAssociationEvent && Model.getFacade().isAStereotype(pce.getOldValue())) { // removed stereotype removeElementListener( listener, pce.getOldValue()); } } }
3.666667
/** * @param filename the filename to read from */ public void read(String filename) { try { FileReader f = new FileReader(filename); BufferedReader fr = new BufferedReader(f); String line = ""; String content = ""; boolean inSection = false; while (line != null) { line = fr.readLine(); if (line != null) { if (inSection) { String sectionId = getSectId(line); if (sectionId != null) { inSection = false; mAry.put(sectionId, content); content = ""; } else { content += line + LINE_SEPARATOR; } } else { String sectionId = getSectId(line); if (sectionId != null) { inSection = true; } } } } fr.close(); } catch (IOException e) { LOG.error("Error: " + e.toString()); } }
4.111111
private boolean saveGraphicsToFile(File theFile, CmdSaveGraphics cmd, boolean overwrite) throws IOException { if ( theFile.exists() && !overwrite ) { int response = JOptionPane.showConfirmDialog(ArgoFrame.getInstance(), Translator.messageFormat("optionpane.confirm-overwrite", new Object[] {theFile}), Translator.localize("optionpane.confirm-overwrite-title"), JOptionPane.YES_NO_OPTION); if (response == JOptionPane.NO_OPTION) return false; } FileOutputStream fo = null; try { fo = new FileOutputStream( theFile ); cmd.setStream(fo); cmd.setScale(Configuration.getInteger( SaveGraphicsManager.KEY_GRAPHICS_RESOLUTION, 1)); cmd.doIt(); } finally { if (fo != null) { fo.close(); } } return true; }
2.777778
public void targetAdded(TargetEvent e) { if (!updatingSelection) { updatingSelection = true; Object[] targets = e.getAddedTargets(); int rows = getRowCount(); for (int i = 0; i < targets.length; i++) { Object target = targets[i]; if (target instanceof Fig) { target = ((Fig) target).getOwner(); } for (int j = 0; j < rows; j++) { Object rowItem = ((DefaultMutableTreeNode) getPathForRow(j).getLastPathComponent()) .getUserObject(); if (rowItem == target) { updatingSelectionViaTreeSelection = true; addSelectionRow(j); updatingSelectionViaTreeSelection = false; } } } if (getSelectionCount() > 0) { scrollRowToVisible(getSelectionRows()[0]); } updatingSelection = false; } // setTargets(e.getNewTargets()); }
3.111111
/** * Saves the given actions in the configuration file * * @param newActions * the actions array */ public static void saveShortcuts(Action[] newActions) { for (int i = 0; i < newActions.length; i++) { Action oldAction = (Action) shortcutHash .get(newActions[i].getKey()); if (newActions[i].getCurrentShortcut() == null && newActions[i].getDefaultShortcut() != null) { // if a default action was voided then we have to save it Configuration.setString(Configuration.makeKey(oldAction .getKey()), ""); } else if (newActions[i].getCurrentShortcut() != null && !newActions[i].getCurrentShortcut().equals( newActions[i].getDefaultShortcut())) { // if a not-default current shortcut was added, then we have to // save it Configuration.setString(Configuration.makeKey(oldAction .getKey()), KeyEventUtils.formatKeyStroke(newActions[i] .getCurrentShortcut())); } else { // if the actual is not going to be saved, then try to remove it // (as it could have been cancelled) Configuration.removeKey(Configuration.makeKey(oldAction .getKey())); } } }
3.444444
protected void scanAnnotatedMembers(Map<Class<? extends Annotation>, List<FrameworkMethod>> methodsForAnnotations, Map<Class<? extends Annotation>, List<FrameworkField>> fieldsForAnnotations) { for (Class<?> eachClass : getSuperClasses(fClass)) { for (Method eachMethod : MethodSorter.getDeclaredMethods(eachClass)) { addToAnnotationLists(new FrameworkMethod(eachMethod), methodsForAnnotations); } // ensuring fields are sorted to make sure that entries are inserted // and read from fieldForAnnotations in a deterministic order for (Field eachField : getSortedDeclaredFields(eachClass)) { addToAnnotationLists(new FrameworkField(eachField), fieldsForAnnotations); } } }
4
/** * Verifies that listeners added with addFirstListener() while tests are run concurrently are * notified about test failures. */ @Test public void reportConcurrentFailuresAfterAddFirstListener() throws Exception { new AbstractConcurrentFailuresTest() { @Override protected void addListener(ExaminedListener listener) { fNotifier.addFirstListener(listener); } }.test(); }
4.222222
private static Description makeDescription(Test test) { if (test instanceof TestCase) { TestCase tc = (TestCase) test; return Description.createTestDescription(tc.getClass(), tc.getName(), getAnnotations(tc)); } else if (test instanceof TestSuite) { TestSuite ts = (TestSuite) test; String name = ts.getName() == null ? createSuiteDescription(ts) : ts.getName(); Description description = Description.createSuiteDescription(name); int n = ts.testCount(); for (int i = 0; i < n; i++) { Description made = makeDescription(ts.testAt(i)); description.addChild(made); } return description; } else if (test instanceof Describable) { Describable adapter = (Describable) test; return adapter.getDescription(); } else if (test instanceof TestDecorator) { TestDecorator decorator = (TestDecorator) test; return makeDescription(decorator.getTest()); } else { // This is the best we can do in this case return Description.createSuiteDescription(test.getClass()); } }
4.111111
private EntityManager internalCreateEntityManager(SynchronizationType synchronizationType, Map map) { validateNotClosed(); //TODO support discardOnClose, persistencecontexttype?, interceptor, return new EntityManagerImpl( this, PersistenceContextType.EXTENDED, synchronizationType, transactionType, discardOnClose, sessionInterceptorClass, map ); }
4.222222
@Test public void testBasicHiLoOptimizerUsage() { int increment = 10; Long next; // test historic sequence behavior, where the initial values start at 1... SourceMock sequence = new SourceMock( 1 ); Optimizer optimizer = buildHiloOptimizer( -1, increment ); for ( int i = 1; i <= increment; i++ ) { next = ( Long ) optimizer.generate( sequence ); assertEquals( i, next.intValue() ); } assertEquals( 1, sequence.getTimesCalled() ); // once to initialze state assertEquals( 1, sequence.getCurrentValue() ); // force a "clock over" next = ( Long ) optimizer.generate( sequence ); assertEquals( 11, next.intValue() ); assertEquals( 2, sequence.getTimesCalled() ); assertEquals( 2, sequence.getCurrentValue() ); // test historic table behavior, where the initial values started at 0 (we now force 1 to be the first used id value) sequence = new SourceMock( 0 ); optimizer = buildHiloOptimizer( -1, increment ); for ( int i = 1; i <= increment; i++ ) { next = ( Long ) optimizer.generate( sequence ); assertEquals( i, next.intValue() ); } assertEquals( 2, sequence.getTimesCalled() ); // here have have an extra call to get to 1 initially assertEquals( 1, sequence.getCurrentValue() ); // force a "clock over" next = ( Long ) optimizer.generate( sequence ); assertEquals( 11, next.intValue() ); assertEquals( 3, sequence.getTimesCalled() ); assertEquals( 2, sequence.getCurrentValue() ); }
3.333333
/** * Test default optimizer selection for sequence backed generators * based on the configured increment size; both in the case of the * dialect supporting pooled sequences (pooled) and not (hilo) */ @Test public void testDefaultOptimizerBasedOnIncrementBackedBySequence() { Properties props = buildGeneratorPropertiesBase(); props.setProperty( SequenceStyleGenerator.INCREMENT_PARAM, "10" ); // for dialects which do not support pooled sequences, we default to pooled+table Dialect dialect = new SequenceDialect(); SequenceStyleGenerator generator = new SequenceStyleGenerator(); generator.configure( StandardBasicTypes.LONG, props, dialect ); assertClassAssignability( TableStructure.class, generator.getDatabaseStructure().getClass() ); assertClassAssignability( PooledOptimizer.class, generator.getOptimizer().getClass() ); assertEquals( SequenceStyleGenerator.DEF_SEQUENCE_NAME, generator.getDatabaseStructure().getName() ); // for dialects which do support pooled sequences, we default to pooled+sequence dialect = new PooledSequenceDialect(); generator = new SequenceStyleGenerator(); generator.configure( StandardBasicTypes.LONG, props, dialect ); assertClassAssignability( SequenceStructure.class, generator.getDatabaseStructure().getClass() ); assertClassAssignability( PooledOptimizer.class, generator.getOptimizer().getClass() ); assertEquals( SequenceStyleGenerator.DEF_SEQUENCE_NAME, generator.getDatabaseStructure().getName() ); }
3.555556
public static void main(String[] args) { CustomVersionOneStrategy strategy = new CustomVersionOneStrategy(); for ( int i = 0; i < 1000; i++ ) { System.out.println( "Generation # " + i + " ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" ); byte[] loBits = new byte[8]; long sysTime = System.currentTimeMillis(); short hiTime = (short) ( System.currentTimeMillis() >>> 32 ); int loTime = (int) sysTime; System.arraycopy( BytesHelper.fromShort( hiTime ), 0, loBits, 0, 2 ); System.arraycopy( BytesHelper.fromInt( loTime ), 0, loBits, 2, 4 ); System.arraycopy( Helper.getCountBytes(), 0, loBits, 6, 2 ); System.out.println( " before bit setting ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" ); System.out.println( " loBits[0] : " + BytesHelper.toBinaryString( loBits[0] ) ); System.out.println( " lsb : " + BytesHelper.toBinaryString( BytesHelper.asLong( loBits ) ) ); System.out.println( " ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" ); loBits[0] &= 0x3f; loBits[0] |= ((byte)2 << (byte)6); System.out.println( " after bit setting ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" ); System.out.println( " loBits[0] : " + BytesHelper.toBinaryString( loBits[0] ) ); long leastSignificantBits = BytesHelper.asLong( loBits ); System.out.println( " lsb : " + BytesHelper.toBinaryString( leastSignificantBits ) ); System.out.println( " ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" ); UUID uuid = new UUID( strategy.mostSignificantBits, leastSignificantBits ); System.out.println( " uuid : " + uuid.toString() ); System.out.println( " variant : " + uuid.variant() ); System.out.println( " version : " + uuid.version() ); if ( uuid.variant() != 2 ) { throw new RuntimeException( "bad variant" ); } System.out.println( "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" ); } }
3.555556
public void doTestWithTupleSubsetResultTransformerNullAliases(TupleSubsetResultTransformer transformer) throws Exception { doTest( buildBasicKey( CacheableResultTransformer.create( transformer, null, new boolean[] { true } ) ) ); doTest( buildBasicKey( CacheableResultTransformer.create( transformer, null, new boolean[] { true, true } ) ) ); doTest( buildBasicKey( CacheableResultTransformer.create( transformer, null, new boolean[] { true, true, true } ) ) ); doTest( buildBasicKey( CacheableResultTransformer.create( transformer, null, new boolean[] { false, true } ) ) ); doTest( buildBasicKey( CacheableResultTransformer.create( transformer, null, new boolean[] { true, false } ) ) ); doTest( buildBasicKey( CacheableResultTransformer.create( transformer, null, new boolean[] { false, true, true } ) ) ); doTest( buildBasicKey( CacheableResultTransformer.create( transformer, null, new boolean[] {true, false, true } ) ) ); doTest( buildBasicKey( CacheableResultTransformer.create( transformer, null, new boolean[] {true, true, false } ) ) ); doTest( buildBasicKey( CacheableResultTransformer.create( transformer, null, new boolean[] {false, false, true } ) ) ); doTest( buildBasicKey( CacheableResultTransformer.create( transformer, null, new boolean[] {false, true, false } ) ) ); doTest( buildBasicKey( CacheableResultTransformer.create( transformer, null, new boolean[] {false, false, true } ) ) ); }
3.777778
public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Person)) return false; Person person = (Person) o; if (id != person.id) return false; if (name != null ? !name.equals(person.name) : person.name != null) return false; if (surname != null ? !surname.equals(person.surname) : person.surname != null) return false; return true; }
3.888889
private void readAndSetAddress(Scanner scanner, Person p) { Address old = p.getAddress(); String input = scanner.nextLine(); if ("NULL".equals(input)) { p.setAddress(null); if (old != null) { old.getPersons().remove(p); } } else if ("".equals(input)) { } else { try { Integer id = Integer.valueOf(input); Address a = entityManager.find(Address.class, id); if (a == null) { System.err.println("Unknown address id, setting to NULL."); p.setAddress(null); if (old != null) { old.getPersons().remove(p); } } else { p.setAddress(a); a.getPersons().add(p); if (old != null) { old.getPersons().remove(p); } } } catch (NumberFormatException e) { System.err.println("Invalid address id, setting to NULL."); p.setAddress(null); if (old != null) { old.getPersons().remove(p); } } } }
3.888889
/** * add statistics report of a DB query * * @param rows rows count returned * @param time time taken */ void executed(long rows, long time) { // read lock is enough, concurrent updates are supported by the underlying type AtomicLong // this only guards executed(long, long) to be called, when another thread is executing getExecutionAvgTime() readLock.lock(); try { // Less chances for a context switch for (long old = executionMinTime.get(); (time < old) && !executionMinTime.compareAndSet(old, time); old = executionMinTime.get()); for (long old = executionMaxTime.get(); (time > old) && !executionMaxTime.compareAndSet(old, time); old = executionMaxTime.get()); executionCount.getAndIncrement(); executionRowCount.addAndGet(rows); totalExecutionTime.addAndGet(time); } finally { readLock.unlock(); } }
3.333333
public String toString() { return new StringBuilder() .append("QueryStatistics") .append("[cacheHitCount=").append(this.cacheHitCount) .append(",cacheMissCount=").append(this.cacheMissCount) .append(",cachePutCount=").append(this.cachePutCount) .append(",executionCount=").append(this.executionCount) .append(",executionRowCount=").append(this.executionRowCount) .append(",executionAvgTime=").append(this.getExecutionAvgTime()) .append(",executionMaxTime=").append(this.executionMaxTime) .append(",executionMinTime=").append(this.executionMinTime) .append(']') .toString(); }
4
public String toString() { StringBuilder buf = new StringBuilder() .append("SecondLevelCacheStatistics") .append("[hitCount=").append(this.hitCount) .append(",missCount=").append(this.missCount) .append(",putCount=").append(this.putCount); //not sure if this would ever be null but wanted to be careful if (region != null) { buf.append(",elementCountInMemory=").append(this.getElementCountInMemory()) .append(",elementCountOnDisk=").append(this.getElementCountOnDisk()) .append(",sizeInMemory=").append(this.getSizeInMemory()); } buf.append(']'); return buf.toString(); }
3.888889
Object processEntity(Object value, EntityType entityType) throws HibernateException { if (value!=null) { getSession().getPersistenceContext().reassociateIfUninitializedProxy(value); // if it is an initialized proxy, let cascade // handle it later on } return null; }
4.555556
/** * 1. Recreate the collection key -> collection map * 2. rebuild the collection entries * 3. call Interceptor.postFlush() */ protected void postFlush(SessionImplementor session) throws HibernateException { LOG.trace( "Post flush" ); final PersistenceContext persistenceContext = session.getPersistenceContext(); persistenceContext.getCollectionsByKey().clear(); // the database has changed now, so the subselect results need to be invalidated // the batch fetching queues should also be cleared - especially the collection batch fetching one persistenceContext.getBatchFetchQueue().clear(); for ( Map.Entry<PersistentCollection, CollectionEntry> me : IdentityMap.concurrentEntries( persistenceContext.getCollectionEntries() ) ) { CollectionEntry collectionEntry = me.getValue(); PersistentCollection persistentCollection = me.getKey(); collectionEntry.postFlush(persistentCollection); if ( collectionEntry.getLoadedPersister() == null ) { //if the collection is dereferenced, remove from the session cache //iter.remove(); //does not work, since the entrySet is not backed by the set persistenceContext.getCollectionEntries() .remove(persistentCollection); } else { //otherwise recreate the mapping between the collection and its key CollectionKey collectionKey = new CollectionKey( collectionEntry.getLoadedPersister(), collectionEntry.getLoadedKey() ); persistenceContext.getCollectionsByKey().put(collectionKey, persistentCollection); } } }
3.444444
/** * Build a ParameterMemento from the given parameter registration * * @param registration The parameter registration from a ProcedureCall * * @return The memento */ public static ParameterMemento fromRegistration(ParameterRegistrationImplementor registration) { return new ParameterMemento( registration.getPosition(), registration.getName(), registration.getMode(), registration.getType(), registration.getHibernateType() ); }
4.666667
@Test public void testQueryCollectionOfValues() throws Exception { Session s = openSession(); s.beginTransaction(); Baz baz = new Baz(); baz.setDefaults(); s.save(baz); Glarch g = new Glarch(); Serializable gid = s.save(g); if ( !(getDialect() instanceof MySQLDialect) && !(getDialect() instanceof HSQLDialect) /*&& !(dialect instanceof MckoiDialect)*/ && !(getDialect() instanceof SAPDBDialect) && !(getDialect() instanceof PointbaseDialect) && !(getDialect() instanceof TimesTenDialect) ) { s.createFilter( baz.getFooArray(), "where size(this.bytes) > 0" ).list(); s.createFilter( baz.getFooArray(), "where 0 in elements(this.bytes)" ).list(); } s.getTransaction().commit(); s.close(); s = openSession(); s.beginTransaction(); s.createQuery( "from Baz baz join baz.fooSet foo join foo.foo.foo foo2 where foo2.string = 'foo'" ).list(); s.createQuery( "from Baz baz join baz.fooArray foo join foo.foo.foo foo2 where foo2.string = 'foo'" ).list(); s.createQuery( "from Baz baz join baz.stringDateMap date where index(date) = 'foo'" ).list(); s.createQuery( "from Baz baz join baz.topGlarchez g where index(g) = 'A'" ).list(); s.createQuery( "select index(g) from Baz baz join baz.topGlarchez g" ).list(); assertTrue( s.createQuery( "from Baz baz left join baz.stringSet" ).list().size()==3 ); baz = (Baz) s.createQuery( "from Baz baz join baz.stringSet str where str='foo'" ).list().get(0); assertTrue( !Hibernate.isInitialized( baz.getStringSet() ) ); baz = (Baz) s.createQuery( "from Baz baz left join fetch baz.stringSet" ).list().get(0); assertTrue( Hibernate.isInitialized( baz.getStringSet() ) ); assertTrue( s.createQuery( "from Baz baz join baz.stringSet string where string='foo'" ).list().size()==1 ); assertTrue( s.createQuery( "from Baz baz inner join baz.components comp where comp.name='foo'" ).list().size()==1 ); //List bss = s.find("select baz, ss from Baz baz inner join baz.stringSet ss"); s.createQuery( "from Glarch g inner join g.fooComponents comp where comp.fee is not null" ).list(); s.createQuery( "from Glarch g inner join g.fooComponents comp join comp.fee fee where fee.count > 0" ).list(); s.createQuery( "from Glarch g inner join g.fooComponents comp where comp.fee.count is not null" ).list(); s.delete(baz); s.delete( s.get(Glarch.class, gid) ); s.getTransaction().commit(); s.close(); }
2.888889
@SkipForDialect(value = AbstractHANADialect.class, comment = "HANA currently requires specifying table name by 'FOR UPDATE of t1.c1' if there are more than one tables/views/subqueries in the FROM clause") @Test public void testRefresh() throws Exception { final Session s = openSession(); s.beginTransaction(); Foo foo = new Foo(); s.save( foo ); s.flush(); s.doWork( new AbstractWork() { @Override public void execute(Connection connection) throws SQLException { final String sql = "update " + getDialect().openQuote() + "foos" + getDialect().closeQuote() + " set long_ = -3"; Statement st = connection.createStatement(); st.executeUpdate( sql ); } } ); s.refresh(foo); assertEquals( Long.valueOf( -3l ), foo.getLong() ); assertEquals( LockMode.READ, s.getCurrentLockMode( foo ) ); s.refresh(foo, LockMode.UPGRADE); if ( getDialect().supportsOuterJoinForUpdate() ) { assertEquals( LockMode.UPGRADE, s.getCurrentLockMode( foo ) ); } s.delete(foo); s.getTransaction().commit(); s.close(); }
3
public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof OuterKey)) return false; final OuterKey cidDetailID = (OuterKey) o; if (detailId != null ? !detailId.equals(cidDetailID.detailId) : cidDetailID.detailId != null) return false; if (master != null ? !master.equals(cidDetailID.master) : cidDetailID.master != null) return false; return true; }
3.222222
@Test @SkipForDialect( { HSQLDialect.class, PostgreSQL81Dialect.class, PostgreSQLDialect.class } ) public void testEscapedJDBC() throws HibernateException, SQLException { Session session = openSession(); session.beginTransaction(); for ( Object entity : session.createQuery( "from A" ).list() ) { session.delete( entity ); } A savedA = new A(); savedA.setName("Max"); session.save(savedA); B savedB = new B(); session.save(savedB); session.flush(); int count = session.createQuery("from A").list().size(); session.getTransaction().commit(); session.close(); session = openSession(); session.beginTransaction(); Query query; if( getDialect() instanceof TimesTenDialect) { // TimesTen does not permit general expressions (like UPPER) in the second part of a LIKE expression, // so we execute a similar test query = session.createSQLQuery("select identifier_column as {a.id}, clazz_discriminata as {a.class}, count_ as {a.count}, name as {a.name} from TA where {fn ucase(name)} like 'MAX'" ) .addEntity( "a", A.class ); } else { query = session.createSQLQuery( "select identifier_column as {a.id}, clazz_discriminata as {a.class}, count_ as {a.count}, name as {a.name} from TA where {fn ucase(name)} like {fn ucase('max')}" ) .addEntity( "a", A.class ); } List list = query.list(); assertNotNull(list); assertEquals(1, list.size()); session.getTransaction().commit(); session.close(); }
3.555556
@Test @TestForIssue( jiraKey = "HHH-21" ) public void testCompositeIdId() throws HibernateException, SQLException { Session s = openSession(); s.beginTransaction(); CompositeIdId id = new CompositeIdId(); id.setName("Max"); id.setSystem("c64"); id.setId("games"); s.save(id); s.getTransaction().commit(); s.close(); s = openSession(); s.beginTransaction(); // having a composite id with one property named id works since the map used by sqlloader to map names to properties handles it. String sql = "select system as {c.system}, id as {c.id}, name as {c.name}, foo as {c.composite.foo}, bar as {c.composite.bar} from CompositeIdId where system=? and id=?"; SQLQuery query = s.createSQLQuery( sql ).addEntity( "c", CompositeIdId.class ); query.setString(0, "c64"); query.setString(1, "games"); CompositeIdId id2 = (CompositeIdId) query.uniqueResult(); check(id, id2); s.getTransaction().commit(); s.close(); s = openSession(); s.beginTransaction(); CompositeIdId useForGet = new CompositeIdId(); useForGet.setSystem("c64"); useForGet.setId("games"); // this doesn't work since the verification does not take column span into respect! CompositeIdId getted = (CompositeIdId) s.get(CompositeIdId.class, useForGet); check(id,getted); s.getTransaction().commit(); s.close(); }
3.222222
@Override public void runTest(final Test test, final TestResult result) { Thread t = new Thread() { @Override public void run() { try { // inlined due to limitation in VA/Java //ActiveTestSuite.super.runTest(test, result); test.run(result); } finally { ActiveTestSuite.this.runFinished(); } } }; t.start(); }
4.555556
public boolean equalsFoo(Foo other) { if ( _bytes!=other._bytes ) { if ( _bytes==null || other._bytes==null ) return false; if ( _bytes.length!=other._bytes.length ) return false; for ( int i=0; i< _bytes.length; i++) { if ( _bytes[i] != other._bytes[i] ) return false; } } return ( this._bool == other._bool ) && ( ( this._boolean == other._boolean ) || ( this._boolean.equals(other._boolean) ) ) && ( ( this._byte == other._byte ) || ( this._byte.equals(other._byte) ) ) //&& ( ( this._date == other._date ) || ( this._date.getDate() == other._date.getDate() && this._date.getMonth() == other._date.getMonth() && this._date.getYear() == other._date.getYear() ) ) && ( ( this._double == other._double ) || ( this._double.equals(other._double) ) ) && ( ( this._float == other._float ) || ( this._float.equals(other._float) ) ) && ( this._int == other._int ) && ( ( this._integer == other._integer ) || ( this._integer.equals(other._integer) ) ) && ( ( this._long == other._long ) || ( this._long.equals(other._long) ) ) && ( this._null == other._null ) && ( ( this._short == other._short ) || ( this._short.equals(other._short) ) ) && ( ( this._string == other._string) || ( this._string.equals(other._string) ) ) //&& ( ( this._timestamp==other._timestamp) || ( this._timestamp.getDate() == other._timestamp.getDate() && this._timestamp.getYear() == other._timestamp.getYear() && this._timestamp.getMonth() == other._timestamp.getMonth() ) ) && ( this._zero == other._zero ) && ( ( this._foo == other._foo ) || ( this._foo.getKey().equals( other._foo.getKey() ) ) ) && ( ( this.blob == other.blob ) || ( this.blob.equals(other.blob) ) ) && ( this.yesno == other.yesno ) && ( ( this.binary == other.binary ) || java.util.Arrays.equals(this.binary, other.binary) ) && ( this.key.equals(other.key) ) && ( this.theLocale.equals(other.theLocale) ) && ( ( this.custom == other.custom ) || ( this.custom[0].equals(other.custom[0]) && this.custom[1].equals(other.custom[1]) ) ); }
1.888889
@Test public void testSerializationFailsOnAfterStatementAggressiveReleaseWithOpenResources() throws Throwable { prepare(); Session s = getSessionUnderTest(); Silly silly = new Silly( "silly" ); s.save( silly ); // this should cause the CM to obtain a connection, and then release it s.flush(); // both scroll() and iterate() cause batching to hold on // to resources, which should make aggressive-release not release // the connection (and thus cause serialization to fail) ScrollableResults sr = s.createQuery( "from Silly" ).scroll(); try { SerializationHelper.serialize( s ); fail( "Serialization allowed on connected session; or aggressive release released connection with open resources" ); } catch( IllegalStateException e ) { // expected behavior } // getting the first row only because SybaseASE15Dialect throws NullPointerException // if data is not read before closing the ResultSet sr.next(); // Closing the ScrollableResults does currently force batching to // aggressively release the connection sr.close(); SerializationHelper.serialize( s ); s.delete( silly ); s.flush(); release( s ); done(); }
3.888889
@Override protected void prepareTest() throws Exception { Session s = openSession(); Transaction t = s.beginTransaction(); Child child_1_1 = new Child( "achild1-1"); Child child_1_2 = new Child( "ychild1-2"); Child child_1_3 = new Child( "dchild1-3"); Child child_2_1 = new Child( "bchild2-1"); Child child_2_2 = new Child( "cchild2-2"); Child child_2_3 = new Child( "zchild2-3"); s.save( child_1_1 ); s.save( child_2_1 ); s.save( child_1_2 ); s.save( child_2_2 ); s.save( child_1_3 ); s.save( child_2_3 ); s.flush(); Parent p1 = new Parent( "parent1" ); p1.addChild( child_1_1 ); p1.addChild( child_1_2 ); p1.addChild( child_1_3 ); s.save( p1 ); Parent p2 = new Parent( "parent2" ); p2.addChild( child_2_1 ); p2.addChild( child_2_2 ); p2.addChild( child_2_3 ); s.save( p2 ); t.commit(); s.close(); }
4.444444
@Test @TestForIssue( jiraKey = "HHH-2045" ) @RequiresDialect( H2Dialect.class ) public void testEmptyInList() { Session session = openSession(); session.beginTransaction(); Human human = new Human(); human.setName( new Name( "Lukasz", null, "Antoniak" ) ); human.setNickName( "NONE" ); session.save( human ); session.getTransaction().commit(); session.close(); session = openSession(); session.beginTransaction(); List results = session.createQuery( "from Human h where h.nickName in ()" ).list(); assertEquals( 0, results.size() ); session.getTransaction().commit(); session.close(); session = openSession(); session.beginTransaction(); session.delete( human ); session.getTransaction().commit(); session.close(); }
4.444444
@Test @TestForIssue( jiraKey = "HHH-2257" ) public void testImplicitJoinsInDifferentClauses() { // both the classic and ast translators output the same syntactically valid sql // for all of these cases; the issue is that shallow (iterate) and // non-shallow (list/scroll) queries return different results because the // shallow skips the inner join which "weeds out" results from the non-shallow queries. // The results were initially different depending upon the clause(s) in which the // implicit join occurred Session s = openSession(); s.beginTransaction(); SimpleEntityWithAssociation owner = new SimpleEntityWithAssociation( "owner" ); SimpleAssociatedEntity e1 = new SimpleAssociatedEntity( "thing one", owner ); SimpleAssociatedEntity e2 = new SimpleAssociatedEntity( "thing two" ); s.save( e1 ); s.save( e2 ); s.save( owner ); s.getTransaction().commit(); s.close(); checkCounts( "select e.owner from SimpleAssociatedEntity e", 1, "implicit-join in select clause" ); checkCounts( "select e.id, e.owner from SimpleAssociatedEntity e", 1, "implicit-join in select clause" ); // resolved to a "id short cut" when part of the order by clause -> no inner join = no weeding out... checkCounts( "from SimpleAssociatedEntity e order by e.owner", 2, "implicit-join in order-by clause" ); // resolved to a "id short cut" when part of the group by clause -> no inner join = no weeding out... checkCounts( "select e.owner.id, count(*) from SimpleAssociatedEntity e group by e.owner", 2, "implicit-join in select and group-by clauses" ); s = openSession(); s.beginTransaction(); s.delete( e1 ); s.delete( e2 ); s.delete( owner ); s.getTransaction().commit(); s.close(); }
3.777778
@Test @TestForIssue( jiraKey = "HHH-1631" ) public void testSubclassOrSuperclassPropertyReferenceInJoinedSubclass() { // this is a long standing bug in Hibernate; see HHH-1631 for details and history // // (1) pregnant is defined as a property of the class (Mammal) itself // (2) description is defined as a property of the superclass (Animal) // (3) name is defined as a property of a particular subclass (Human) new SyntaxChecker( "from Zoo z join z.mammals as m where m.name.first = 'John'" ).checkIterate(); new SyntaxChecker( "from Zoo z join z.mammals as m where m.pregnant = false" ).checkAll(); new SyntaxChecker( "select m.pregnant from Zoo z join z.mammals as m where m.pregnant = false" ).checkAll(); new SyntaxChecker( "from Zoo z join z.mammals as m where m.description = 'tabby'" ).checkAll(); new SyntaxChecker( "select m.description from Zoo z join z.mammals as m where m.description = 'tabby'" ).checkAll(); new SyntaxChecker( "from Zoo z join z.mammals as m where m.name.first = 'John'" ).checkAll(); new SyntaxChecker( "select m.name from Zoo z join z.mammals as m where m.name.first = 'John'" ).checkAll(); new SyntaxChecker( "select m.pregnant from Zoo z join z.mammals as m" ).checkAll(); new SyntaxChecker( "select m.description from Zoo z join z.mammals as m" ).checkAll(); new SyntaxChecker( "select m.name from Zoo z join z.mammals as m" ).checkAll(); new SyntaxChecker( "from DomesticAnimal da join da.owner as o where o.nickName = 'Gavin'" ).checkAll(); new SyntaxChecker( "select da.father from DomesticAnimal da join da.owner as o where o.nickName = 'Gavin'" ).checkAll(); new SyntaxChecker( "select da.father from DomesticAnimal da where da.owner.nickName = 'Gavin'" ).checkAll(); }
4.333333