Dataset Viewer
Auto-converted to Parquet Duplicate
id
stringlengths
19
22
content
stringlengths
187
14.2k
max_stars_repo_path
stringlengths
15
210
satd-removal_data_1
TODO: make this a big red scary button @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (mDisk == null) { finish(); return; } setContentView(R.layout.storage_wizard_generic); mFormatPrivate = getIntent().getBooleanExtra(EXTRA_FORMAT_PRIVATE, false); if (mFormatPrivate) { setHeaderText(R.string.storage_wizard_format_confirm_title); setBodyText(R.string.storage_wizard_format_confirm_body, mDisk.getDescription()); } else { setHeaderText(R.string.storage_wizard_format_confirm_public_title); setBodyText(R.string.storage_wizard_format_confirm_public_body, mDisk.getDescription()); } // TODO: make this a big red scary button getNextButton().setText(R.string.storage_wizard_format_confirm_next); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (mDisk == null) { finish(); return; } setContentView(R.layout.storage_wizard_generic); mFormatPrivate = getIntent().getBooleanExtra(EXTRA_FORMAT_PRIVATE, false); setIllustrationInternal(mFormatPrivate); if (mFormatPrivate) { setHeaderText(R.string.storage_wizard_format_confirm_title); setBodyText(R.string.storage_wizard_format_confirm_body, mDisk.getDescription()); } else { setHeaderText(R.string.storage_wizard_format_confirm_public_title); setBodyText(R.string.storage_wizard_format_confirm_public_body, mDisk.getDescription()); } getNextButton().setText(R.string.storage_wizard_format_confirm_next); getNextButton().setBackgroundTintList(getColorStateList(R.color.storage_wizard_button_red)); }
src/com/android/settings/deviceinfo/StorageWizardFormatConfirm.java
satd-removal_data_2
TODO: catch expectation failures and resignal correctly public void invokeWithJavaArgs(Object[] args) throws Throwable { IokeObject msg = ioke.newMessage("invoke"); Message invoke = (Message) IokeObject.data(msg); // TODO: catch expectation failures and resignal correctly List<Runtime.RescueInfo> pendingRescues = new ArrayList<Runtime.RescueInfo>(); IokeObject rr = IokeObject.as(((Message)IokeObject.data(ioke.mimic)).sendTo(ioke.mimic, ioke.ground, ioke.rescue), ioke.ground); List<Object> conds = new ArrayList(); final IokeObject pendingCondition = IokeObject.as(IokeObject.getCellChain(ioke.condition, ioke.message, ioke.ground, "Pending"), ioke.ground); conds.add(pendingCondition); pendingRescues.add(new Runtime.RescueInfo(rr, conds, pendingRescues, ioke.getBindIndex())); ioke.registerRescues(pendingRescues); try { invoke.sendTo(msg, iokeStepDefObject, iokeStepDefObject, multilineArg(args)); } catch(ControlFlow.Rescue e) { if(e.getRescue().token == pendingRescues) { throw JRuby.cucumberPending("TODO"); // throw (Exception)(e.getCondition().getCell(ioke.message, ioke.ground, "rootException")); } else { throw e; } } finally { ioke.unregisterRescues(pendingRescues); } } public void invokeWithJavaArgs(Object[] args) throws Throwable { IokeObject msg = ioke.newMessage("invoke"); Message invoke = (Message) IokeObject.data(msg); List<Runtime.RescueInfo> pendingRescues = new ArrayList<Runtime.RescueInfo>(); IokeObject rr = IokeObject.as(((Message)IokeObject.data(ioke.mimic)).sendTo(ioke.mimic, ioke.ground, ioke.rescue), ioke.ground); List<Object> conds = new ArrayList(); conds.add(lang.pendingCondition); pendingRescues.add(new Runtime.RescueInfo(rr, conds, pendingRescues, ioke.getBindIndex())); ioke.registerRescues(pendingRescues); List<Runtime.RescueInfo> failureRescues = new ArrayList<Runtime.RescueInfo>(); IokeObject rr2 = IokeObject.as(((Message)IokeObject.data(ioke.mimic)).sendTo(ioke.mimic, ioke.ground, ioke.rescue), ioke.ground); List<Object> failureConds = new ArrayList(); failureConds.add(lang.failedExpectationCondition); failureRescues.add(new Runtime.RescueInfo(rr2, failureConds, failureRescues, ioke.getBindIndex())); ioke.registerRescues(failureRescues); try { invoke.sendTo(msg, iokeStepDefObject, iokeStepDefObject, multilineArg(args)); } catch(ControlFlow.Rescue e) { if(e.getRescue().token == pendingRescues) { throw JRuby.cucumberPending("TODO"); } else if(e.getRescue().token == failureRescues) { throwCucumberIokeException(((Message)IokeObject.data(ioke.reportMessage)).sendTo(ioke.reportMessage, ioke.ground, e.getCondition()).toString()); } else { throw e; } } finally { ioke.unregisterRescues(failureRescues); ioke.unregisterRescues(pendingRescues); } }
cuke4duke/src/main/java/cuke4duke/internal/ik/IkStepDefinition.java
satd-removal_data_3
FIXME: this is broken and untested (it should set the mark instead of limit) public void mark() { // FIXME: this is broken and untested (it should set the mark instead of limit) this.limit = position.duplicate(); } public void mark() { this.mark = position.duplicate(); }
codec/src/main/java/org/apache/mina/codec/IoBuffer.java
satd-removal_data_4
TODO support unicode! private static StringBuilder ioListToStringBuilder(final OtpErlangObject o, final StringBuilder sb0, final int maxLength) { StringBuilder sb = sb0; if (sb.length() >= maxLength) { return sb; } if (o instanceof OtpErlangLong) { final OtpErlangLong l = (OtpErlangLong) o; try { sb.append(l.charValue()); } catch (final OtpErlangRangeException e) { } } else if (o instanceof OtpErlangString) { final OtpErlangString s = (OtpErlangString) o; sb.append(s.stringValue()); } else if (o instanceof OtpErlangList) { final OtpErlangList l = (OtpErlangList) o; for (final OtpErlangObject i : l) { if (sb.length() < maxLength) { ioListToStringBuilder(i, sb, maxLength); } } if (sb.length() < maxLength) { ioListToStringBuilder(l.getLastTail(), sb, maxLength); } } else if (o instanceof OtpErlangBinary) { final OtpErlangBinary b = (OtpErlangBinary) o; // TODO support unicode! final String s = new String(b.binaryValue(), Charsets.ISO_8859_1); sb.append(s); } else if (o != null) { sb.append(o.toString()); } if (sb.length() > maxLength) { sb = new StringBuilder(sb.substring(0, maxLength)); sb.append("... <truncated>"); } return sb; } private static StringBuilder ioListToStringBuilder(final OtpErlangObject o, final StringBuilder sb0, final int maxLength) { StringBuilder sb = sb0; if (sb.length() >= maxLength) { return sb; } if (o instanceof OtpErlangLong) { final OtpErlangLong l = (OtpErlangLong) o; try { sb.append(l.charValue()); } catch (final OtpErlangRangeException e) { } } else if (o instanceof OtpErlangString) { final OtpErlangString s = (OtpErlangString) o; sb.append(s.stringValue()); } else if (o instanceof OtpErlangList) { final OtpErlangList l = (OtpErlangList) o; for (final OtpErlangObject i : l) { if (sb.length() < maxLength) { ioListToStringBuilder(i, sb, maxLength); } } if (sb.length() < maxLength) { ioListToStringBuilder(l.getLastTail(), sb, maxLength); } } else if (o instanceof OtpErlangBinary) { final OtpErlangBinary b = (OtpErlangBinary) o; String s = decode(b.binaryValue(), Charsets.UTF_8); if (s == null) { s = new String(b.binaryValue(), Charsets.ISO_8859_1); } sb.append(s); } else if (o != null) { sb.append(o.toString()); } if (sb.length() > maxLength) { sb = new StringBuilder(sb.substring(0, maxLength)); sb.append("... <truncated>"); } return sb; }
org.erlide.util/src/org/erlide/util/Util.java
satd-removal_data_5
todo: need a reciprocal stop protected void internalNonBlockingStart() throws IOException { try { // copy TezConfiguration workingConf = new TezConfiguration( currentConf ); prepareEnsureStagingDir( workingConf ); tezClient = TezClient.create( flowStep.getName(), workingConf, Collections.<String, LocalResource>emptyMap(), credentials ); tezClient.start(); // todo: need a reciprocal stop dagClient = tezClient.submitDAG( dag ); flowStep.logInfo( "submitted tez dag: " + dagClient.getExecutionContext() ); // if( dagClient.getApplicationReport() != null && dagClient.getApplicationReport().getTrackingUrl() != null ) // flowStep.logInfo( "tracking url: " + dagClient.getApplicationReport().getTrackingUrl() ); } catch( TezException exception ) { throw new CascadingException( exception ); } } protected void internalNonBlockingStart() throws IOException { try { TezConfiguration workingConf = new TezConfiguration( currentConf ); if( !workingConf.getBoolean( YarnConfiguration.TIMELINE_SERVICE_ENABLED, YarnConfiguration.DEFAULT_TIMELINE_SERVICE_ENABLED ) ) flowStep.logWarn( "'" + YarnConfiguration.TIMELINE_SERVICE_ENABLED + "' is disabled, please enable to capture detailed metrics of completed flows, this may require starting the YARN timeline server daemon." ); // this could be problematic flowStep.logInfo( "tez session mode enabled: " + workingConf.getBoolean( TezConfiguration.TEZ_AM_SESSION_MODE, TezConfiguration.TEZ_AM_SESSION_MODE_DEFAULT ) ); prepareEnsureStagingDir( workingConf ); tezClient = TezClient.create( flowStep.getName(), workingConf, false ); tezClient.start(); dagClient = tezClient.submitDAG( dag ); flowStep.logInfo( "submitted tez dag to app master: " + tezClient.getAppMasterApplicationId() ); } catch( TezException exception ) { throw new CascadingException( exception ); } }
cascading-hadoop2-tez/src/main/java/cascading/flow/tez/planner/Hadoop2TezFlowStepJob.java
satd-removal_data_6
XXX: REMOVE THIS SYNCHRONIZED: once threading issues in AS7 WS are fixed public void start() throws WebServicePublishException { ClassLoader origLoader = Thread.currentThread().getContextClassLoader(); //XXX: REMOVE THIS SYNCHRONIZED: once threading issues in AS7 WS are fixed synchronized (BaseWebService.class) { try { _service = _domain.getServiceReference(_config.getServiceName()); PortName portName = _config.getPort(); javax.wsdl.Service wsdlService = WSDLUtil.getService(_config.getWsdl(), portName); _wsdlPort = WSDLUtil.getPort(wsdlService, portName); // Update the portName portName.setServiceQName(wsdlService.getQName()); portName.setName(_wsdlPort.getName()); BaseWebService wsProvider = new BaseWebService(); wsProvider.setInvocationClassLoader(Thread.currentThread().getContextClassLoader()); // Hook the handler wsProvider.setConsumer(this); List<Source> metadata = new ArrayList<Source>(); StreamSource source = WSDLUtil.getStream(_config.getWsdl()); metadata.add(source); Map<String, Object> properties = new HashMap<String, Object>(); properties.put(Endpoint.WSDL_SERVICE, portName.getServiceQName()); properties.put(Endpoint.WSDL_PORT, portName.getPortQName()); properties.put(WSDL_LOCATION, WSDLUtil.getURL(_config.getWsdl()).toExternalForm()); String path = "/" + portName.getServiceName(); if (_config.getContextPath() != null) { path = "/" + _config.getContextPath() + "/" + portName.getServiceName(); } String publishUrl = _scheme + "://" + _config.getSocketAddr().getHost() + ":" + _config.getSocketAddr().getPort() + path; LOGGER.info("Publishing WebService at " + publishUrl); // make sure we don't pollute the class loader used by the WS subsystem Thread.currentThread().setContextClassLoader(getClass().getClassLoader()); _endpoint = Endpoint.create(wsProvider); _endpoint.setMetadata(metadata); _endpoint.setProperties(properties); _endpoint.publish(publishUrl); } catch (MalformedURLException e) { throw new WebServicePublishException(e); } catch (WSDLException e) { throw new WebServicePublishException(e); } finally { Thread.currentThread().setContextClassLoader(origLoader); } } } public void start() throws WebServicePublishException { ClassLoader origLoader = Thread.currentThread().getContextClassLoader(); try { _service = _domain.getServiceReference(_config.getServiceName()); PortName portName = _config.getPort(); javax.wsdl.Service wsdlService = WSDLUtil.getService(_config.getWsdl(), portName); _wsdlPort = WSDLUtil.getPort(wsdlService, portName); // Update the portName portName.setServiceQName(wsdlService.getQName()); portName.setName(_wsdlPort.getName()); BaseWebService wsProvider = new BaseWebService(); wsProvider.setInvocationClassLoader(Thread.currentThread().getContextClassLoader()); // Hook the handler wsProvider.setConsumer(this); List<Source> metadata = new ArrayList<Source>(); StreamSource source = WSDLUtil.getStream(_config.getWsdl()); metadata.add(source); Map<String, Object> properties = new HashMap<String, Object>(); properties.put(Endpoint.WSDL_SERVICE, portName.getServiceQName()); properties.put(Endpoint.WSDL_PORT, portName.getPortQName()); properties.put(WSDL_LOCATION, WSDLUtil.getURL(_config.getWsdl()).toExternalForm()); String path = "/" + portName.getServiceName(); if (_config.getContextPath() != null) { path = "/" + _config.getContextPath() + "/" + portName.getServiceName(); } String publishUrl = _scheme + "://" + _config.getSocketAddr().getHost() + ":" + _config.getSocketAddr().getPort() + path; LOGGER.info("Publishing WebService at " + publishUrl); // make sure we don't pollute the class loader used by the WS subsystem Thread.currentThread().setContextClassLoader(getClass().getClassLoader()); _endpoint = Endpoint.create(wsProvider); _endpoint.setMetadata(metadata); _endpoint.setProperties(properties); _endpoint.publish(publishUrl); } catch (MalformedURLException e) { throw new WebServicePublishException(e); } catch (WSDLException e) { throw new WebServicePublishException(e); } finally { Thread.currentThread().setContextClassLoader(origLoader); } }
soap/src/main/java/org/switchyard/component/soap/InboundHandler.java
satd-removal_data_7
TODO 428889 extract root feature seeds on this class loader side @Test public void testPublishingWithRootFeatures() { File productDefinition = resourceFile("publishers/products/rootFeatures.product"); subject = initPublisher(createFeatureIU("org.eclipse.rcp", "4.4.0.v20140128"), createFeatureIU("org.eclipse.e4.rcp", "1.0"), createFeatureIU("org.eclipse.help", "2.0.102.v20140128"), createFeatureIU("org.eclipse.egit", "2.0")); // TODO 428889 this information shall come from the IProductDescriptor Set<String> rootFeatures = new HashSet<String>(asList("org.eclipse.help", "org.eclipse.egit")); IInstallableUnit unit = getUnit(subject.publishProduct(productDefinition, rootFeatures, null, FLAVOR)); assertThat(unit.getRequirements(), hasItem(requirement("org.eclipse.rcp.feature.group", "4.4.0.v20140128"))); assertThat(unit.getRequirements(), hasItem(requirement("org.eclipse.e4.rcp.feature.group", "1.0"))); assertThat(unit.getRequirements(), not(hasItem(requirement("org.eclipse.help.feature.group", "2.0.102.v20140128")))); assertThat(unit.getRequirements(), not(hasItem(requirement("org.eclipse.egit.feature.group", "2.0")))); // TODO 428889 extract root feature seeds on this class loader side } @Test public void testPublishingWithRootFeatures() { File productDefinition = resourceFile("publishers/products/rootFeatures.product"); subject = initPublisher(createFeatureIU("org.eclipse.rcp", "4.4.0.v20140128"), createFeatureIU("org.eclipse.e4.rcp", "1.0"), createFeatureIU("org.eclipse.help", "2.0.102.v20140128"), createFeatureIU("org.eclipse.egit", "2.0")); List<DependencySeed> seeds = subject.publishProduct(productDefinition, null, FLAVOR); IInstallableUnit productUnit = getUnique(productUnit(), unitsIn(seeds)); assertThat(productUnit.getRequirements(), hasItem(requirement("org.eclipse.rcp.feature.group", "4.4.0.v20140128"))); assertThat(productUnit.getRequirements(), hasItem(requirement("org.eclipse.e4.rcp.feature.group", "1.0"))); assertThat(productUnit.getRequirements(), not(hasItem(requirement("org.eclipse.help.feature.group", "2.0.102.v20140128")))); assertThat(productUnit.getRequirements(), not(hasItem(requirement("org.eclipse.egit.feature.group", "2.0")))); assertThat(seeds.get(1).getId(), is("org.eclipse.help")); assertThat((IInstallableUnit) seeds.get(1).getInstallableUnit(), is(unitWithId("org.eclipse.help.feature.group"))); assertThat(seeds.get(2).getId(), is("org.eclipse.egit")); assertThat((IInstallableUnit) seeds.get(2).getInstallableUnit(), is(unitWithId("org.eclipse.egit.feature.group"))); assertThat(seeds, hasSize(3)); }
tycho-bundles/org.eclipse.tycho.p2.tools.tests/src/test/java/org/eclipse/tycho/p2/tools/publisher/PublishProductToolTest.java
satd-removal_data_8
TODO Check for existence of the getter and skip it (+ warn) if it's already there. @Override public void handle(AnnotationValues<Getter> annotation, JCAnnotation ast, JavacAST.Node annotationNode) { //TODO Check for existence of the getter and skip it (+ warn) if it's already there. if ( annotationNode.up().getKind() != Kind.FIELD ) { annotationNode.addError("@Getter is only supported on a field."); return; } Getter getter = annotation.getInstance(); JCClassDecl javacClassTree = (JCClassDecl) annotationNode.up().up().get(); int access = toJavacModifier(getter.value()); JCMethodDecl getterMethod = createGetter(access, annotationNode.up(), annotationNode.getTreeMaker()); javacClassTree.defs = javacClassTree.defs.append(getterMethod); } @Override public void handle(AnnotationValues<Getter> annotation, JCAnnotation ast, JavacAST.Node annotationNode) { if ( annotationNode.up().getKind() != Kind.FIELD ) { annotationNode.addError("@Getter is only supported on a field."); return; } String methodName = toGetterName((JCVariableDecl) annotationNode.up().get()); if ( methodExists(methodName, annotationNode.up()) ) { annotationNode.addWarning( String.format("Not generating %s(): A method with that name already exists", methodName)); return; } Getter getter = annotation.getInstance(); JCClassDecl javacClassTree = (JCClassDecl) annotationNode.up().up().get(); int access = toJavacModifier(getter.value()); JCMethodDecl getterMethod = createGetter(access, annotationNode.up(), annotationNode.getTreeMaker()); javacClassTree.defs = javacClassTree.defs.append(getterMethod); }
src/lombok/javac/handlers/HandleGetter.java
satd-removal_data_9
TODO: Web Hosting #118779 @Test public void testListImagesDetail() throws Exception { List<Image> response = connection.listImageDetails(); assert null != response; long imageCount = response.size(); assertTrue(imageCount >= 0); for (Image image : response) { assertTrue(image.getId() >= 1); assert null != image.getName() : image; // TODO: Web Hosting #118779 // assert null != image.getCreated() : image; // assert null != image.getUpdated() : image; assert null != image.getStatus() : image; } } @Test public void testListImagesDetail() throws Exception { List<Image> response = connection.listImageDetails(); assert null != response; long imageCount = response.size(); assertTrue(imageCount >= 0); for (Image image : response) { assertTrue(image.getId() >= 1); assert null != image.getName() : image; // sometimes this is not present per: Web Hosting #118820 // assert null != image.getCreated() : image; assert null != image.getUpdated() : image; assert null != image.getStatus() : image; } }
rackspace/cloudservers/core/src/test/java/org/jclouds/rackspace/cloudservers/CloudServersConnectionLiveTest.java
satd-removal_data_10
TODO record duration @Override public void callRecordComplete(ResourceEvent event) { Qualifier q = event.getQualifier(); RecordCompleteEvent.Cause cause = RecordCompleteEvent.Cause.UNKNOWN; String errorText = null; if (q == SpeechDetectorConstants.INITIAL_TIMEOUT_EXPIRED) { cause = RecordCompleteEvent.Cause.INI_TIMEOUT; } else if (q == ResourceEvent.STOPPED) { if (callRecording.isNormalDisconnect()) { cause = RecordCompleteEvent.Cause.DISCONNECT; } else { cause = RecordCompleteEvent.Cause.CANCEL; } } else if (q == ResourceEvent.RTC_TRIGGERED) { cause = RecordCompleteEvent.Cause.CANCEL; } else if (q == ResourceEvent.NO_QUALIFIER) { if (event.getError() != ResourceEvent.NO_ERROR) { cause = RecordCompleteEvent.Cause.ERROR; } errorText = event.getError() + ": " + event.getErrorText(); } // TODO record duration final RecordCompleteEvent<T> recordCompleteEvent = new MohoRecordCompleteEvent<T>(_parent, cause, _dialect.getCallRecordDuration(event), errorText, callRecording); _parent.dispatch(recordCompleteEvent); callRecording.done(recordCompleteEvent); _futures.remove(callRecording); } @Override public void callRecordComplete(ResourceEvent event) { Qualifier q = event.getQualifier(); RecordCompleteEvent.Cause cause = RecordCompleteEvent.Cause.UNKNOWN; String errorText = null; if (q == SpeechDetectorConstants.INITIAL_TIMEOUT_EXPIRED) { cause = RecordCompleteEvent.Cause.INI_TIMEOUT; } else if (q == ResourceEvent.STOPPED) { if (callRecording.isNormalDisconnect()) { cause = RecordCompleteEvent.Cause.DISCONNECT; } else { cause = RecordCompleteEvent.Cause.CANCEL; } } else if (q == ResourceEvent.RTC_TRIGGERED) { cause = RecordCompleteEvent.Cause.CANCEL; } else if (q == ResourceEvent.NO_QUALIFIER) { if (event.getError() != ResourceEvent.NO_ERROR) { cause = RecordCompleteEvent.Cause.ERROR; } errorText = event.getError() + ": " + event.getErrorText(); } final RecordCompleteEvent<T> recordCompleteEvent = new MohoRecordCompleteEvent<T>(_parent, cause, _dialect.getCallRecordDuration(event), errorText, callRecording); _parent.dispatch(recordCompleteEvent); callRecording.done(recordCompleteEvent); _futures.remove(callRecording); if(callRecording.getMaxDurationTimerFuture() != null) { callRecording.getMaxDurationTimerFuture().cancel(true); ((ApplicationContextImpl) _context).getScheduledEcutor().remove(callRecording.getMaxDurationTask()); ((ApplicationContextImpl) _context).getScheduledEcutor().purge(); } }
moho-impl/src/main/java/com/voxeo/moho/media/GenericMediaService.java
satd-removal_data_11
TODO: Is this where we should handle this? public void generateTables(String schemaName, String tableName, Connection conn, DatabaseMetaData meta) throws SQLException { fireGenerationEvent(_loc.get("generating-columns", schemaName, tableName)); if (_log.isTraceEnabled()) _log.trace(_loc.get("gen-tables", schemaName, tableName)); Column[] cols = _dict.getColumns(meta, conn.getCatalog(), schemaName, tableName, null, conn); // when we want to get all the columns for all tables, we need to build // a list of tables to verify because some databases (e.g., Postgres) // will include indexes in the list of columns, and there is no way to // distinguish the indexes from proper columns Set tableNames = null; if (tableName == null || "%".equals(tableName)) { Table[] tables = _dict.getTables(meta, conn.getCatalog(), schemaName, tableName, conn); tableNames = new HashSet(); for (int i = 0; tables != null && i < tables.length; i++) { if (cols == null) tableNames.add(tables[i].getName()); else tableNames.add(tables[i].getName().toUpperCase()); } } // if database can't handle null table name, recurse on each known name if (cols == null && tableName == null) { for (Iterator itr = tableNames.iterator(); itr.hasNext();) generateTables(schemaName, (String) itr.next(), conn, meta); return; } SchemaGroup group = getSchemaGroup(); Schema schema; Table table; String tableSchema; for (int i = 0; cols != null && i < cols.length; i++) { // TODO: Is this where we should handle this? if (tableName == null || tableName.equals("%")) { tableName = cols[i].getTableName(); } if (schemaName == null) { tableSchema = StringUtils.trimToNull(cols[i].getSchemaName()); } else { tableSchema = schemaName; } // ignore special tables if (!_openjpaTables && (tableName.toUpperCase().startsWith("OPENJPA_") || tableName.toUpperCase().startsWith("JDO_"))) // legacy continue; if (_dict.isSystemTable(tableName, tableSchema, schemaName != null)) continue; // ignore tables not in list, or not allowed by schemas property if (tableNames != null && !tableNames.contains(tableName.toUpperCase())) continue; if (!isAllowedTable(tableSchema, tableName)) continue; schema = group.getSchema(tableSchema); if (schema == null) schema = group.addSchema(tableSchema); table = schema.getTable(tableName); if (table == null) { table = schema.addTable(tableName); if (_log.isTraceEnabled()) _log.trace(_loc.get("col-table", table)); } if (_log.isTraceEnabled()) _log.trace(_loc.get("gen-column", cols[i].getName(), table)); if (table.getColumn(cols[i].getName()) == null) table.importColumn(cols[i]); } } public void generateTables(String schemaName, String tableName, Connection conn, DatabaseMetaData meta) throws SQLException { fireGenerationEvent(_loc.get("generating-columns", schemaName, tableName)); if (_log.isTraceEnabled()) _log.trace(_loc.get("gen-tables", schemaName, tableName)); Column[] cols = _dict.getColumns(meta, conn.getCatalog(), schemaName, tableName, null, conn); // when we want to get all the columns for all tables, we need to build // a list of tables to verify because some databases (e.g., Postgres) // will include indexes in the list of columns, and there is no way to // distinguish the indexes from proper columns Set tableNames = null; if (tableName == null || "%".equals(tableName)) { Table[] tables = _dict.getTables(meta, conn.getCatalog(), schemaName, tableName, conn); tableNames = new HashSet(); for (int i = 0; tables != null && i < tables.length; i++) { if (cols == null) tableNames.add(tables[i].getName()); else tableNames.add(tables[i].getName().toUpperCase()); } } // if database can't handle null table name, recurse on each known name if (cols == null && tableName == null) { for (Iterator itr = tableNames.iterator(); itr.hasNext();) generateTables(schemaName, (String) itr.next(), conn, meta); return; } SchemaGroup group = getSchemaGroup(); Schema schema; Table table; String tableSchema; for (int i = 0; cols != null && i < cols.length; i++) { if (tableName == null || tableName.equals("%")) { tableName = cols[i].getTableName(); } if (schemaName == null) { tableSchema = StringUtils.trimToNull(cols[i].getSchemaName()); } else { tableSchema = schemaName; } // ignore special tables if (!_openjpaTables && (tableName.toUpperCase().startsWith("OPENJPA_") || tableName.toUpperCase().startsWith("JDO_"))) // legacy continue; if (_dict.isSystemTable(tableName, tableSchema, schemaName != null)) continue; // ignore tables not in list, or not allowed by schemas property if (tableNames != null && !tableNames.contains(tableName.toUpperCase())) continue; if (!isAllowedTable(tableSchema, tableName)) continue; schema = group.getSchema(tableSchema); if (schema == null) schema = group.addSchema(tableSchema); table = schema.getTable(tableName); if (table == null) { table = schema.addTable(tableName); if (_log.isTraceEnabled()) _log.trace(_loc.get("col-table", table)); } if (_log.isTraceEnabled()) _log.trace(_loc.get("gen-column", cols[i].getName(), table)); if (table.getColumn(cols[i].getName()) == null) { // It's possible that the original column name was delimited, // so delimit it and try again String delimCol = _dict.addDelimiters(cols[i].getName()); if (table.getColumn(delimCol) == null) { table.importColumn(cols[i]); } } } }
openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/schema/SchemaGenerator.java
satd-removal_data_12
TODO it might be nice to move these calculations somewhere else since they will need to be reused @Override public void handle(Session session, GlowPlayer player, BlockPlacementMessage message) { if (player == null) return; GlowWorld world = player.getWorld(); int x = message.getX(); int z = message.getZ(); int y = message.getY(); switch (message.getDirection()) { case 0: --y; break; case 1: ++y; break; case 2: --z; break; case 3: ++z; break; case 4: --x; break; case 5: ++x; break; } // TODO it might be nice to move these calculations somewhere else since they will need to be reused int chunkX = x / GlowChunk.WIDTH + ((x < 0 && x % GlowChunk.WIDTH != 0) ? -1 : 0); int chunkZ = z / GlowChunk.HEIGHT + ((z < 0 && z % GlowChunk.HEIGHT != 0) ? -1 : 0); int localX = (x - chunkX * GlowChunk.WIDTH) % GlowChunk.WIDTH; int localZ = (z - chunkZ * GlowChunk.HEIGHT) % GlowChunk.HEIGHT; GlowChunk chunk = world.getChunkManager().getChunk(chunkX, chunkZ); chunk.setType(localX, localZ, y, Material.WOOD.getId()); // TODO this should also be somewhere else as well... perhaps in the chunk.setType() method itself? BlockChangeMessage bcmsg = new BlockChangeMessage(x, y, z, Material.WOOD.getId(), 0); for (GlowPlayer p: world.getRawPlayers()) { p.getSession().send(bcmsg); } } @Override public void handle(Session session, GlowPlayer player, BlockPlacementMessage message) { if (player == null) return; GlowWorld world = player.getWorld(); int x = message.getX(); int z = message.getZ(); int y = message.getY(); switch (message.getDirection()) { case 0: --y; break; case 1: ++y; break; case 2: --z; break; case 3: ++z; break; case 4: --x; break; case 5: ++x; break; } world.getBlockAt(x, y, z).setType(Material.WOOD); }
src/main/java/net/glowstone/msg/handler/BlockPlacementMessageHandler.java
satd-removal_data_13
TODO set the owner property @Override public void add(IdentityContext context, AttributedType value) { if (IdentityType.class.isInstance(value)) { EntityGraph graph = EntityGraph.create(value, config.getIdentityModel()); graph.setProperty(config.getIdentityModel().getIdentityClassProperty(), value.getClass().getName()); graph.persist(getEntityManager(context)); } else if (Relationship.class.isInstance(value)) { Relationship relationship = (Relationship) value; EntityGraph graph = EntityGraph.create(relationship, config.getRelationshipModel()); graph.setProperty(config.getRelationshipModel().getRelationshipClassProperty(), relationship.getClass().getName()); // For each of the identities participating in the relationship, create a new node in the graph Class<?> relationshipIdentityClass = config.getRelationshipModel().getRelationshipMember().getDeclaringClass(); Set<Property<? extends IdentityType>> identityProperties = relationshipMetadata.getRelationshipIdentityProperties( relationship.getClass()); for (Property<? extends IdentityType> property : identityProperties) { Object entity = graph.createEntity(relationshipIdentityClass); graph.createNode(entity, false); // If the relationship member property is a String, set the identifier as the value if (String.class.equals(config.getRelationshipModel().getRelationshipMember().getJavaClass())) { IdentityType relationshipIdentity = property.getValue(relationship); // We use the convention "Identity ID:Partition ID" to store identity references // TODO maybe replace this with an IdentityReference instead? graph.setProperty(config.getRelationshipModel().getRelationshipMember(), String.format("%s:%s", relationshipIdentity.getId(), relationshipIdentity.getPartition().getId())); } else { // Otherwise we set the value to the entity with the specified identifier AttributedType member = (AttributedType) config.getRelationshipModel().getRelationshipMember().getValue(relationship); String identifier = member.getId(); Object identityEntity = lookupEntityByParameter(context, config.getIdentityModel(), IdentityType.class, "id", identifier); graph.setProperty(config.getRelationshipModel().getRelationshipMember(), identityEntity); } graph.setProperty(config.getRelationshipModel().getRelationshipDescriptor(), property.getName()); // TODO set the owner property } graph.persist(getEntityManager(context)); } } @Override public void add(IdentityContext context, AttributedType attributedType) { attributedType.setId(context.getIdGenerator().generate()); if (IdentityType.class.isInstance(attributedType)) { IdentityType identityType = (IdentityType) attributedType; identityType.setPartition(context.getPartition()); } EntityManager entityManager = getEntityManager(context); for (EntityMapper entityMapper : getMapperFor(attributedType.getClass())) { Object entity = entityMapper.createEntity(attributedType, entityManager); if (entity != null) { entityManager.persist(entity); } if (Relationship.class.isInstance(attributedType)) { addRelationshipIdentity(attributedType, entityManager); } } entityManager.flush(); }
modules/idm/impl/src/main/java/org/picketlink/idm/jpa/internal/JPAIdentityStore.java
satd-removal_data_14
TODO: fix this (BATCH-1030) @Test public void testFailedStepRestarted() throws Exception { SimpleFlow flow = new SimpleFlow("job"); List<StateTransition> transitions = new ArrayList<StateTransition>(); transitions.add(StateTransition.createStateTransition(new StepState(new StepSupport("step1") { @Override public void execute(StepExecution stepExecution) throws JobInterruptedException, UnexpectedJobExecutionException { stepExecution.setStatus(BatchStatus.FAILED); stepExecution.setExitStatus(ExitStatus.FAILED); jobRepository.update(stepExecution); } }), "step2")); transitions.add(StateTransition.createEndStateTransition(new StepState(new StubStep("step2") { @Override public void execute(StepExecution stepExecution) throws JobInterruptedException, UnexpectedJobExecutionException { if (fail) { stepExecution.setStatus(BatchStatus.FAILED); stepExecution.setExitStatus(ExitStatus.FAILED); jobRepository.update(stepExecution); } else { super.execute(stepExecution); } } }))); flow.setStateTransitions(transitions); job.setFlow(flow); job.afterPropertiesSet(); fail = true; job.execute(jobExecution); assertEquals(ExitStatus.FAILED, jobExecution.getExitStatus()); assertEquals(2, jobExecution.getStepExecutions().size()); jobRepository.update(jobExecution); jobExecution = jobRepository.createJobExecution("job", new JobParameters()); fail = false; job.execute(jobExecution); assertEquals(ExitStatus.COMPLETED, jobExecution.getExitStatus()); // TODO: fix this (BATCH-1030) // assertEquals(1, jobExecution.getStepExecutions().size()); } @Test public void testFailedStepRestarted() throws Exception { SimpleFlow flow = new SimpleFlow("job"); List<StateTransition> transitions = new ArrayList<StateTransition>(); transitions.add(StateTransition.createStateTransition(new StepState(new StepSupport("step1") { @Override public void execute(StepExecution stepExecution) throws JobInterruptedException, UnexpectedJobExecutionException { stepExecution.setStatus(BatchStatus.FAILED); stepExecution.setExitStatus(ExitStatus.FAILED); jobRepository.update(stepExecution); } }), "step2")); transitions.add(StateTransition.createEndStateTransition(new StepState(new StubStep("step2") { @Override public void execute(StepExecution stepExecution) throws JobInterruptedException, UnexpectedJobExecutionException { if (fail) { stepExecution.setStatus(BatchStatus.FAILED); stepExecution.setExitStatus(ExitStatus.FAILED); jobRepository.update(stepExecution); } else { super.execute(stepExecution); } } }))); flow.setStateTransitions(transitions); job.setFlow(flow); job.afterPropertiesSet(); fail = true; job.execute(jobExecution); assertEquals(ExitStatus.FAILED, jobExecution.getExitStatus()); assertEquals(2, jobExecution.getStepExecutions().size()); jobRepository.update(jobExecution); jobExecution = jobRepository.createJobExecution("job", new JobParameters()); fail = false; job.execute(jobExecution); assertEquals(ExitStatus.COMPLETED, jobExecution.getExitStatus()); assertEquals(1, jobExecution.getStepExecutions().size()); }
spring-batch-core/src/test/java/org/springframework/batch/core/job/flow/FlowJobTests.java
satd-removal_data_15
TODO: debug view for candidate strip needed. private void updateSuggestions() { final SuggestedWords suggestions = mSuggestions; final List<SuggestedWordInfo> suggestedWordInfoList = suggestions.mSuggestedWordInfoList; clear(); final int paneWidth = getWidth(); final int dividerWidth = mDividers.get(0).getMeasuredWidth(); int x = 0; int y = 0; int fromIndex = NUM_CANDIDATES_IN_STRIP; final int count = Math.min(mWords.size(), suggestions.size()); closeCandidatesPane(); mExpandCandidatesPane.setEnabled(count >= NUM_CANDIDATES_IN_STRIP); for (int i = 0; i < count; i++) { final CharSequence word = suggestions.getWord(i); if (word == null) continue; final SuggestedWordInfo info = (suggestedWordInfoList != null) ? suggestedWordInfoList.get(i) : null; final boolean isAutoCorrect = suggestions.mHasMinimalSuggestion && ((i == 1 && !suggestions.mTypedWordValid) || (i == 0 && suggestions.mTypedWordValid)); // HACK: even if i == 0, we use mColorOther when this suggestion's length is 1 // and there are multiple suggestions, such as the default punctuation list. // TODO: Need to revisit this logic with bigram suggestions final boolean isSuggestedCandidate = (i != 0); final boolean isPunctuationSuggestions = (word.length() == 1 && count > 1); final TextView tv = mWords.get(i); // TODO: Reorder candidates in strip as appropriate. The center candidate should hold // the word when space is typed (valid typed word or auto corrected word). tv.setTextColor(getCandidateTextColor(isAutoCorrect, isSuggestedCandidate || isPunctuationSuggestions, info)); tv.setText(getStyledCandidateWord(word, isAutoCorrect)); // TODO: call TextView.setTextScaleX() to fit the candidate in single line. if (i >= NUM_CANDIDATES_IN_STRIP) { tv.measure(UNSPECIFIED_MEASURESPEC, UNSPECIFIED_MEASURESPEC); final int width = tv.getMeasuredWidth(); // TODO: Handle overflow case. if (dividerWidth + x + width >= paneWidth) { centeringCandidates(fromIndex, i - 1, x, paneWidth); x = 0; y += mCandidateStripHeight; fromIndex = i; } if (x != 0) { final View divider = mDividers.get(i - NUM_CANDIDATES_IN_STRIP); addCandidateAt(divider, x, y); x += dividerWidth; } addCandidateAt(tv, x, y); x += width; } if (DBG && info != null) { final TextView dv = new TextView(getContext(), null); dv.setTextSize(10.0f); dv.setTextColor(0xff808080); dv.setText(info.getDebugString()); // TODO: debug view for candidate strip needed. // mCandidatesPane.addView(dv); // LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams)dv.getLayoutParams(); // lp.gravity = Gravity.BOTTOM; } } if (x != 0) { // Centering last candidates row. centeringCandidates(fromIndex, count - 1, x, paneWidth); } } private void updateSuggestions() { final SuggestedWords suggestions = mSuggestions; final List<SuggestedWordInfo> suggestedWordInfoList = suggestions.mSuggestedWordInfoList; clear(); final int paneWidth = getWidth(); final int dividerWidth = mDividers.get(0).getMeasuredWidth(); final int dividerHeight = mDividers.get(0).getMeasuredHeight(); int x = 0; int y = 0; int fromIndex = NUM_CANDIDATES_IN_STRIP; final int count = Math.min(mWords.size(), suggestions.size()); closeCandidatesPane(); mExpandCandidatesPane.setEnabled(count >= NUM_CANDIDATES_IN_STRIP); for (int i = 0; i < count; i++) { final CharSequence suggestion = suggestions.getWord(i); if (suggestion == null) continue; final SuggestedWordInfo suggestionInfo = (suggestedWordInfoList != null) ? suggestedWordInfoList.get(i) : null; final boolean isAutoCorrect = suggestions.mHasMinimalSuggestion && ((i == 1 && !suggestions.mTypedWordValid) || (i == 0 && suggestions.mTypedWordValid)); // HACK: even if i == 0, we use mColorOther when this suggestion's length is 1 // and there are multiple suggestions, such as the default punctuation list. // TODO: Need to revisit this logic with bigram suggestions final boolean isSuggestedCandidate = (i != 0); final boolean isPunctuationSuggestions = (suggestion.length() == 1 && count > 1); final TextView word = mWords.get(i); // TODO: Reorder candidates in strip as appropriate. The center candidate should hold // the word when space is typed (valid typed word or auto corrected word). word.setTextColor(getCandidateTextColor(isAutoCorrect, isSuggestedCandidate || isPunctuationSuggestions, suggestionInfo)); word.setText(getStyledCandidateWord(suggestion, isAutoCorrect)); // TODO: call TextView.setTextScaleX() to fit the candidate in single line. word.measure(UNSPECIFIED_MEASURESPEC, UNSPECIFIED_MEASURESPEC); final int width = word.getMeasuredWidth(); final int height = word.getMeasuredHeight(); final TextView info; if (DBG && suggestionInfo != null && !TextUtils.isEmpty(suggestionInfo.getDebugString())) { info = mInfos.get(i); info.setText(suggestionInfo.getDebugString()); info.setVisibility(View.VISIBLE); info.measure(UNSPECIFIED_MEASURESPEC, UNSPECIFIED_MEASURESPEC); } else { info = null; } if (i < NUM_CANDIDATES_IN_STRIP) { if (info != null) { final int infoWidth = info.getMeasuredWidth(); FrameLayoutCompatUtils.placeViewAt( info, x + width - infoWidth, y, infoWidth, info.getMeasuredHeight()); } } else { // TODO: Handle overflow case. if (dividerWidth + x + width >= paneWidth) { centeringCandidates(fromIndex, i - 1, x, paneWidth); x = 0; y += mCandidateStripHeight; fromIndex = i; } if (x != 0) { final View divider = mDividers.get(i - NUM_CANDIDATES_IN_STRIP); mCandidatesPane.addView(divider); FrameLayoutCompatUtils.placeViewAt( divider, x, y + (mCandidateStripHeight - dividerHeight) / 2, dividerWidth, dividerHeight); x += dividerWidth; } mCandidatesPane.addView(word); FrameLayoutCompatUtils.placeViewAt( word, x, y + (mCandidateStripHeight - height) / 2, width, height); if (info != null) { mCandidatesPane.addView(info); final int infoWidth = info.getMeasuredWidth(); FrameLayoutCompatUtils.placeViewAt( info, x + width - infoWidth, y, infoWidth, info.getMeasuredHeight()); } x += width; } } if (x != 0) { // Centering last candidates row. centeringCandidates(fromIndex, count - 1, x, paneWidth); } }
java/src/com/android/inputmethod/latin/CandidateView.java
satd-removal_data_16
todo log & ignore public void run() { final Selector selector = this.selector; for (; ;) { try { keyLoad = selector.keys().size(); selector.select(); synchronized (selectorWorkQueue) { while (! selectorWorkQueue.isEmpty()) { final SelectorTask task = selectorWorkQueue.remove(); try { task.run(selector); } catch (Throwable t) { t.printStackTrace(); // todo log & ignore } } } final Set<SelectionKey> selectedKeys = selector.selectedKeys(); final Iterator<SelectionKey> iterator = selectedKeys.iterator(); while (iterator.hasNext()) { final SelectionKey key = iterator.next(); iterator.remove(); try { key.interestOps(key.interestOps() & (SelectionKey.OP_ACCEPT)); try { final NioHandle handle = (NioHandle) key.attachment(); handle.getHandlerExecutor().execute(handle.getHandler()); } catch (Throwable t) { // tough crap // todo log @ trace t.printStackTrace(); } } catch (CancelledKeyException e) { // todo log @ trace (normal) // e.printStackTrace(); continue; } } } catch (ClosedSelectorException e) { // THIS is the "official" signalling mechanism // todo log @ trace (normal) // e.printStackTrace(); return; } catch (IOException e) { // todo - other I/O errors - should they be fatal? e.printStackTrace(); } } } public void run() { final Selector selector = this.selector; for (; ;) { try { keyLoad = selector.keys().size(); selector.select(); synchronized (selectorWorkQueue) { while (! selectorWorkQueue.isEmpty()) { final SelectorTask task = selectorWorkQueue.remove(); try { task.run(selector); } catch (Throwable t) { log.trace(t, "NIO selector task failed"); } } } final Set<SelectionKey> selectedKeys = selector.selectedKeys(); final Iterator<SelectionKey> iterator = selectedKeys.iterator(); while (iterator.hasNext()) { final SelectionKey key = iterator.next(); iterator.remove(); try { key.interestOps(key.interestOps() & (SelectionKey.OP_ACCEPT)); try { final NioHandle handle = (NioHandle) key.attachment(); handle.getHandlerExecutor().execute(handle.getHandler()); } catch (Throwable t) { log.trace(t, "Failed to execute handler"); } } catch (CancelledKeyException e) { log.trace("Key %s cancelled", key); continue; } } } catch (ClosedSelectorException e) { // THIS is the "official" signalling mechanism log.trace("Selector %s closed", selector); return; } catch (IOException e) { log.trace(e, "I/O error in selector loop"); } } }
nio-impl/src/main/java/org/jboss/xnio/core/nio/NioSelectorRunnable.java
satd-removal_data_17
FIXME Should be refactored when OPENENGSB-1931 is fixed public void init() { new Thread() { @Override public void run() { try { Collection<ConnectorConfiguration> configs; try { Map<String, String> emptyMap = Collections.emptyMap(); configs = configPersistence.load(emptyMap); } catch (InvalidConfigurationException e) { throw new IllegalStateException(e); } catch (PersistenceException e) { throw new IllegalStateException(e); } // FIXME Should be refactored when OPENENGSB-1931 is fixed configs = Collections2.filter(configs, new Predicate<ConfigItem<?>>() { @Override public boolean apply(ConfigItem<?> input) { return input instanceof ConnectorConfiguration; } }); for (ConnectorConfiguration c : configs) { try { registrationManager.updateRegistration(c.getConnectorId(), c.getContent()); } catch (ConnectorValidationFailedException e) { throw new IllegalStateException(e); } } } catch (Exception e) { LOGGER.error("Exception while restoring connectors", e); } } }.start(); } public void init() { new Thread() { @Override public void run() { Collection<ConnectorConfiguration> configs; try { Map<String, String> emptyMap = Collections.emptyMap(); configs = configPersistence.load(emptyMap); } catch (InvalidConfigurationException e) { throw new IllegalStateException(e); } catch (PersistenceException e) { throw new IllegalStateException(e); } for (ConnectorConfiguration c : configs) { try { registrationManager.updateRegistration(c.getConnectorId(), c.getContent()); } catch (ConnectorValidationFailedException e) { throw new IllegalStateException(e); } } } }.start(); }
components/services/src/main/java/org/openengsb/core/services/internal/ConnectorManagerImpl.java
satd-removal_data_18
TODO CHECK BIZARE D'AVOIR KER = ENVELOPE @Override public void propagate(int evtmask) throws ContradictionException { int k = set.getKernelSize(); card.updateLowerBound(k, aCause); int e = set.getEnvelopeSize(); card.updateUpperBound(e, aCause); if (card.instantiated()) { int c = card.getValue(); ISet env = set.getEnvelope(); if (c == k) { // TODO CHECK BIZARE D'AVOIR KER = ENVELOPE ISet ker = set.getEnvelope(); for (int j=set.getEnvelopeFirstElement(); j!=SetVar.END; j=set.getEnvelopeNextElement()) { if (!ker.contain(j)) { set.removeFromEnvelope(j, aCause); } } } else if (c == e) { for (int j=set.getEnvelopeFirstElement(); j!=SetVar.END; j=set.getEnvelopeNextElement()) { set.addToKernel(j, aCause); } } } } @Override public void propagate(int evtmask) throws ContradictionException { int k = set.getKernelSize(); card.updateLowerBound(k, aCause); int e = set.getEnvelopeSize(); card.updateUpperBound(e, aCause); if (card.instantiated()) { int c = card.getValue(); if (c == k) { for (int j=set.getEnvelopeFirstElement(); j!=SetVar.END; j=set.getEnvelopeNextElement()) { if (!set.kernelContains(j)) { set.removeFromEnvelope(j, aCause); } } } else if (c == e) { for (int j=set.getEnvelopeFirstElement(); j!=SetVar.END; j=set.getEnvelopeNextElement()) { set.addToKernel(j, aCause); } } } }
choco-solver/src/main/java/solver/constraints/propagators/set/PropCardinality.java
satd-removal_data_19
TODO: setForeground / startForeground public void register(final Intent intent) { Log.d(TAG, "register(" + intent.getAction() + ")"); // TODO: setForeground / startForeground if (this.helperAPI5s == null) { this.setForeground(true); } else { // TODO: fix me } synchronized (this.pendingIOOps) { Log.d(TAG, "currentIOOps=" + this.pendingIOOps.size()); this.pendingIOOps.add(intent); Log.d(TAG, "currentIOOps=" + this.pendingIOOps.size()); } } public void register(final Intent intent) { Log.d(TAG, "register(" + intent.getAction() + ")"); // setForeground / startForeground Notification notification = null; if (this.helperAPI5s == null) { this.setForeground(true); } else { notification = this.getNotification(); this.helperAPI5s.startForeground(this, NOTIFICATION_PENDING, notification); } if (new ConnectorCommand(intent).getType() == ConnectorCommand.TYPE_SEND) { if (notification == null) { notification = this.getNotification(); } NotificationManager mNotificationMgr = (NotificationManager) this .getSystemService(Context.NOTIFICATION_SERVICE); mNotificationMgr.notify(NOTIFICATION_PENDING, notification); } synchronized (this.pendingIOOps) { Log.d(TAG, "currentIOOps=" + this.pendingIOOps.size()); this.pendingIOOps.add(intent); Log.d(TAG, "currentIOOps=" + this.pendingIOOps.size()); } }
src/de/ub0r/android/websms/connector/common/ConnectorService.java
satd-removal_data_20
Remove those meaningless options for now. TODO: delete them for good @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setInputMethodSettingsCategoryTitle(R.string.language_selection_title); setSubtypeEnablerTitle(R.string.select_language); addPreferencesFromResource(R.xml.prefs); final Resources res = getResources(); final Context context = getActivity(); mVoicePreference = (ListPreference) findPreference(PREF_VOICE_MODE); mShowCorrectionSuggestionsPreference = (ListPreference) findPreference(PREF_SHOW_SUGGESTIONS_SETTING); SharedPreferences prefs = getPreferenceManager().getSharedPreferences(); prefs.registerOnSharedPreferenceChangeListener(this); mAutoCorrectionThresholdPreference = (ListPreference) findPreference(PREF_AUTO_CORRECTION_THRESHOLD); mBigramSuggestion = (CheckBoxPreference) findPreference(PREF_BIGRAM_SUGGESTION); mBigramPrediction = (CheckBoxPreference) findPreference(PREF_BIGRAM_PREDICTIONS); mDebugSettingsPreference = findPreference(PREF_DEBUG_SETTINGS); if (mDebugSettingsPreference != null) { final Intent debugSettingsIntent = new Intent(Intent.ACTION_MAIN); debugSettingsIntent.setClassName( context.getPackageName(), DebugSettings.class.getName()); mDebugSettingsPreference.setIntent(debugSettingsIntent); } ensureConsistencyOfAutoCorrectionSettings(); final PreferenceGroup generalSettings = (PreferenceGroup) findPreference(PREF_GENERAL_SETTINGS); final PreferenceGroup textCorrectionGroup = (PreferenceGroup) findPreference(PREF_CORRECTION_SETTINGS); final PreferenceGroup miscSettings = (PreferenceGroup) findPreference(PREF_MISC_SETTINGS); final boolean showVoiceKeyOption = res.getBoolean( R.bool.config_enable_show_voice_key_option); if (!showVoiceKeyOption) { generalSettings.removePreference(mVoicePreference); } final PreferenceGroup advancedSettings = (PreferenceGroup) findPreference(PREF_ADVANCED_SETTINGS); // Remove those meaningless options for now. TODO: delete them for good advancedSettings.removePreference(findPreference(PREF_BIGRAM_SUGGESTION)); advancedSettings.removePreference(findPreference(PREF_KEY_ENABLE_SPAN_INSERT)); if (!VibratorUtils.getInstance(context).hasVibrator()) { generalSettings.removePreference(findPreference(PREF_VIBRATE_ON)); if (null != advancedSettings) { // Theoretically advancedSettings cannot be null advancedSettings.removePreference(findPreference(PREF_VIBRATION_DURATION_SETTINGS)); } } final boolean showPopupOption = res.getBoolean( R.bool.config_enable_show_popup_on_keypress_option); if (!showPopupOption) { generalSettings.removePreference(findPreference(PREF_POPUP_ON)); } final boolean showBigramSuggestionsOption = res.getBoolean( R.bool.config_enable_next_word_suggestions_option); if (!showBigramSuggestionsOption) { textCorrectionGroup.removePreference(mBigramSuggestion); if (null != mBigramPrediction) { textCorrectionGroup.removePreference(mBigramPrediction); } } final CheckBoxPreference includeOtherImesInLanguageSwitchList = (CheckBoxPreference)findPreference(PREF_INCLUDE_OTHER_IMES_IN_LANGUAGE_SWITCH_LIST); includeOtherImesInLanguageSwitchList.setEnabled( !SettingsValues.isLanguageSwitchKeySupressed(prefs)); mKeyPreviewPopupDismissDelay = (ListPreference)findPreference(PREF_KEY_PREVIEW_POPUP_DISMISS_DELAY); final String[] entries = new String[] { res.getString(R.string.key_preview_popup_dismiss_no_delay), res.getString(R.string.key_preview_popup_dismiss_default_delay), }; final String popupDismissDelayDefaultValue = Integer.toString(res.getInteger( R.integer.config_key_preview_linger_timeout)); mKeyPreviewPopupDismissDelay.setEntries(entries); mKeyPreviewPopupDismissDelay.setEntryValues( new String[] { "0", popupDismissDelayDefaultValue }); if (null == mKeyPreviewPopupDismissDelay.getValue()) { mKeyPreviewPopupDismissDelay.setValue(popupDismissDelayDefaultValue); } mKeyPreviewPopupDismissDelay.setEnabled( SettingsValues.isKeyPreviewPopupEnabled(prefs, res)); final PreferenceScreen dictionaryLink = (PreferenceScreen) findPreference(PREF_CONFIGURE_DICTIONARIES_KEY); final Intent intent = dictionaryLink.getIntent(); final int number = context.getPackageManager().queryIntentActivities(intent, 0).size(); if (0 >= number) { textCorrectionGroup.removePreference(dictionaryLink); } final boolean showUsabilityStudyModeOption = res.getBoolean(R.bool.config_enable_usability_study_mode_option) || ProductionFlag.IS_EXPERIMENTAL || ENABLE_EXPERIMENTAL_SETTINGS; final Preference usabilityStudyPref = findPreference(PREF_USABILITY_STUDY_MODE); if (!showUsabilityStudyModeOption) { if (usabilityStudyPref != null) { miscSettings.removePreference(usabilityStudyPref); } } if (ProductionFlag.IS_EXPERIMENTAL) { if (usabilityStudyPref instanceof CheckBoxPreference) { CheckBoxPreference checkbox = (CheckBoxPreference)usabilityStudyPref; checkbox.setChecked(prefs.getBoolean(PREF_USABILITY_STUDY_MODE, true)); checkbox.setSummary(R.string.settings_warning_researcher_mode); } } mKeypressVibrationDurationSettingsPref = (PreferenceScreen) findPreference(PREF_VIBRATION_DURATION_SETTINGS); if (mKeypressVibrationDurationSettingsPref != null) { mKeypressVibrationDurationSettingsPref.setOnPreferenceClickListener( new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference arg0) { showKeypressVibrationDurationSettingsDialog(); return true; } }); updateKeypressVibrationDurationSettingsSummary(prefs, res); } mKeypressSoundVolumeSettingsPref = (PreferenceScreen) findPreference(PREF_KEYPRESS_SOUND_VOLUME); if (mKeypressSoundVolumeSettingsPref != null) { mKeypressSoundVolumeSettingsPref.setOnPreferenceClickListener( new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference arg0) { showKeypressSoundVolumeSettingDialog(); return true; } }); updateKeypressSoundVolumeSummary(prefs, res); } refreshEnablingsOfKeypressSoundAndVibrationSettings(prefs, res); } @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setInputMethodSettingsCategoryTitle(R.string.language_selection_title); setSubtypeEnablerTitle(R.string.select_language); addPreferencesFromResource(R.xml.prefs); final Resources res = getResources(); final Context context = getActivity(); mVoicePreference = (ListPreference) findPreference(PREF_VOICE_MODE); mShowCorrectionSuggestionsPreference = (ListPreference) findPreference(PREF_SHOW_SUGGESTIONS_SETTING); SharedPreferences prefs = getPreferenceManager().getSharedPreferences(); prefs.registerOnSharedPreferenceChangeListener(this); mAutoCorrectionThresholdPreference = (ListPreference) findPreference(PREF_AUTO_CORRECTION_THRESHOLD); mBigramPrediction = (CheckBoxPreference) findPreference(PREF_BIGRAM_PREDICTIONS); mDebugSettingsPreference = findPreference(PREF_DEBUG_SETTINGS); if (mDebugSettingsPreference != null) { final Intent debugSettingsIntent = new Intent(Intent.ACTION_MAIN); debugSettingsIntent.setClassName( context.getPackageName(), DebugSettings.class.getName()); mDebugSettingsPreference.setIntent(debugSettingsIntent); } ensureConsistencyOfAutoCorrectionSettings(); final PreferenceGroup generalSettings = (PreferenceGroup) findPreference(PREF_GENERAL_SETTINGS); final PreferenceGroup textCorrectionGroup = (PreferenceGroup) findPreference(PREF_CORRECTION_SETTINGS); final PreferenceGroup miscSettings = (PreferenceGroup) findPreference(PREF_MISC_SETTINGS); final boolean showVoiceKeyOption = res.getBoolean( R.bool.config_enable_show_voice_key_option); if (!showVoiceKeyOption) { generalSettings.removePreference(mVoicePreference); } if (!VibratorUtils.getInstance(context).hasVibrator()) { final PreferenceGroup advancedSettings = (PreferenceGroup) findPreference(PREF_ADVANCED_SETTINGS); generalSettings.removePreference(findPreference(PREF_VIBRATE_ON)); if (null != advancedSettings) { // Theoretically advancedSettings cannot be null advancedSettings.removePreference(findPreference(PREF_VIBRATION_DURATION_SETTINGS)); } } final boolean showPopupOption = res.getBoolean( R.bool.config_enable_show_popup_on_keypress_option); if (!showPopupOption) { generalSettings.removePreference(findPreference(PREF_POPUP_ON)); } final CheckBoxPreference includeOtherImesInLanguageSwitchList = (CheckBoxPreference)findPreference(PREF_INCLUDE_OTHER_IMES_IN_LANGUAGE_SWITCH_LIST); includeOtherImesInLanguageSwitchList.setEnabled( !SettingsValues.isLanguageSwitchKeySupressed(prefs)); mKeyPreviewPopupDismissDelay = (ListPreference)findPreference(PREF_KEY_PREVIEW_POPUP_DISMISS_DELAY); final String[] entries = new String[] { res.getString(R.string.key_preview_popup_dismiss_no_delay), res.getString(R.string.key_preview_popup_dismiss_default_delay), }; final String popupDismissDelayDefaultValue = Integer.toString(res.getInteger( R.integer.config_key_preview_linger_timeout)); mKeyPreviewPopupDismissDelay.setEntries(entries); mKeyPreviewPopupDismissDelay.setEntryValues( new String[] { "0", popupDismissDelayDefaultValue }); if (null == mKeyPreviewPopupDismissDelay.getValue()) { mKeyPreviewPopupDismissDelay.setValue(popupDismissDelayDefaultValue); } mKeyPreviewPopupDismissDelay.setEnabled( SettingsValues.isKeyPreviewPopupEnabled(prefs, res)); final PreferenceScreen dictionaryLink = (PreferenceScreen) findPreference(PREF_CONFIGURE_DICTIONARIES_KEY); final Intent intent = dictionaryLink.getIntent(); final int number = context.getPackageManager().queryIntentActivities(intent, 0).size(); if (0 >= number) { textCorrectionGroup.removePreference(dictionaryLink); } final boolean showUsabilityStudyModeOption = res.getBoolean(R.bool.config_enable_usability_study_mode_option) || ProductionFlag.IS_EXPERIMENTAL || ENABLE_EXPERIMENTAL_SETTINGS; final Preference usabilityStudyPref = findPreference(PREF_USABILITY_STUDY_MODE); if (!showUsabilityStudyModeOption) { if (usabilityStudyPref != null) { miscSettings.removePreference(usabilityStudyPref); } } if (ProductionFlag.IS_EXPERIMENTAL) { if (usabilityStudyPref instanceof CheckBoxPreference) { CheckBoxPreference checkbox = (CheckBoxPreference)usabilityStudyPref; checkbox.setChecked(prefs.getBoolean(PREF_USABILITY_STUDY_MODE, true)); checkbox.setSummary(R.string.settings_warning_researcher_mode); } } mKeypressVibrationDurationSettingsPref = (PreferenceScreen) findPreference(PREF_VIBRATION_DURATION_SETTINGS); if (mKeypressVibrationDurationSettingsPref != null) { mKeypressVibrationDurationSettingsPref.setOnPreferenceClickListener( new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference arg0) { showKeypressVibrationDurationSettingsDialog(); return true; } }); updateKeypressVibrationDurationSettingsSummary(prefs, res); } mKeypressSoundVolumeSettingsPref = (PreferenceScreen) findPreference(PREF_KEYPRESS_SOUND_VOLUME); if (mKeypressSoundVolumeSettingsPref != null) { mKeypressSoundVolumeSettingsPref.setOnPreferenceClickListener( new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference arg0) { showKeypressSoundVolumeSettingDialog(); return true; } }); updateKeypressSoundVolumeSummary(prefs, res); } refreshEnablingsOfKeypressSoundAndVibrationSettings(prefs, res); }
java/src/com/android/inputmethod/latin/Settings.java
satd-removal_data_21
TODO: include last social snippet after update private Dialog createNameDialog() { // Build set of all available display names final ArrayList<ValuesDelta> allNames = new ArrayList<ValuesDelta>(); for (EntityDelta entity : this.mEntities) { final ArrayList<ValuesDelta> displayNames = entity .getMimeEntries(StructuredName.CONTENT_ITEM_TYPE); allNames.addAll(displayNames); } // Wrap our context to inflate list items using correct theme final Context dialogContext = new ContextThemeWrapper(this, android.R.style.Theme_Light); final LayoutInflater dialogInflater = this.getLayoutInflater().cloneInContext(dialogContext); final ListAdapter nameAdapter = new ArrayAdapter<ValuesDelta>(this, android.R.layout.simple_list_item_1, allNames) { @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = dialogInflater.inflate( android.R.layout.simple_expandable_list_item_1, parent, false); } final ValuesDelta structuredName = this.getItem(position); final String displayName = structuredName.getAsString(StructuredName.DISPLAY_NAME); ((TextView)convertView).setText(displayName); return convertView; } }; final DialogInterface.OnClickListener clickListener = new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); // User picked display name, so make super-primary final ValuesDelta structuredName = allNames.get(which); structuredName.put(Data.IS_PRIMARY, 1); structuredName.put(Data.IS_SUPER_PRIMARY, 1); // TODO: include last social snippet after update final String displayName = structuredName.getAsString(StructuredName.DISPLAY_NAME); } }; final AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(R.string.dialog_primary_name); builder.setSingleChoiceItems(nameAdapter, 0, clickListener); return builder.create(); } private Dialog createNameDialog() { // Build set of all available display names final ArrayList<ValuesDelta> allNames = new ArrayList<ValuesDelta>(); for (EntityDelta entity : mState) { final ArrayList<ValuesDelta> displayNames = entity .getMimeEntries(StructuredName.CONTENT_ITEM_TYPE); allNames.addAll(displayNames); } // Wrap our context to inflate list items using correct theme final Context dialogContext = new ContextThemeWrapper(this, android.R.style.Theme_Light); final LayoutInflater dialogInflater = this.getLayoutInflater() .cloneInContext(dialogContext); final ListAdapter nameAdapter = new ArrayAdapter<ValuesDelta>(this, android.R.layout.simple_list_item_1, allNames) { @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = dialogInflater.inflate(android.R.layout.simple_list_item_1, parent, false); } final ValuesDelta structuredName = this.getItem(position); final String displayName = structuredName.getAsString(StructuredName.DISPLAY_NAME); ((TextView)convertView).setText(displayName); return convertView; } }; final DialogInterface.OnClickListener clickListener = new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); // User picked display name, so make super-primary final ValuesDelta structuredName = allNames.get(which); structuredName.put(Data.IS_PRIMARY, 1); structuredName.put(Data.IS_SUPER_PRIMARY, 1); // Update header based on edited values bindHeader(); } }; final AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(R.string.dialog_primary_name); builder.setSingleChoiceItems(nameAdapter, 0, clickListener); return builder.create(); }
src/com/android/contacts/ui/EditContactActivity.java
satd-removal_data_22
todo: should support more that List/Set @SuppressWarnings("unchecked") public void injectValueIntoField(Object instance, InvocationProviders invocationProviders, AeshContext aeshContext, boolean doValidation) throws OptionValidatorException { if(converter == null || instance == null) return; try { Field field = getField(instance.getClass(), fieldName); if(!Modifier.isPublic(field.getModifiers())) field.setAccessible(true); if(!Modifier.isPublic(instance.getClass().getModifiers())) { Constructor constructor = instance.getClass().getDeclaredConstructor(); if(constructor != null) constructor.setAccessible(true); } if(optionType == OptionType.NORMAL || optionType == OptionType.BOOLEAN || optionType == OptionType.ARGUMENT) { if(getValue() != null) field.set(instance, doConvert(getValue(), invocationProviders, instance, aeshContext, doValidation)); else if(defaultValues.size() > 0) { field.set(instance, doConvert(defaultValues.get(0), invocationProviders, instance, aeshContext, doValidation)); } } else if(optionType == OptionType.LIST || optionType == OptionType.ARGUMENTS) { if(field.getType().isInterface() || Modifier.isAbstract(field.getType().getModifiers())) { if(Set.class.isAssignableFrom(field.getType())) { Set tmpSet = new HashSet<>(); if(values.size() > 0) { for(String in : values) tmpSet.add(doConvert(in, invocationProviders, instance, aeshContext, doValidation)); } else if(defaultValues.size() > 0) { for(String in : defaultValues) tmpSet.add(doConvert(in, invocationProviders, instance, aeshContext, doValidation)); } field.set(instance, tmpSet); } else if(List.class.isAssignableFrom(field.getType())) { List tmpList = new ArrayList(); if(values.size() > 0) { for(String in : values) tmpList.add(doConvert(in, invocationProviders, instance, aeshContext, doValidation)); } else if(defaultValues.size() > 0) { for(String in : defaultValues) tmpList.add(doConvert(in, invocationProviders, instance, aeshContext, doValidation)); } field.set(instance, tmpList); } //todo: should support more that List/Set } else { Collection tmpInstance = (Collection) field.getType().newInstance(); if(values.size() > 0) { for(String in : values) tmpInstance.add(doConvert(in, invocationProviders, instance, aeshContext, doValidation)); } else if(defaultValues.size() > 0) { for(String in : defaultValues) tmpInstance.add(doConvert(in, invocationProviders, instance, aeshContext, doValidation)); } field.set(instance, tmpInstance); } } else if(optionType == OptionType.GROUP) { if(field.getType().isInterface() || Modifier.isAbstract(field.getType().getModifiers())) { Map<String, Object> tmpMap = newHashMap(); for(String propertyKey : properties.keySet()) tmpMap.put(propertyKey,doConvert(properties.get(propertyKey), invocationProviders, instance, aeshContext, doValidation)); field.set(instance, tmpMap); } else { Map<String,Object> tmpMap = (Map<String,Object>) field.getType().newInstance(); for(String propertyKey : properties.keySet()) tmpMap.put(propertyKey,doConvert(properties.get(propertyKey), invocationProviders, instance, aeshContext, doValidation)); field.set(instance, tmpMap); } } } catch (NoSuchFieldException | IllegalAccessException | NoSuchMethodException | InstantiationException e) { e.printStackTrace(); } } @SuppressWarnings("unchecked") public void injectValueIntoField(Object instance, InvocationProviders invocationProviders, AeshContext aeshContext, boolean doValidation) throws OptionValidatorException { if(converter == null || instance == null) return; try { Field field = getField(instance.getClass(), fieldName); if(!Modifier.isPublic(field.getModifiers())) field.setAccessible(true); if(!Modifier.isPublic(instance.getClass().getModifiers())) { Constructor constructor = instance.getClass().getDeclaredConstructor(); if(constructor != null) constructor.setAccessible(true); } if(optionType == OptionType.NORMAL || optionType == OptionType.BOOLEAN || optionType == OptionType.ARGUMENT) { if(getValue() != null) field.set(instance, doConvert(getValue(), invocationProviders, instance, aeshContext, doValidation)); else if(defaultValues.size() > 0) { field.set(instance, doConvert(defaultValues.get(0), invocationProviders, instance, aeshContext, doValidation)); } } else if(optionType == OptionType.LIST || optionType == OptionType.ARGUMENTS) { Collection tmpSet = initializeCollection(field); if(values.size() > 0) { for(String in : values) tmpSet.add(doConvert(in, invocationProviders, instance, aeshContext, doValidation)); } else if(defaultValues.size() > 0) { for(String in : defaultValues) tmpSet.add(doConvert(in, invocationProviders, instance, aeshContext, doValidation)); } field.set(instance, tmpSet); } else if(optionType == OptionType.GROUP) { if(field.getType().isInterface() || Modifier.isAbstract(field.getType().getModifiers())) { Map<String, Object> tmpMap = newHashMap(); for(String propertyKey : properties.keySet()) tmpMap.put(propertyKey,doConvert(properties.get(propertyKey), invocationProviders, instance, aeshContext, doValidation)); field.set(instance, tmpMap); } else { Map<String,Object> tmpMap = (Map<String,Object>) field.getType().newInstance(); for(String propertyKey : properties.keySet()) tmpMap.put(propertyKey,doConvert(properties.get(propertyKey), invocationProviders, instance, aeshContext, doValidation)); field.set(instance, tmpMap); } } } catch (NoSuchFieldException | IllegalAccessException | NoSuchMethodException | InstantiationException e) { e.printStackTrace(); } }
src/main/java/org/aesh/command/impl/internal/ProcessedOption.java
satd-removal_data_23
TODO: Confirm correct delete policy for exchange private void onExchange() { Account account = SetupData.getAccount(); HostAuth recvAuth = account.getOrCreateHostAuthRecv(this); recvAuth.setConnection(HostAuth.SCHEME_EAS, recvAuth.mAddress, recvAuth.mPort, recvAuth.mFlags | HostAuth.FLAG_SSL); HostAuth sendAuth = account.getOrCreateHostAuthSend(this); sendAuth.setConnection(HostAuth.SCHEME_EAS, sendAuth.mAddress, sendAuth.mPort, sendAuth.mFlags | HostAuth.FLAG_SSL); // TODO: Confirm correct delete policy for exchange account.setDeletePolicy(Account.DELETE_POLICY_ON_DELETE); account.setSyncInterval(Account.CHECK_INTERVAL_PUSH); account.setSyncLookback(1); SetupData.setCheckSettingsMode(SetupData.CHECK_AUTODISCOVER); AccountSetupExchange.actionIncomingSettings(this, SetupData.getFlowMode(), account); finish(); } private void onExchange() { Account account = SetupData.getAccount(); HostAuth recvAuth = account.getOrCreateHostAuthRecv(this); recvAuth.setConnection(HostAuth.SCHEME_EAS, recvAuth.mAddress, recvAuth.mPort, recvAuth.mFlags | HostAuth.FLAG_SSL); HostAuth sendAuth = account.getOrCreateHostAuthSend(this); sendAuth.setConnection(HostAuth.SCHEME_EAS, sendAuth.mAddress, sendAuth.mPort, sendAuth.mFlags | HostAuth.FLAG_SSL); AccountSetupBasics.setFlagsForProtocol(account, HostAuth.SCHEME_EAS); SetupData.setCheckSettingsMode(SetupData.CHECK_AUTODISCOVER); AccountSetupExchange.actionIncomingSettings(this, SetupData.getFlowMode(), account); finish(); }
src/com/android/email/activity/setup/AccountSetupAccountType.java
satd-removal_data_24
TODO: Log exception public void performSimpleAction(SimpleSessionAction action) { final Session session = sessionManager.getSession(); Transaction tx = null; try { tx = session.beginTransaction(); action.perform(session); tx.commit(); } catch (Exception ex) { //TODO: Log exception if (tx != null) { tx.rollback(); } } finally { session.close(); } } public void performSimpleAction(SimpleSessionAction action) { final Session session = sessionManager.getSession(); Transaction tx = null; try { tx = session.beginTransaction(); action.perform(session); tx.commit(); } catch (Exception ex) { if (tx != null) { tx.rollback(); } throw new AtomDatabaseException("Failure performing hibernate action: " + action.toString(), ex); } finally { session.close(); } }
adapters/hibernate/src/main/java/org/atomhopper/hibernate/HibernateFeedRepository.java
satd-removal_data_25
TODO: THIS IS INEFFICIENT BECAUSE FOR EACH PROPERTY WE DITHER AGAIN @Override public void addToLaserJob(LaserJob job, GraphicSet objects) { //TODO for (LaserProperty prop : this.getLaserProperties()) { Rectangle2D bb = objects.getBoundingBox(); if (bb != null && bb.getWidth() > 0 && bb.getHeight() > 0) { BufferedImage scaledImg = new BufferedImage((int) bb.getWidth(), (int) bb.getHeight(), BufferedImage.TYPE_INT_RGB); Graphics2D g = scaledImg.createGraphics(); g.setColor(Color.white); g.fillRect(0, 0, scaledImg.getWidth(), scaledImg.getHeight()); g.setClip(0, 0, scaledImg.getWidth(), scaledImg.getHeight()); if (objects.getTransform() != null) { Rectangle2D origBB = objects.getOriginalBoundingBox(); Rectangle2D targetBB = new Rectangle(0, 0, scaledImg.getWidth(), scaledImg.getHeight()); g.setTransform(Helper.getTransform(origBB, targetBB)); } g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); for (GraphicObject o : objects) { o.render(g); } BufferedImageAdapter ad = new BufferedImageAdapter(scaledImg, invertColors); ad.setColorShift(this.getColorShift()); BlackWhiteRaster bw = new BlackWhiteRaster(ad, this.getDitherAlgorithm()); //TODO: THIS IS INEFFICIENT BECAUSE FOR EACH PROPERTY WE DITHER AGAIN job.getRasterPart().addImage(bw, prop, new Point((int) bb.getX(), (int) bb.getY())); } } } @Override public void addToLaserJob(LaserJob job, GraphicSet set) { //Decompose Objects if their distance is big enough for (GraphicSet objects : this.decompose(set)) { Rectangle2D bb = objects.getBoundingBox(); if (bb != null && bb.getWidth() > 0 && bb.getHeight() > 0) { //First render them on an empty image BufferedImage scaledImg = new BufferedImage((int) bb.getWidth(), (int) bb.getHeight(), BufferedImage.TYPE_INT_RGB); Graphics2D g = scaledImg.createGraphics(); g.setColor(Color.white); g.fillRect(0, 0, scaledImg.getWidth(), scaledImg.getHeight()); g.setClip(0, 0, scaledImg.getWidth(), scaledImg.getHeight()); if (objects.getTransform() != null) { Rectangle2D origBB = objects.getOriginalBoundingBox(); Rectangle2D targetBB = new Rectangle(0, 0, scaledImg.getWidth(), scaledImg.getHeight()); g.setTransform(Helper.getTransform(origBB, targetBB)); } g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); for (GraphicObject o : objects) { o.render(g); } //Then dither this image BufferedImageAdapter ad = new BufferedImageAdapter(scaledImg, invertColors); ad.setColorShift(this.getColorShift()); BlackWhiteRaster bw = new BlackWhiteRaster(ad, this.getDitherAlgorithm()); for (LaserProperty prop : this.getLaserProperties()) {//and add it to the raster part as often as defined in the profile job.getRasterPart().addImage(bw, prop, new Point((int) bb.getX(), (int) bb.getY())); } } } }
src/com/t_oster/visicut/model/RasterProfile.java
satd-removal_data_26
todo - also allow src from files here public void execute() throws BuildException { log("execute()", Project.MSG_VERBOSE); command = command.trim(); try { if (srcFile == null && command.length() == 0 && filesets.isEmpty()) { throw new BuildException("Source file does not exist!", getLocation()); } if (srcFile != null && !srcFile.exists()) { throw new BuildException("Source file does not exist!", getLocation()); } // deal with the filesets for (int i = 0; i < filesets.size(); i++) { FileSet fs = (FileSet) filesets.elementAt(i); DirectoryScanner ds = fs.getDirectoryScanner(getProject()); File srcDir = fs.getDir(getProject()); String[] srcFiles = ds.getIncludedFiles(); } try { PrintStream out = System.out; try { if (output != null) { log("Opening PrintStream to output file " + output, Project.MSG_VERBOSE); out = new PrintStream( new BufferedOutputStream( new FileOutputStream(output .getAbsolutePath(), append))); } //todo - also allow src from files here if (command == null) { command = getText(new BufferedReader(new FileReader(srcFile))); } if (command != null) { execGroovy(command,out); } else { throw new BuildException("Source file does not exist!", getLocation()); } } finally { if (out != null && out != System.out) { out.close(); } } } catch (IOException e) { throw new BuildException(e, getLocation()); } log("statements executed successfully"); } finally{} } public void execute() throws BuildException { log("execute()", Project.MSG_VERBOSE); command = command.trim(); try { if (srcFile == null && command.length() == 0 && filesets.isEmpty()) { throw new BuildException("Source file does not exist!", getLocation()); } if (srcFile != null && !srcFile.exists()) { throw new BuildException("Source file does not exist!", getLocation()); } // deal with the filesets for (int i = 0; i < filesets.size(); i++) { FileSet fs = (FileSet) filesets.elementAt(i); DirectoryScanner ds = fs.getDirectoryScanner(getProject()); File srcDir = fs.getDir(getProject()); String[] srcFiles = ds.getIncludedFiles(); } try { PrintStream out = System.out; try { if (output != null) { log("Opening PrintStream to output file " + output, Project.MSG_VERBOSE); out = new PrintStream( new BufferedOutputStream( new FileOutputStream(output .getAbsolutePath(), append))); } // if there are no groovy statements between the enclosing Groovy tags // then read groovy statements in from a text file using the src attribute if (command == null || command.trim().length() == 0) { command = getText(new BufferedReader(new FileReader(srcFile))); } if (command != null) { execGroovy(command,out); } else { throw new BuildException("Source file does not exist!", getLocation()); } } finally { if (out != null && out != System.out) { out.close(); } } } catch (IOException e) { throw new BuildException(e, getLocation()); } log("statements executed successfully"); } finally{} }
src/main/org/codehaus/groovy/ant/Groovy.java
satd-removal_data_27
TODO add uninitialized entities immediately again public Iterator<Move> moveIterator(final Object planningEntity) { scoreDirector.beforeEntityAdded(planningEntity); // TODO add uninitialized entities immediately again scoreDirector.afterEntityAdded(planningEntity); if (planningValueWalkerList.size() == 1) { PlanningValueWalker planningValueWalker = planningValueWalkerList.iterator().next(); return planningValueWalker.moveIterator(planningEntity); } else { final List<Iterator<Move>> moveIteratorList = new ArrayList<Iterator<Move>>(planningValueWalkerList.size()); final List<Move> composedMoveList = new ArrayList<Move>(planningValueWalkerList.size()); boolean moveIteratorIsFirst = true; for (PlanningValueWalker planningValueWalker : planningValueWalkerList) { Iterator<Move> moveIterator = planningValueWalker.moveIterator(planningEntity); moveIteratorList.add(moveIterator); Move initialMove; if (moveIteratorIsFirst) { // The first moveIterator 's next() call will be done by the new Iterator 's next() call initialMove = null; moveIteratorIsFirst = false; } else { if (!moveIterator.hasNext()) { // TODO the algorithms should be able to cope with that. Mind the use of .walkerList.get(j) throw new IllegalStateException("The planning entity class (" + planningEntityDescriptor.getPlanningEntityClass() + ") for planning variable (" + planningValueWalker.getPlanningVariableDescriptor().getVariableName() + ") has an empty planning value range for planning entity (" + planningEntity + ")."); } initialMove = moveIterator.next(); } composedMoveList.add(initialMove); } return new Iterator<Move>() { public boolean hasNext() { for (Iterator<Move> moveIterator : moveIteratorList) { if (moveIterator.hasNext()) { return true; } } // All levels are maxed out return false; } public Move next() { // Find the level to increment (for example in 115999) for (int i = 0; i < moveIteratorList.size(); i++) { Iterator<Move> moveIterator = moveIteratorList.get(i); if (moveIterator.hasNext()) { // Increment that level (for example 5 in 115999) composedMoveList.set(i, moveIterator.next()); // Do not touch the higher levels (for example each 1 in 115999) break; } else { // Reset a lower level (for example each 9 in 115999) moveIterator = planningValueWalkerList.get(i).moveIterator(planningEntity); moveIteratorList.set(i, moveIterator); composedMoveList.set(i, moveIterator.next()); } } return new CompositeMove(new ArrayList<Move>(composedMoveList)); } public void remove() { throw new UnsupportedOperationException(); } }; } } public Iterator<Move> moveIterator(final Object planningEntity) { if (planningValueWalkerList.size() == 1) { PlanningValueWalker planningValueWalker = planningValueWalkerList.iterator().next(); return planningValueWalker.moveIterator(planningEntity); } else { final List<Iterator<Move>> moveIteratorList = new ArrayList<Iterator<Move>>(planningValueWalkerList.size()); final List<Move> composedMoveList = new ArrayList<Move>(planningValueWalkerList.size()); boolean moveIteratorIsFirst = true; for (PlanningValueWalker planningValueWalker : planningValueWalkerList) { Iterator<Move> moveIterator = planningValueWalker.moveIterator(planningEntity); moveIteratorList.add(moveIterator); Move initialMove; if (moveIteratorIsFirst) { // The first moveIterator 's next() call will be done by the new Iterator 's next() call initialMove = null; moveIteratorIsFirst = false; } else { if (!moveIterator.hasNext()) { // TODO the algorithms should be able to cope with that. Mind the use of .walkerList.get(j) throw new IllegalStateException("The planning entity class (" + planningEntityDescriptor.getPlanningEntityClass() + ") for planning variable (" + planningValueWalker.getPlanningVariableDescriptor().getVariableName() + ") has an empty planning value range for planning entity (" + planningEntity + ")."); } initialMove = moveIterator.next(); } composedMoveList.add(initialMove); } return new Iterator<Move>() { public boolean hasNext() { for (Iterator<Move> moveIterator : moveIteratorList) { if (moveIterator.hasNext()) { return true; } } // All levels are maxed out return false; } public Move next() { // Find the level to increment (for example in 115999) for (int i = 0; i < moveIteratorList.size(); i++) { Iterator<Move> moveIterator = moveIteratorList.get(i); if (moveIterator.hasNext()) { // Increment that level (for example 5 in 115999) composedMoveList.set(i, moveIterator.next()); // Do not touch the higher levels (for example each 1 in 115999) break; } else { // Reset a lower level (for example each 9 in 115999) moveIterator = planningValueWalkerList.get(i).moveIterator(planningEntity); moveIteratorList.set(i, moveIterator); composedMoveList.set(i, moveIterator.next()); } } return new CompositeMove(new ArrayList<Move>(composedMoveList)); } public void remove() { throw new UnsupportedOperationException(); } }; } }
drools-planner-core/src/main/java/org/drools/planner/core/heuristic/selector/variable/PlanningVariableWalker.java
satd-removal_data_28
FIXME throw assertion exception if constraintValidatorType == null private static Class<?> extractType(Class<? extends ConstraintValidator<?, ?>> validator) { Map<Type, Type> resolvedTypes = new HashMap<Type, Type>(); Type constraintValidatorType = resolveTypes( resolvedTypes, validator ); //we now have all bind from a type to its resolution at one level //FIXME throw assertion exception if constraintValidatorType == null Type validatorType = ( ( ParameterizedType ) constraintValidatorType ).getActualTypeArguments()[VALIDATOR_TYPE_INDEX]; while ( resolvedTypes.containsKey( validatorType ) ) { validatorType = resolvedTypes.get( validatorType ); } //FIXME raise an exception if validatorType is not a class return ( Class<?> ) validatorType; } private static Class<?> extractType(Class<? extends ConstraintValidator<?, ?>> validator) { Map<Type, Type> resolvedTypes = new HashMap<Type, Type>(); Type constraintValidatorType = resolveTypes( resolvedTypes, validator ); //we now have all bind from a type to its resolution at one level Type validatorType = ( ( ParameterizedType ) constraintValidatorType ).getActualTypeArguments()[VALIDATOR_TYPE_INDEX]; if ( validatorType == null ) { throw new ValidationException( "Null is an invalid type for a constraint validator." ); } else if ( validatorType instanceof GenericArrayType ) { validatorType = Array.class; } while ( resolvedTypes.containsKey( validatorType ) ) { validatorType = resolvedTypes.get( validatorType ); } //FIXME raise an exception if validatorType is not a class return ( Class<?> ) validatorType; }
hibernate-validator/src/main/java/org/hibernate/validation/util/ValidatorTypeHelper.java
satd-removal_data_29
TODO group by ANKI private void setOutputProductsGridContent(final ViewDefinitionState viewDefinitionState, final Entity order) { GridComponent outputProducts = (GridComponent) viewDefinitionState.getComponentByReference("outputProductsGrid"); List<Entity> outputProductsList = new ArrayList<Entity>(); for (Entity productionRecord : order.getHasManyField("productionRecords")) { outputProductsList.addAll(productionRecord.getHasManyField("recordOperationProductOutComponents")); } Collections.sort(outputProductsList, new EntityProductInOutComparator()); outputProducts.setEntities(outputProductsList); outputProducts.setVisible(true); // TODO group by ANKI } private void setOutputProductsGridContent(final ViewDefinitionState viewDefinitionState, final Entity order) { GridComponent outputProducts = (GridComponent) viewDefinitionState.getComponentByReference("outputProductsGrid"); List<Entity> outputProductsList = new ArrayList<Entity>(); for (Entity productionRecord : order.getHasManyField("productionRecords")) { outputProductsList.addAll(productionRecord.getHasManyField("recordOperationProductOutComponents")); } Collections.sort(outputProductsList, new EntityProductInOutComparator()); outputProducts.setEntities(productionBalanceReportDataService.groupProductInOutComponentsByProduct(outputProductsList)); outputProducts.setVisible(true); }
mes-plugins/mes-plugins-production-counting/src/main/java/com/qcadoo/mes/productionCounting/internal/ProductionBalanceViewService.java
satd-removal_data_30
todo: HTTPS values public void processAction(ActionRequest actionRequest, ActionResponse actionResponse) throws PortletException, IOException { String mode = actionRequest.getParameter("mode"); WebContainer container = PortletManager.getCurrentWebContainer(actionRequest); String server = "generic"; if(container instanceof JettyContainer) { server = "jetty"; } actionResponse.setRenderParameter("server", server); if(mode.equals("new")) { // User selected to add a new connector, need to show criteria portlet actionResponse.setRenderParameter("mode", "new"); String protocol = actionRequest.getParameter("protocol"); actionResponse.setRenderParameter("protocol", protocol); } else if(mode.equals("add")) { // User just submitted the form to add a new connector // Get submitted values //todo: lots of validation String protocol = actionRequest.getParameter("protocol"); String host = actionRequest.getParameter("host"); int port = Integer.parseInt(actionRequest.getParameter("port")); int maxThreads = Integer.parseInt(actionRequest.getParameter("maxThreads")); Integer minThreads = getInteger(actionRequest, "minThreads"); String name = actionRequest.getParameter("name"); // Create and configure the connector WebConnector connector = PortletManager.createWebConnector(actionRequest, name, protocol, host, port); connector.setMaxThreads(maxThreads); // todo: more configurable HTTP/Jetty values if(connector instanceof JettyWebConnector) { if(minThreads != null) { ((JettyWebConnector)connector).setMinThreads(minThreads.intValue()); } } if(protocol.equals(WebContainer.PROTOCOL_HTTPS)) { //todo: HTTPS values } // Start the connector try { ((GeronimoManagedBean)connector).startRecursive(); } catch (Exception e) { log.error("Unable to start connector", e); //todo: get into rendered page somehow? } actionResponse.setRenderParameter("mode", "list"); } else if(mode.equals("save")) { // User just submitted the form to update a connector // Get submitted values //todo: lots of validation String host = actionRequest.getParameter("host"); int port = Integer.parseInt(actionRequest.getParameter("port")); int maxThreads = Integer.parseInt(actionRequest.getParameter("maxThreads")); Integer minThreads = getInteger(actionRequest, "minThreads"); String objectName = actionRequest.getParameter("objectName"); // Identify and update the connector WebConnector connector = null; WebConnector all[] = PortletManager.getWebConnectors(actionRequest); for (int i = 0; i < all.length; i++) { WebConnector conn = all[i]; if(((GeronimoManagedBean)conn).getObjectName().equals(objectName)) { connector = conn; break; } } if(connector != null) { connector.setHost(host); connector.setPort(port); connector.setMaxThreads(maxThreads); if(connector instanceof JettyWebConnector) { if(minThreads != null) { ((JettyWebConnector)connector).setMinThreads(minThreads.intValue()); } } } actionResponse.setRenderParameter("mode", "list"); } else if(mode.equals("start")) { String objectName = actionRequest.getParameter("name"); // work with the current connector to start it. WebConnector connector = null; WebConnector all[] = PortletManager.getWebConnectors(actionRequest); for (int i = 0; i < all.length; i++) { WebConnector conn = all[i]; if(((GeronimoManagedBean)conn).getObjectName().equals(objectName)) { connector = conn; break; } } if(connector != null) { try { ((GeronimoManagedBean)connector).startRecursive(); } catch (Exception e) { log.error("Unable to start connector", e); //todo: get into rendered page somehow? } } else { log.error("Incorrect connector reference"); //Replace this with correct error processing } actionResponse.setRenderParameter("name", objectName); actionResponse.setRenderParameter("mode", "list"); } else if(mode.equals("stop")) { String objectName = actionRequest.getParameter("name"); // work with the current connector to stop it. WebConnector connector = null; WebConnector all[] = PortletManager.getWebConnectors(actionRequest); for (int i = 0; i < all.length; i++) { WebConnector conn = all[i]; if(((GeronimoManagedBean)conn).getObjectName().equals(objectName)) { connector = conn; break; } } if(connector != null) { try { ((GeronimoManagedBean)connector).stop(); } catch (Exception e) { log.error("Unable to stop connector", e); //todo: get into rendered page somehow? } } else { log.error("Incorrect connector reference"); //Replace this with correct error processing } actionResponse.setRenderParameter("name", objectName); actionResponse.setRenderParameter("mode", "list"); } else if(mode.equals("edit")) { String objectName = actionRequest.getParameter("name"); actionResponse.setRenderParameter("objectName", objectName); actionResponse.setRenderParameter("mode", "edit"); } else if(mode.equals("delete")) { // User chose to delete a connector String objectName = actionRequest.getParameter("name"); PortletManager.getCurrentWebContainer(actionRequest).removeConnector(objectName); actionResponse.setRenderParameter("mode", "list"); } } public void processAction(ActionRequest actionRequest, ActionResponse actionResponse) throws PortletException, IOException { String mode = actionRequest.getParameter("mode"); WebContainer container = PortletManager.getCurrentWebContainer(actionRequest); String server = "generic"; if(container instanceof JettyContainer) { server = "jetty"; } else if (container instanceof TomcatContainer) { server = "tomcat"; } actionResponse.setRenderParameter("server", server); if(mode.equals("new")) { // User selected to add a new connector, need to show criteria portlet actionResponse.setRenderParameter("mode", "new"); String protocol = actionRequest.getParameter("protocol"); actionResponse.setRenderParameter("protocol", protocol); } else if(mode.equals("add")) { // User just submitted the form to add a new connector // Get submitted values //todo: lots of validation String protocol = actionRequest.getParameter("protocol"); String host = actionRequest.getParameter("host"); int port = Integer.parseInt(actionRequest.getParameter("port")); int maxThreads = Integer.parseInt(actionRequest.getParameter("maxThreads")); Integer minThreads = getInteger(actionRequest, "minThreads"); String name = actionRequest.getParameter("name"); // Create and configure the connector WebConnector connector = PortletManager.createWebConnector(actionRequest, name, protocol, host, port); connector.setMaxThreads(maxThreads); // todo: more configurable HTTP/Jetty values if(connector instanceof JettyWebConnector) { if(minThreads != null) { ((JettyWebConnector)connector).setMinThreads(minThreads.intValue()); } } if(protocol.equals(WebContainer.PROTOCOL_HTTPS)) { String keystoreType = actionRequest.getParameter("keystoreType"); String keystoreFile = actionRequest.getParameter("keystoreFile"); String privateKeyPass = actionRequest.getParameter("privateKeyPassword"); String keystorePass = actionRequest.getParameter("keystorePassword"); String secureProtocol = actionRequest.getParameter("secureProtocol"); String algorithm = actionRequest.getParameter("algorithm"); boolean clientAuth = isValid(actionRequest.getParameter("clientAuth")); SecureConnector secure = (SecureConnector) connector; if(isValid(keystoreType)) {secure.setKeystoreType(keystoreType);} if(isValid(keystoreFile)) {secure.setKeystoreFileName(keystoreFile);} if(isValid(keystorePass)) {secure.setKeystorePassword(keystorePass);} if(isValid(secureProtocol)) {secure.setSecureProtocol(secureProtocol);} if(isValid(algorithm)) {secure.setAlgorithm(algorithm);} secure.setClientAuthRequired(clientAuth); if(secure instanceof JettySecureConnector) { if(isValid(privateKeyPass)) {((JettySecureConnector)secure).setKeyPassword(privateKeyPass);} } } // Start the connector try { ((GeronimoManagedBean)connector).startRecursive(); } catch (Exception e) { log.error("Unable to start connector", e); //todo: get into rendered page somehow? } actionResponse.setRenderParameter("mode", "list"); } else if(mode.equals("save")) { // User just submitted the form to update a connector // Get submitted values //todo: lots of validation String host = actionRequest.getParameter("host"); int port = Integer.parseInt(actionRequest.getParameter("port")); int maxThreads = Integer.parseInt(actionRequest.getParameter("maxThreads")); Integer minThreads = getInteger(actionRequest, "minThreads"); String objectName = actionRequest.getParameter("objectName"); // Identify and update the connector WebConnector connector = null; WebConnector all[] = PortletManager.getWebConnectors(actionRequest); for (int i = 0; i < all.length; i++) { WebConnector conn = all[i]; if(((GeronimoManagedBean)conn).getObjectName().equals(objectName)) { connector = conn; break; } } if(connector != null) { connector.setHost(host); connector.setPort(port); connector.setMaxThreads(maxThreads); if(connector instanceof JettyWebConnector) { if(minThreads != null) { ((JettyWebConnector)connector).setMinThreads(minThreads.intValue()); } } if(connector instanceof SecureConnector) { String keystoreType = actionRequest.getParameter("keystoreType"); String keystoreFile = actionRequest.getParameter("keystoreFile"); String privateKeyPass = actionRequest.getParameter("privateKeyPassword"); String keystorePass = actionRequest.getParameter("keystorePassword"); String secureProtocol = actionRequest.getParameter("secureProtocol"); String algorithm = actionRequest.getParameter("algorithm"); boolean clientAuth = isValid(actionRequest.getParameter("clientAuth")); SecureConnector secure = (SecureConnector) connector; if(isValid(keystoreType)) {secure.setKeystoreType(keystoreType);} if(isValid(keystoreFile)) {secure.setKeystoreFileName(keystoreFile);} if(isValid(keystorePass)) {secure.setKeystorePassword(keystorePass);} if(isValid(secureProtocol)) {secure.setSecureProtocol(secureProtocol);} if(isValid(algorithm)) {secure.setAlgorithm(algorithm);} secure.setClientAuthRequired(clientAuth); if(secure instanceof JettySecureConnector) { if(isValid(privateKeyPass)) {((JettySecureConnector)secure).setKeyPassword(privateKeyPass);} } } } actionResponse.setRenderParameter("mode", "list"); } else if(mode.equals("start")) { String objectName = actionRequest.getParameter("name"); // work with the current connector to start it. WebConnector connector = null; WebConnector all[] = PortletManager.getWebConnectors(actionRequest); for (int i = 0; i < all.length; i++) { WebConnector conn = all[i]; if(((GeronimoManagedBean)conn).getObjectName().equals(objectName)) { connector = conn; break; } } if(connector != null) { try { ((GeronimoManagedBean)connector).startRecursive(); } catch (Exception e) { log.error("Unable to start connector", e); //todo: get into rendered page somehow? } } else { log.error("Incorrect connector reference"); //Replace this with correct error processing } actionResponse.setRenderParameter("name", objectName); actionResponse.setRenderParameter("mode", "list"); } else if(mode.equals("stop")) { String objectName = actionRequest.getParameter("name"); // work with the current connector to stop it. WebConnector connector = null; WebConnector all[] = PortletManager.getWebConnectors(actionRequest); for (int i = 0; i < all.length; i++) { WebConnector conn = all[i]; if(((GeronimoManagedBean)conn).getObjectName().equals(objectName)) { connector = conn; break; } } if(connector != null) { try { ((GeronimoManagedBean)connector).stop(); } catch (Exception e) { log.error("Unable to stop connector", e); //todo: get into rendered page somehow? } } else { log.error("Incorrect connector reference"); //Replace this with correct error processing } actionResponse.setRenderParameter("name", objectName); actionResponse.setRenderParameter("mode", "list"); } else if(mode.equals("edit")) { String objectName = actionRequest.getParameter("name"); actionResponse.setRenderParameter("objectName", objectName); actionResponse.setRenderParameter("mode", "edit"); } else if(mode.equals("delete")) { // User chose to delete a connector String objectName = actionRequest.getParameter("name"); PortletManager.getCurrentWebContainer(actionRequest).removeConnector(objectName); actionResponse.setRenderParameter("mode", "list"); } }
applications/console-standard/src/java/org/apache/geronimo/console/webmanager/ConnectorPortlet.java
satd-removal_data_31
FIXME: Make a static with the default search provider private void loadSearchProvider( final Properties properties ) { // See if we're using Lucene, and if so, ensure that its index directory is up to date. final String providerClassName = TextUtil.getStringProperty( properties, PROP_SEARCHPROVIDER, DEFAULT_SEARCHPROVIDER ); try { final Class<?> providerClass = ClassUtil.findClass( "org.apache.wiki.search", providerClassName ); m_searchProvider = ( SearchProvider )providerClass.newInstance(); } catch( final ClassNotFoundException | InstantiationException | IllegalAccessException e ) { log.warn("Failed loading SearchProvider, will use BasicSearchProvider.", e); } if( null == m_searchProvider ) { // FIXME: Make a static with the default search provider m_searchProvider = new BasicSearchProvider(); } log.debug("Loaded search provider " + m_searchProvider); } private void loadSearchProvider( final Properties properties ) { // See if we're using Lucene, and if so, ensure that its index directory is up-to-date. final String providerClassName = TextUtil.getStringProperty( properties, PROP_SEARCHPROVIDER, DEFAULT_SEARCHPROVIDER ); try { m_searchProvider = ClassUtil.buildInstance( "org.apache.wiki.search", providerClassName ); } catch( final ReflectiveOperationException e ) { log.warn( "Failed loading SearchProvider, will use BasicSearchProvider.", e ); } if( null == m_searchProvider ) { m_searchProvider = new BasicSearchProvider(); } log.debug( "Loaded search provider {}", m_searchProvider ); }
jspwiki-main/src/main/java/org/apache/wiki/search/DefaultSearchManager.java
satd-removal_data_32
todo sync this @Override public void processResult(int i, String s, Object o, String s1) { KeeperException.Code returnCode = KeeperException.Code.get(i); ZkLocalStatusAndEndpoints statusAndEndpoints = (ZkLocalStatusAndEndpoints) o; log.info("Claim callback " + returnCode.name() + " " + s); switch (returnCode) { case OK: synchronized (this) { storage = Storage.DIRTY; } try { // todo sync this statusAndEndpoints.writeStatusEndpoint(); synchronized (statusAndEndpoints) { statusAndEndpoints.storage = Storage.SYNCED; } } catch (CoordinateMissingException e) { log.info("Problems writing config, coordinate missing"); statusAndEndpoints.updateCoordinateListenersAndTakeAction( CoordinateListener.Event.NOT_OWNER, "Can not write config: " + returnCode.name() + " " + s); break; } catch (CloudnameException e) { log.info("Problems writing config." + e.getMessage()); statusAndEndpoints.updateCoordinateListenersAndTakeAction( CoordinateListener.Event.LOST_CONNECTION_TO_STORAGE, "Can not write config after claim: " + returnCode.name() + " " + s); break; } statusAndEndpoints.updateCoordinateListenersAndTakeAction( CoordinateListener.Event.COORDINATE_OK, "synced on recovery"); break; case NODEEXISTS: synchronized (statusAndEndpoints) { if (statusAndEndpoints.storage == Storage.DIRTY || statusAndEndpoints.storage == Storage.SYNCED ) { break; } } // synchronized (this) { // storage = Storage.UNCLAIMED; // } statusAndEndpoints.updateCoordinateListenersAndTakeAction( CoordinateListener.Event.NOT_OWNER, "Node already exists."); break; case NONODE: // synchronized (this) { //storage = Storage.UNCLAIMED; // } statusAndEndpoints.updateCoordinateListenersAndTakeAction( CoordinateListener.Event.NOT_OWNER, "No node on claiming coordinate: " + returnCode.name() + " " + s); break; default: //synchronized (this) { // storage = Storage.UNCLAIMED; //} statusAndEndpoints.updateCoordinateListenersAndTakeAction( CoordinateListener.Event.LOST_CONNECTION_TO_STORAGE, "Could not reclaim coordinate. Return code: " + returnCode.name() + " " + s); } } @Override public void processResult(int i, String s, Object o, String s1) { KeeperException.Code returnCode = KeeperException.Code.get(i); ZkLocalStatusAndEndpoints statusAndEndpoints = (ZkLocalStatusAndEndpoints) o; log.info("Claim callback " + returnCode.name() + " " + s); switch (returnCode) { case OK: synchronized (statusAndEndpoints) { try { statusAndEndpoints.writeStatusEndpoint(); storage = Storage.SYNCED; } catch (CoordinateMissingException e) { log.info("Problems writing config, coordinate missing"); statusAndEndpoints.updateCoordinateListenersAndTakeAction( CoordinateListener.Event.NOT_OWNER, "Can not write config: " + returnCode.name() + " " + s); break; } catch (CloudnameException e) { log.info("Problems writing config." + e.getMessage()); statusAndEndpoints.updateCoordinateListenersAndTakeAction( CoordinateListener.Event.LOST_CONNECTION_TO_STORAGE, "Can not write config after claim: " + returnCode.name() + " " + s); break; } } statusAndEndpoints.updateCoordinateListenersAndTakeAction( CoordinateListener.Event.COORDINATE_OK, "synced on recovery"); break; case NODEEXISTS: synchronized (statusAndEndpoints) { // If everything is fine, this is not a true negative, so ignore it. if (storage == Storage.SYNCED && claimed) { break; } } statusAndEndpoints.updateCoordinateListenersAndTakeAction( CoordinateListener.Event.NOT_OWNER, "Node already exists."); break; case NONODE: statusAndEndpoints.updateCoordinateListenersAndTakeAction( CoordinateListener.Event.NOT_OWNER, "No node on claiming coordinate: " + returnCode.name() + " " + s); break; default: statusAndEndpoints.updateCoordinateListenersAndTakeAction( CoordinateListener.Event.LOST_CONNECTION_TO_STORAGE, "Could not reclaim coordinate. Return code: " + returnCode.name() + " " + s); } }
cn/src/main/java/org/cloudname/zk/ZkLocalStatusAndEndpoints.java
satd-removal_data_33
TODO - use type NAMEDRANGE public void setRefersToFormula(String formulaText) { XSSFEvaluationWorkbook fpb = XSSFEvaluationWorkbook.create(workbook); Ptg[] ptgs; try { ptgs = FormulaParser.parse(formulaText, fpb, FormulaType.CELL); // TODO - use type NAMEDRANGE } catch (RuntimeException e) { if (e.getClass().getName().startsWith(FormulaParser.class.getName())) { throw new IllegalArgumentException("Unparsable formula '" + formulaText + "'", e); } throw e; } ctName.setStringValue(formulaText); } public void setRefersToFormula(String formulaText) { XSSFEvaluationWorkbook fpb = XSSFEvaluationWorkbook.create(workbook); try { Ptg[] ptgs = FormulaParser.parse(formulaText, fpb, FormulaType.NAMEDRANGE); } catch (RuntimeException e) { if (e.getClass().getName().startsWith(FormulaParser.class.getName())) { throw new IllegalArgumentException("Unparsable formula '" + formulaText + "'", e); } throw e; } ctName.setStringValue(formulaText); }
src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFName.java
satd-removal_data_34
TODO add description private void ingestWork(ContentContainerObject parent, Resource parentResc, Resource childResc) throws DepositException { PID childPid = PIDs.get(childResc.getURI()); WorkObject obj; boolean skip = skipResumed(childResc); if (skip) { obj = repository.getWorkObject(childPid); ingestChildren(obj, childResc); // Avoid adding primaryObject relation for a resuming deposit if already present if (!obj.getResource().hasProperty(Cdr.primaryObject)) { // Set the primary object for this work if one was specified addPrimaryObject(obj, childResc); } } else { Model model = ModelFactory.createDefaultModel(); Resource workResc = model.getResource(childPid.getRepositoryPath()); populateAIPProperties(childResc, workResc); // send txid along with uris for the following actions FedoraTransaction tx = repository.startTransaction(); // TODO add ACLs try { obj = repository.createWorkObject(childPid, model); parent.addMember(obj); // TODO add description // Increment the count of objects deposited prior to adding children addClicks(1); log.info("Created work object {} for deposit {}", childPid, getDepositPID()); ingestChildren(obj, childResc); // Set the primary object for this work if one was specified addPrimaryObject(obj, childResc); } catch(Exception e) { tx.cancel(e); } finally { tx.close(); } } } private void ingestWork(ContentContainerObject parent, Resource parentResc, Resource childResc) throws DepositException, IOException { PID childPid = PIDs.get(childResc.getURI()); WorkObject obj; boolean skip = skipResumed(childResc); if (skip) { obj = repository.getWorkObject(childPid); ingestChildren(obj, childResc); // Avoid adding primaryObject relation for a resuming deposit if already present if (!obj.getResource().hasProperty(Cdr.primaryObject)) { // Set the primary object for this work if one was specified addPrimaryObject(obj, childResc); } } else { Model model = ModelFactory.createDefaultModel(); Resource workResc = model.getResource(childPid.getRepositoryPath()); populateAIPProperties(childResc, workResc); // send txid along with uris for the following actions FedoraTransaction tx = repository.startTransaction(); // TODO add ACLs try { obj = repository.createWorkObject(childPid, model); parent.addMember(obj); addDescription(obj); // Increment the count of objects deposited prior to adding children addClicks(1); log.info("Created work object {} for deposit {}", childPid, getDepositPID()); ingestChildren(obj, childResc); // Set the primary object for this work if one was specified addPrimaryObject(obj, childResc); } catch(Exception e) { tx.cancel(e); } finally { tx.close(); } } }
deposit/src/main/java/edu/unc/lib/deposit/fcrepo4/IngestContentObjectsJob.java
satd-removal_data_35
TODO(kevinb): why does the source come out as unknown?? public void testInjectInnerClass() throws Exception { Injector injector = Guice.createInjector(); try { injector.getInstance(InnerClass.class); fail(); } catch (Exception expected) { // TODO(kevinb): why does the source come out as unknown?? assertContains(expected.getMessage(), "Error at " + InnerClass.class.getName() + ".class(ErrorMessagesTest.java:", "Injecting into inner classes is not supported."); } } public void testInjectInnerClass() throws Exception { Injector injector = Guice.createInjector(); try { injector.getInstance(InnerClass.class); fail(); } catch (Exception expected) { assertContains(expected.getMessage(), "Injecting into inner classes is not supported.", "at " + InnerClass.class.getName() + ".class(ErrorMessagesTest.java:"); } }
test/com/google/inject/ErrorMessagesTest.java
satd-removal_data_36
TODO Copy as Image to Clipboard. But not on Linux 64-bit. See https://bugs.eclipse.org/bugs/show_bug.cgi?id=283960 private void makeLocalToolBar() { IActionBars bars = getViewSite().getActionBars(); IToolBarManager manager = bars.getToolBarManager(); fDrillDownManager.addNavigationActions(manager); manager.add(new Separator()); manager.add(fActionPinContent); manager.add(new Separator()); manager.add(fActionLayout); final IMenuManager menuManager = bars.getMenuManager(); IMenuManager depthMenuManager = new MenuManager(Messages.ZestView_3); menuManager.add(depthMenuManager); // Depth Actions fDepthActions = new Action[6]; for(int i = 0; i < fDepthActions.length; i++) { fDepthActions[i] = createDepthAction(i, i + 1); depthMenuManager.add(fDepthActions[i]); } // Set depth from prefs int depth = ArchiZestPlugin.INSTANCE.getPreferenceStore().getInt(IPreferenceConstants.VISUALISER_DEPTH); getContentProvider().setDepth(depth); fDepthActions[depth].setChecked(true); // Set filter based on Viewpoint IMenuManager viewpointMenuManager = new MenuManager(Messages.ZestView_5); menuManager.add(viewpointMenuManager); // Get viewpoint from prefs String viewpointID = ArchiZestPlugin.INSTANCE.getPreferenceStore().getString(IPreferenceConstants.VISUALISER_VIEWPOINT); getContentProvider().setViewpointFilter(ViewpointManager.INSTANCE.getViewpoint(viewpointID)); // Viewpoint actions fViewpointActions = new ArrayList<IAction>(); for(IViewpoint vp : ViewpointManager.INSTANCE.getAllViewpoints()) { IAction action = createViewpointMenuAction(vp); fViewpointActions.add(action); viewpointMenuManager.add(action); // Set checked if(vp.getID().equals(viewpointID)) { action.setChecked(true); } } // Set filter based on Relationship IMenuManager relationshipMenuManager = new MenuManager(Messages.ZestView_6); menuManager.add(relationshipMenuManager); // Get relationship from prefs String relationshipID = ArchiZestPlugin.INSTANCE.getPreferenceStore().getString(IPreferenceConstants.VISUALISER_RELATIONSHIP); EClass eClass = (EClass)IArchimatePackage.eINSTANCE.getEClassifier(relationshipID); getContentProvider().setRelationshipFilter(eClass); // Relationship actions, first the "None" relationship fRelationshipActions = new ArrayList<IAction>(); IAction action = createRelationshipMenuAction(null); if(eClass == null) { action.setChecked(true); } fRelationshipActions.add(action); relationshipMenuManager.add(action); // Then get all relationships and sort them ArrayList<EClass> actionList = new ArrayList<EClass>(Arrays.asList(ArchimateModelUtils.getRelationsClasses())); actionList.sort((o1, o2) -> o1.getName().compareTo(o2.getName())); for(EClass rel : actionList) { action = createRelationshipMenuAction(rel); fRelationshipActions.add(action); relationshipMenuManager.add(action); // Set checked if(eClass != null && rel.getName().equals(eClass.getName())) { action.setChecked(true); } } // Orientation IMenuManager orientationMenuManager = new MenuManager(Messages.ZestView_32); menuManager.add(orientationMenuManager); // Direction fDirectionActions = new Action[3]; fDirectionActions[0] = createOrientationMenuAction(0, Messages.ZestView_33, ZestViewerContentProvider.DIR_BOTH); orientationMenuManager.add(fDirectionActions[0]); fDirectionActions[1] = createOrientationMenuAction(1, Messages.ZestView_34, ZestViewerContentProvider.DIR_IN); orientationMenuManager.add(fDirectionActions[1]); fDirectionActions[2] = createOrientationMenuAction(2, Messages.ZestView_35, ZestViewerContentProvider.DIR_OUT); orientationMenuManager.add(fDirectionActions[2]); // Set direction from prefs int direction = ArchiZestPlugin.INSTANCE.getPreferenceStore().getInt(IPreferenceConstants.VISUALISER_DIRECTION); getContentProvider().setDirection(direction); fDirectionActions[direction].setChecked(true); menuManager.add(new Separator()); // TODO Copy as Image to Clipboard. But not on Linux 64-bit. See https://bugs.eclipse.org/bugs/show_bug.cgi?id=283960 if(!(PlatformUtils.isLinux() && PlatformUtils.is64Bit())) { menuManager.add(fActionCopyImageToClipboard); } menuManager.add(fActionExportImageToFile); } private void makeLocalToolBar() { IActionBars bars = getViewSite().getActionBars(); IToolBarManager manager = bars.getToolBarManager(); fDrillDownManager.addNavigationActions(manager); manager.add(new Separator()); manager.add(fActionPinContent); manager.add(new Separator()); manager.add(fActionLayout); final IMenuManager menuManager = bars.getMenuManager(); IMenuManager depthMenuManager = new MenuManager(Messages.ZestView_3); menuManager.add(depthMenuManager); // Depth Actions fDepthActions = new Action[6]; for(int i = 0; i < fDepthActions.length; i++) { fDepthActions[i] = createDepthAction(i, i + 1); depthMenuManager.add(fDepthActions[i]); } // Set depth from prefs int depth = ArchiZestPlugin.INSTANCE.getPreferenceStore().getInt(IPreferenceConstants.VISUALISER_DEPTH); getContentProvider().setDepth(depth); fDepthActions[depth].setChecked(true); // Set filter based on Viewpoint IMenuManager viewpointMenuManager = new MenuManager(Messages.ZestView_5); menuManager.add(viewpointMenuManager); // Get viewpoint from prefs String viewpointID = ArchiZestPlugin.INSTANCE.getPreferenceStore().getString(IPreferenceConstants.VISUALISER_VIEWPOINT); getContentProvider().setViewpointFilter(ViewpointManager.INSTANCE.getViewpoint(viewpointID)); // Viewpoint actions fViewpointActions = new ArrayList<IAction>(); for(IViewpoint vp : ViewpointManager.INSTANCE.getAllViewpoints()) { IAction action = createViewpointMenuAction(vp); fViewpointActions.add(action); viewpointMenuManager.add(action); // Set checked if(vp.getID().equals(viewpointID)) { action.setChecked(true); } } // Set filter based on Relationship IMenuManager relationshipMenuManager = new MenuManager(Messages.ZestView_6); menuManager.add(relationshipMenuManager); // Get relationship from prefs String relationshipID = ArchiZestPlugin.INSTANCE.getPreferenceStore().getString(IPreferenceConstants.VISUALISER_RELATIONSHIP); EClass eClass = (EClass)IArchimatePackage.eINSTANCE.getEClassifier(relationshipID); getContentProvider().setRelationshipFilter(eClass); // Relationship actions, first the "None" relationship fRelationshipActions = new ArrayList<IAction>(); IAction action = createRelationshipMenuAction(null); if(eClass == null) { action.setChecked(true); } fRelationshipActions.add(action); relationshipMenuManager.add(action); // Then get all relationships and sort them ArrayList<EClass> actionList = new ArrayList<EClass>(Arrays.asList(ArchimateModelUtils.getRelationsClasses())); actionList.sort((o1, o2) -> o1.getName().compareTo(o2.getName())); for(EClass rel : actionList) { action = createRelationshipMenuAction(rel); fRelationshipActions.add(action); relationshipMenuManager.add(action); // Set checked if(eClass != null && rel.getName().equals(eClass.getName())) { action.setChecked(true); } } // Orientation IMenuManager orientationMenuManager = new MenuManager(Messages.ZestView_32); menuManager.add(orientationMenuManager); // Direction fDirectionActions = new Action[3]; fDirectionActions[0] = createOrientationMenuAction(0, Messages.ZestView_33, ZestViewerContentProvider.DIR_BOTH); orientationMenuManager.add(fDirectionActions[0]); fDirectionActions[1] = createOrientationMenuAction(1, Messages.ZestView_34, ZestViewerContentProvider.DIR_IN); orientationMenuManager.add(fDirectionActions[1]); fDirectionActions[2] = createOrientationMenuAction(2, Messages.ZestView_35, ZestViewerContentProvider.DIR_OUT); orientationMenuManager.add(fDirectionActions[2]); // Set direction from prefs int direction = ArchiZestPlugin.INSTANCE.getPreferenceStore().getInt(IPreferenceConstants.VISUALISER_DIRECTION); getContentProvider().setDirection(direction); fDirectionActions[direction].setChecked(true); menuManager.add(new Separator()); menuManager.add(fActionCopyImageToClipboard); menuManager.add(fActionExportImageToFile); }
com.archimatetool.zest/src/com/archimatetool/zest/ZestView.java
satd-removal_data_37
XXX lang is not checked?? private void walk(Node n, Parse parse, HTMLMetaTags metaTags, String base, List outlinks) { if (n instanceof Element) { String name = n.getNodeName(); if (name.equalsIgnoreCase("script")) { String lang = null; Node lNode = n.getAttributes().getNamedItem("language"); if (lNode == null) lang = "javascript"; else lang = lNode.getNodeValue(); //XXX lang is not checked?? StringBuffer script = new StringBuffer(); NodeList nn = n.getChildNodes(); if (nn.getLength() > 0) { for (int i = 0; i < nn.getLength(); i++) { if (i > 0) script.append('\n'); script.append(nn.item(i).getNodeValue()); } if (LOG.isDebugEnabled()) { LOG.info("script: language=" + lang + ", text: " + script.toString()); } Outlink[] links = getJSLinks(script.toString(), "", base); if (links != null && links.length > 0) outlinks.addAll(Arrays.asList(links)); // no other children of interest here, go one level up. return; } } else { // process all HTML 4.0 events, if present... NamedNodeMap attrs = n.getAttributes(); int len = attrs.getLength(); for (int i = 0; i < len; i++) { // Window: onload,onunload // Form: onchange,onsubmit,onreset,onselect,onblur,onfocus // Keyboard: onkeydown,onkeypress,onkeyup // Mouse: onclick,ondbclick,onmousedown,onmouseout,onmousover,onmouseup Node anode = attrs.item(i); Outlink[] links = null; if (anode.getNodeName().startsWith("on")) { links = getJSLinks(anode.getNodeValue(), "", base); } else if (anode.getNodeName().equalsIgnoreCase("href")) { String val = anode.getNodeValue(); if (val != null && val.toLowerCase().indexOf("javascript:") != -1) { links = getJSLinks(val, "", base); } } if (links != null && links.length > 0) outlinks.addAll(Arrays.asList(links)); } } } NodeList nl = n.getChildNodes(); for (int i = 0; i < nl.getLength(); i++) { walk(nl.item(i), parse, metaTags, base, outlinks); } } private void walk(Node n, Parse parse, HTMLMetaTags metaTags, String base, List outlinks) { if (n instanceof Element) { String name = n.getNodeName(); if (name.equalsIgnoreCase("script")) { String lang = null; Node lNode = n.getAttributes().getNamedItem("language"); if (lNode == null) lang = "javascript"; else lang = lNode.getNodeValue(); StringBuffer script = new StringBuffer(); NodeList nn = n.getChildNodes(); if (nn.getLength() > 0) { for (int i = 0; i < nn.getLength(); i++) { if (i > 0) script.append('\n'); script.append(nn.item(i).getNodeValue()); } // if (LOG.isInfoEnabled()) { // LOG.info("script: language=" + lang + ", text: " + script.toString()); // } Outlink[] links = getJSLinks(script.toString(), "", base); if (links != null && links.length > 0) outlinks.addAll(Arrays.asList(links)); // no other children of interest here, go one level up. return; } } else { // process all HTML 4.0 events, if present... NamedNodeMap attrs = n.getAttributes(); int len = attrs.getLength(); for (int i = 0; i < len; i++) { // Window: onload,onunload // Form: onchange,onsubmit,onreset,onselect,onblur,onfocus // Keyboard: onkeydown,onkeypress,onkeyup // Mouse: onclick,ondbclick,onmousedown,onmouseout,onmousover,onmouseup Node anode = attrs.item(i); Outlink[] links = null; if (anode.getNodeName().startsWith("on")) { links = getJSLinks(anode.getNodeValue(), "", base); } else if (anode.getNodeName().equalsIgnoreCase("href")) { String val = anode.getNodeValue(); if (val != null && val.toLowerCase().indexOf("javascript:") != -1) { links = getJSLinks(val, "", base); } } if (links != null && links.length > 0) outlinks.addAll(Arrays.asList(links)); } } } NodeList nl = n.getChildNodes(); for (int i = 0; i < nl.getLength(); i++) { walk(nl.item(i), parse, metaTags, base, outlinks); } }
src/plugin/parse-js/src/java/org/apache/nutch/parse/js/JSParseFilter.java
satd-removal_data_38
TODO: implement this! public void removeUserFromGroup(A_CmsUser currentUser, A_CmsProject currentProject, String username, String groupname) throws CmsException { // TODO: implement this! return ; } public void removeUserFromGroup(A_CmsUser currentUser, A_CmsProject currentProject, String username, String groupname) throws CmsException { // Check the security if( isAdmin(currentUser, currentProject) ) { m_userRb.removeUserFromGroup(username, groupname); } else { throw new CmsException(CmsException.C_EXTXT[CmsException.C_NO_ACCESS], CmsException.C_NO_ACCESS); } }
src/com/opencms/file/CmsResourceBroker.java
satd-removal_data_39
TODO what about placeholder for null? should be in searchresult (transient field?) @Override public void writeTo(SearchResponse searchResponse, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { final CSVWriter csvWriter = new CSVWriter(new OutputStreamWriter(entityStream)); final ImmutableSortedSet<String> sortedFields = ImmutableSortedSet.copyOf(searchResponse.fields); // write field headers csvWriter.writeNext(sortedFields.toArray(new String[sortedFields.size()])); // write result set in same order as the header row final String[] fieldValues = new String[sortedFields.size()]; for (ResultMessage message : searchResponse.messages) { int idx = 0; // first collect all values from the current message for (String fieldName : sortedFields) { final Object val = message.message.get(fieldName); fieldValues[idx++] = firstNonNull(val, "").toString(); // TODO what about placeholder for null? should be in searchresult (transient field?) } // write the complete line, some fields might not be present in the message, so there might be null values csvWriter.writeNext(fieldValues); } if (csvWriter.checkError()) { log.error("Encountered unspecified error when writing message result as CSV, result is likely malformed."); } csvWriter.close(); } @Override public void writeTo(SearchResponse searchResponse, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { final CSVWriter csvWriter = new CSVWriter(new OutputStreamWriter(entityStream)); final ImmutableSortedSet<String> sortedFields = ImmutableSortedSet.copyOf(searchResponse.fields); // write field headers csvWriter.writeNext(sortedFields.toArray(new String[sortedFields.size()])); // write result set in same order as the header row final String[] fieldValues = new String[sortedFields.size()]; for (ResultMessage message : searchResponse.messages) { int idx = 0; // first collect all values from the current message for (String fieldName : sortedFields) { final Object val = message.message.get(fieldName); fieldValues[idx++] = ((val == null) ? null : val.toString()); } // write the complete line, some fields might not be present in the message, so there might be null values csvWriter.writeNext(fieldValues); } if (csvWriter.checkError()) { log.error("Encountered unspecified error when writing message result as CSV, result is likely malformed."); } csvWriter.close(); }
graylog2-server/src/main/java/org/graylog2/rest/resources/search/responses/SearchResponseCsvWriter.java
satd-removal_data_40
TODO: multicast properties @Override public void execute(final AsyncCallback<List<SocketBinding>> callback) { // /socket-binding-group=standard-sockets:read-resource(recursive=true) ModelNode operation = new ModelNode(); operation.get(ADDRESS).add("socket-binding-group", groupName); operation.get(OP).set(READ_RESOURCE_OPERATION); operation.get(RECURSIVE).set(true); dispatcher.execute(new DMRAction(operation), new SimpleCallback<DMRResponse>() { @Override public void onSuccess(DMRResponse result) { ModelNode response = ModelNode.fromBase64(result.getResponseText()); ModelNode payload = response.get("result").asObject(); List<ModelNode> socketDescriptions= payload.get("socket-binding").asList(); List<SocketBinding> bindings = new ArrayList<SocketBinding>(); for(ModelNode socket : socketDescriptions) { ModelNode value = socket.asProperty().getValue(); SocketBinding sb = factory.socketBinding().as(); sb.setName(value.get("name").asString()); sb.setGroup(groupName); sb.setPort(value.get("port").asInt()); String interfaceValue = value.get("interface").isDefined() ? value.get("interface").asString() : "not set"; sb.setInterface(interfaceValue); // TODO: multicast properties sb.setMultiCastAddress("not set"); sb.setMultiCastPort(-1); bindings.add(sb); } callback.onSuccess(bindings); } }); } @Override public void execute(final AsyncCallback<List<SocketBinding>> callback) { // /socket-binding-group=standard-sockets:read-resource(recursive=true) ModelNode operation = new ModelNode(); operation.get(ADDRESS).add("socket-binding-group", groupName); operation.get(OP).set(READ_RESOURCE_OPERATION); operation.get(RECURSIVE).set(true); dispatcher.execute(new DMRAction(operation), new SimpleCallback<DMRResponse>() { @Override public void onSuccess(DMRResponse result) { ModelNode response = ModelNode.fromBase64(result.getResponseText()); ModelNode payload = response.get("result").asObject(); List<ModelNode> socketDescriptions= payload.get("socket-binding").asList(); List<SocketBinding> bindings = new ArrayList<SocketBinding>(); for(ModelNode socket : socketDescriptions) { ModelNode value = socket.asProperty().getValue(); SocketBinding sb = factory.socketBinding().as(); sb.setName(value.get("name").asString()); sb.setGroup(groupName); sb.setPort(value.get("port").asInt()); String interfaceValue = value.get("interface").isDefined() ? value.get("interface").asString() : "not set"; sb.setInterface(interfaceValue); if(value.hasDefined("multicast-port")) { sb.setMultiCastAddress(value.get("multicast-address").asString()); sb.setMultiCastPort(value.get("multicast-port").asInt()); } else { sb.setMultiCastAddress(""); sb.setMultiCastPort(0); } bindings.add(sb); } callback.onSuccess(bindings); } }); }
gui/src/main/java/org/jboss/as/console/client/shared/general/model/LoadSocketBindingsCmd.java
satd-removal_data_41
todo log message public void handleEvent(final ConnectedMessageChannel channel) { final Pooled<ByteBuffer> pooledBuffer = connection.allocate(); try { final ByteBuffer buffer = pooledBuffer.getResource(); final int res; try { res = channel.receive(buffer); } catch (IOException e) { connection.handleException(e); return; } if (res == 0) { return; } if (res == -1) { connection.handleException(client.abruptClose(connection)); return; } buffer.flip(); final byte msgType = buffer.get(); switch (msgType) { case Protocol.CONNECTION_ALIVE: { client.trace("Client received connection alive"); connection.sendAliveResponse(); return; } case Protocol.CONNECTION_ALIVE_ACK: { client.trace("Client received connection alive ack"); return; } case Protocol.CONNECTION_CLOSE: { client.trace("Client received connection close request"); connection.handlePreAuthCloseRequest(); return; } case Protocol.AUTH_CHALLENGE: { client.trace("Client received authentication challenge"); connection.getChannel().suspendReads(); connection.getExecutor().execute(new Runnable() { public void run() { final boolean clientComplete = saslClient.isComplete(); if (clientComplete) { connection.handleException(new SaslException("Received extra auth message after completion")); return; } final byte[] response; final byte[] challenge = Buffers.take(buffer, buffer.remaining()); try { response = saslClient.evaluateChallenge(challenge); if (msgType == Protocol.AUTH_COMPLETE && response != null && response.length > 0) { connection.handleException(new SaslException("Received extra auth message after completion")); return; } } catch (Exception e) { client.tracef("Client authentication failed: %s", e); failedMechs.add(saslClient.getMechanismName()); sendCapRequest(serverName); return; } client.trace("Client sending authentication response"); final Pooled<ByteBuffer> pooled = connection.allocate(); final ByteBuffer sendBuffer = pooled.getResource(); sendBuffer.put(Protocol.AUTH_RESPONSE); sendBuffer.put(response); sendBuffer.flip(); connection.send(pooled); connection.getChannel().resumeReads(); return; } }); return; } case Protocol.AUTH_COMPLETE: { client.trace("Client received authentication complete"); connection.getChannel().suspendReads(); connection.getExecutor().execute(new Runnable() { public void run() { final boolean clientComplete = saslClient.isComplete(); final byte[] challenge = Buffers.take(buffer, buffer.remaining()); if (!clientComplete) try { final byte[] response = saslClient.evaluateChallenge(challenge); if (response != null && response.length > 0) { connection.handleException(new SaslException("Received extra auth message after completion")); return; } if (!saslClient.isComplete()) { connection.handleException(new SaslException("Client not complete after processing auth complete message")); return; } } catch (SaslException e) { // todo log message failedMechs.add(saslClient.getMechanismName()); sendCapRequest(serverName); return; } final Object qop = saslClient.getNegotiatedProperty(Sasl.QOP); if ("auth-int".equals(qop) || "auth-conf".equals(qop)) { connection.setSaslWrapper(SaslWrapper.create(saslClient)); } // auth complete. final ConnectionHandlerFactory connectionHandlerFactory = new ConnectionHandlerFactory() { public ConnectionHandler createInstance(final ConnectionHandlerContext connectionContext) { // this happens immediately. final RemoteConnectionHandler connectionHandler = new RemoteConnectionHandler(connectionContext, connection, authorizationID, remoteEndpointName); connection.setReadListener(new RemoteReadListener(connectionHandler, connection)); return connectionHandler; } }; connection.getResult().setResult(connectionHandlerFactory); connection.getChannel().resumeReads(); return; } }); return; } case Protocol.AUTH_REJECTED: { client.trace("Client received authentication rejected"); failedMechs.add(saslClient.getMechanismName()); sendCapRequest(serverName); return; } default: { client.unknownProtocolId(msgType); connection.handleException(client.invalidMessage(connection)); return; } } } finally { pooledBuffer.free(); } } public void handleEvent(final ConnectedMessageChannel channel) { final Pooled<ByteBuffer> pooledBuffer = connection.allocate(); try { final ByteBuffer buffer = pooledBuffer.getResource(); final int res; try { res = channel.receive(buffer); } catch (IOException e) { connection.handleException(e); return; } if (res == 0) { return; } if (res == -1) { connection.handleException(client.abruptClose(connection)); return; } buffer.flip(); final byte msgType = buffer.get(); switch (msgType) { case Protocol.CONNECTION_ALIVE: { client.trace("Client received connection alive"); connection.sendAliveResponse(); return; } case Protocol.CONNECTION_ALIVE_ACK: { client.trace("Client received connection alive ack"); return; } case Protocol.CONNECTION_CLOSE: { client.trace("Client received connection close request"); connection.handlePreAuthCloseRequest(); return; } case Protocol.AUTH_CHALLENGE: { client.trace("Client received authentication challenge"); connection.getChannel().suspendReads(); connection.getExecutor().execute(new Runnable() { public void run() { final boolean clientComplete = saslClient.isComplete(); if (clientComplete) { connection.handleException(new SaslException("Received extra auth message after completion")); return; } final byte[] response; final byte[] challenge = Buffers.take(buffer, buffer.remaining()); try { response = saslClient.evaluateChallenge(challenge); if (msgType == Protocol.AUTH_COMPLETE && response != null && response.length > 0) { connection.handleException(new SaslException("Received extra auth message after completion")); return; } } catch (Throwable e) { final String mechanismName = saslClient.getMechanismName(); client.debugf("Client authentication failed for mechanism %s: %s", mechanismName, e); failedMechs.add(mechanismName); sendCapRequest(serverName); connection.getChannel().resumeReads(); return; } client.trace("Client sending authentication response"); final Pooled<ByteBuffer> pooled = connection.allocate(); final ByteBuffer sendBuffer = pooled.getResource(); sendBuffer.put(Protocol.AUTH_RESPONSE); sendBuffer.put(response); sendBuffer.flip(); connection.send(pooled); connection.getChannel().resumeReads(); return; } }); return; } case Protocol.AUTH_COMPLETE: { client.trace("Client received authentication complete"); connection.getChannel().suspendReads(); connection.getExecutor().execute(new Runnable() { public void run() { final boolean clientComplete = saslClient.isComplete(); final byte[] challenge = Buffers.take(buffer, buffer.remaining()); if (!clientComplete) try { final byte[] response = saslClient.evaluateChallenge(challenge); if (response != null && response.length > 0) { connection.handleException(new SaslException("Received extra auth message after completion")); return; } if (!saslClient.isComplete()) { connection.handleException(new SaslException("Client not complete after processing auth complete message")); return; } } catch (Throwable e) { final String mechanismName = saslClient.getMechanismName(); client.debugf("Client authentication failed for mechanism %s: %s", mechanismName, e); failedMechs.add(mechanismName); sendCapRequest(serverName); return; } final Object qop = saslClient.getNegotiatedProperty(Sasl.QOP); if ("auth-int".equals(qop) || "auth-conf".equals(qop)) { connection.setSaslWrapper(SaslWrapper.create(saslClient)); } // auth complete. final ConnectionHandlerFactory connectionHandlerFactory = new ConnectionHandlerFactory() { public ConnectionHandler createInstance(final ConnectionHandlerContext connectionContext) { // this happens immediately. final RemoteConnectionHandler connectionHandler = new RemoteConnectionHandler(connectionContext, connection, authorizationID, remoteEndpointName); connection.setReadListener(new RemoteReadListener(connectionHandler, connection)); return connectionHandler; } }; connection.getResult().setResult(connectionHandlerFactory); connection.getChannel().resumeReads(); return; } }); return; } case Protocol.AUTH_REJECTED: { final String mechanismName = saslClient.getMechanismName(); client.debugf("Client received authentication rejected for mechanism %s", mechanismName); failedMechs.add(mechanismName); sendCapRequest(serverName); return; } default: { client.unknownProtocolId(msgType); connection.handleException(client.invalidMessage(connection)); return; } } } finally { pooledBuffer.free(); } }
src/main/java/org/jboss/remoting3/remote/ClientConnectionOpenListener.java
satd-removal_data_42
TODO: Support exchange headers for wait and timeout values, see Exchange constants public void process(final Exchange exchange) throws Exception { final Processor output = getProcessor(); if (output == null) { // no output then return return; } // use a new copy of the exchange to route async final Exchange copy = exchange.newCopy(); // let it execute async and return the Future Callable<Exchange> task = new Callable<Exchange>() { public Exchange call() throws Exception { // must use a copy of the original exchange for processing async output.process(copy); return copy; } }; // sumbit the task Future<Exchange> future = getExecutorService().submit(task); // TODO: Support exchange headers for wait and timeout values, see Exchange constants if (waitTaskComplete) { // wait for task to complete Exchange response = future.get(); // if we are out capable then set the response on the original exchange if (ExchangeHelper.isOutCapable(exchange)) { ExchangeHelper.copyResults(exchange, response); } } else { // no we do not expect a reply so lets continue, set a handle to the future task // in case end user need it later exchange.getOut().setBody(future); } } public void process(final Exchange exchange) throws Exception { final Processor output = getProcessor(); if (output == null) { // no output then return return; } // use a new copy of the exchange to route async final Exchange copy = exchange.newCopy(); // let it execute async and return the Future Callable<Exchange> task = new Callable<Exchange>() { public Exchange call() throws Exception { // must use a copy of the original exchange for processing async output.process(copy); return copy; } }; // sumbit the task Future<Exchange> future = getExecutorService().submit(task); // compute if we should wait for task to complete or not boolean wait = waitTaskComplete; if (exchange.getIn().getHeader(Exchange.ASYNC_WAIT) != null) { wait = exchange.getIn().getHeader(Exchange.ASYNC_WAIT, Boolean.class); } if (wait) { // wait for task to complete Exchange response = future.get(); ExchangeHelper.copyResults(exchange, response); } else { // no we do not expect a reply so lets continue, set a handle to the future task // in case end user need it later exchange.getOut().setBody(future); } }
camel-core/src/main/java/org/apache/camel/processor/AsyncProcessor.java
satd-removal_data_43
TODO: Implement remove @Override public void remove(IdentityType value) throws IdentityManagementException { //TODO: Implement remove } @Override public void remove(IdentityType value) throws IdentityManagementException { storeSelector.getStoreForIdentityOperation(this, IdentityStore.class, IdentityType.class, IdentityOperation.delete) .remove(this, value); }
modules/idm/impl/src/main/java/org/picketlink/idm/internal/ContextualIdentityManager.java
satd-removal_data_44
TODO Add an error and a log public static void saveProjects() { ProjectsHandler projectsHandler = Activator.getDefault().getProjectsHandler(); File projectsFile = getProjectsFile(); try { BufferedWriter buffWriter = new BufferedWriter( new FileWriter( projectsFile ) ); buffWriter.write( ProjectsExporter.toXml( projectsHandler.getProjects().toArray( new Project[0] ) ) ); buffWriter.close(); } catch ( IOException e ) { // TODO Add an error and a log } } public static void saveProjects() { ProjectsHandler projectsHandler = Activator.getDefault().getProjectsHandler(); File projectsFile = getProjectsFile(); try { BufferedWriter buffWriter = new BufferedWriter( new FileWriter( projectsFile ) ); buffWriter.write( ProjectsExporter.toXml( projectsHandler.getProjects().toArray( new Project[0] ) ) ); buffWriter.close(); } catch ( IOException e ) { PluginUtils.logError( "An error occured when saving the projects.", e ); ViewUtils.displayErrorMessageBox( "Projects Saving Error", "An error occured when saving the projects." ); } }
studio-apacheds-schemaeditor/src/main/java/org/apache/directory/studio/apacheds/schemaeditor/PluginUtils.java
satd-removal_data_45
TODO should we do time out check between each object call? @Override public void initializeObjects(EntityInfo[] entityInfos, Criteria criteria, Class<?> entityType, SearchFactoryImplementor searchFactoryImplementor, TimeoutManager timeoutManager, Session session) { boolean traceEnabled = log.isTraceEnabled(); //Do not call isTimeOut here as the caller might be the last biggie on the list. final int maxResults = entityInfos.length; if ( maxResults == 0 ) { if ( traceEnabled ) { log.tracef( "No object to initialize", maxResults ); } return; } //TODO should we do time out check between each object call? for ( EntityInfo entityInfo : entityInfos ) { ObjectLoaderHelper.load( entityInfo, session ); } if ( traceEnabled ) { log.tracef( "Initialized %d objects by lookup method.", maxResults ); } } @Override public void initializeObjects(EntityInfo[] entityInfos, LinkedHashMap<EntityInfoLoadKey, Object> idToObjectMap, ObjectInitializationContext objectInitializationContext) { boolean traceEnabled = log.isTraceEnabled(); // Do not call isTimeOut here as the caller might be the last biggie on the list. final int maxResults = entityInfos.length; if ( maxResults == 0 ) { if ( traceEnabled ) { log.tracef( "No object to initialize", maxResults ); } return; } for ( EntityInfo entityInfo : entityInfos ) { Object o = ObjectLoaderHelper.load( entityInfo, objectInitializationContext.getSession() ); if ( o != null ) { EntityInfoLoadKey key = new EntityInfoLoadKey( entityInfo.getClazz(), entityInfo.getId() ); idToObjectMap.put( key, o ); } } if ( traceEnabled ) { log.tracef( "Initialized %d objects by lookup method.", maxResults ); } }
orm/src/main/java/org/hibernate/search/query/hibernate/impl/LookupObjectInitializer.java
satd-removal_data_46
TODO: Do we really need to display this twice? Not like there are any associated stats. @Override protected void statsDisplay() { if (canTreasureHunt) { player.sendMessage(LocaleLoader.getString("Fishing.Ability.Rank", new Object[] { lootTier })); } if (canMagicHunt) { player.sendMessage(LocaleLoader.getString("Fishing.Enchant.Chance", new Object[] { magicChance })); } if (canShake) { //TODO: Do we really need to display this twice? Not like there are any associated stats. if (skillValue < 150) { player.sendMessage(LocaleLoader.getString("Ability.Generic.Template.Lock", new Object[] { LocaleLoader.getString("Fishing.Ability.Locked.0") })); } else { player.sendMessage(LocaleLoader.getString("Fishing.Ability.Shake")); } } } @Override protected void statsDisplay() { if (canTreasureHunt) { player.sendMessage(LocaleLoader.getString("Fishing.Ability.Rank", new Object[] { lootTier })); } if (canMagicHunt) { player.sendMessage(LocaleLoader.getString("Fishing.Enchant.Chance", new Object[] { magicChance })); } if (canShake) { if (skillValue < 150) { player.sendMessage(LocaleLoader.getString("Ability.Generic.Template.Lock", new Object[] { LocaleLoader.getString("Fishing.Ability.Locked.0") })); } else { player.sendMessage(LocaleLoader.getString("Fishing.Ability.Shake", new Object[] { shakeChance })); } } }
src/main/java/com/gmail/nossr50/commands/skills/FishingCommand.java
satd-removal_data_47
TODO: TL this. @Override public void run(final Server server, final CommandSender sender, final String commandLabel, final String[] args) throws Exception { if (args.length < 2) { throw new NotEnoughArgumentsException(); } final ItemStack stack = ess.getItemDb().get(args[1]); final String itemname = stack.getType().toString().toLowerCase(Locale.ENGLISH).replace("_", ""); if (sender instanceof Player && (ess.getSettings().permissionBasedItemSpawn() ? (!ess.getUser(sender).isAuthorized("essentials.give.item-all") && !ess.getUser(sender).isAuthorized("essentials.give.item-" + itemname) && !ess.getUser(sender).isAuthorized("essentials.give.item-" + stack.getTypeId())) : (!ess.getUser(sender).isAuthorized("essentials.itemspawn.exempt") && !ess.getUser(sender).canSpawnItem(stack.getTypeId())))) { throw new Exception(_("cantSpawnItem", itemname)); } final User giveTo = getPlayer(server, args, 0); if (args.length > 3 && Util.isInt(args[2]) && Util.isInt(args[3])) { stack.setAmount(Integer.parseInt(args[2])); stack.setDurability(Short.parseShort(args[3])); } else if (args.length > 2 && Integer.parseInt(args[2]) > 0) { stack.setAmount(Integer.parseInt(args[2])); } else if (ess.getSettings().getDefaultStackSize() > 0) { stack.setAmount(ess.getSettings().getDefaultStackSize()); } else if (ess.getSettings().getOversizedStackSize() > 0 && giveTo.isAuthorized("essentials.oversizedstacks")) { stack.setAmount(ess.getSettings().getOversizedStackSize()); } if (args.length > 3) { for (int i = Util.isInt(args[3]) ? 4 : 3; i < args.length; i++) { final String[] split = args[i].split("[:+',;.]", 2); if (split.length < 1) { continue; } final Enchantment enchantment = Commandenchant.getEnchantment(split[0], sender instanceof Player ? ess.getUser(sender) : null); int level; if (split.length > 1) { level = Integer.parseInt(split[1]); } else { level = enchantment.getMaxLevel(); } stack.addEnchantment(enchantment, level); } } if (stack.getType() == Material.AIR) { throw new Exception(_("cantSpawnItem", "Air")); } //TODO: TL this. final String itemName = stack.getType().toString().toLowerCase(Locale.ENGLISH).replace('_', ' '); sender.sendMessage(ChatColor.BLUE + "Giving " + stack.getAmount() + " of " + itemName + " to " + giveTo.getDisplayName() + "."); if (giveTo.isAuthorized("essentials.oversizedstacks")) { InventoryWorkaround.addItem(giveTo.getInventory(), true, ess.getSettings().getOversizedStackSize(), stack); } else { InventoryWorkaround.addItem(giveTo.getInventory(), true, stack); } giveTo.updateInventory(); } @Override public void run(final Server server, final CommandSender sender, final String commandLabel, final String[] args) throws Exception { if (args.length < 2) { throw new NotEnoughArgumentsException(); } final ItemStack stack = ess.getItemDb().get(args[1]); final String itemname = stack.getType().toString().toLowerCase(Locale.ENGLISH).replace("_", ""); if (sender instanceof Player && (ess.getSettings().permissionBasedItemSpawn() ? (!ess.getUser(sender).isAuthorized("essentials.give.item-all") && !ess.getUser(sender).isAuthorized("essentials.give.item-" + itemname) && !ess.getUser(sender).isAuthorized("essentials.give.item-" + stack.getTypeId())) : (!ess.getUser(sender).isAuthorized("essentials.itemspawn.exempt") && !ess.getUser(sender).canSpawnItem(stack.getTypeId())))) { throw new Exception(_("cantSpawnItem", itemname)); } final User giveTo = getPlayer(server, args, 0); if (args.length > 3 && Util.isInt(args[2]) && Util.isInt(args[3])) { stack.setAmount(Integer.parseInt(args[2])); stack.setDurability(Short.parseShort(args[3])); } else if (args.length > 2 && Integer.parseInt(args[2]) > 0) { stack.setAmount(Integer.parseInt(args[2])); } else if (ess.getSettings().getDefaultStackSize() > 0) { stack.setAmount(ess.getSettings().getDefaultStackSize()); } else if (ess.getSettings().getOversizedStackSize() > 0 && giveTo.isAuthorized("essentials.oversizedstacks")) { stack.setAmount(ess.getSettings().getOversizedStackSize()); } if (args.length > 3) { for (int i = Util.isInt(args[3]) ? 4 : 3; i < args.length; i++) { final String[] split = args[i].split("[:+',;.]", 2); if (split.length < 1) { continue; } final Enchantment enchantment = Commandenchant.getEnchantment(split[0], sender instanceof Player ? ess.getUser(sender) : null); int level; if (split.length > 1) { level = Integer.parseInt(split[1]); } else { level = enchantment.getMaxLevel(); } stack.addEnchantment(enchantment, level); } } if (stack.getType() == Material.AIR) { throw new Exception(_("cantSpawnItem", "Air")); } final String itemName = stack.getType().toString().toLowerCase(Locale.ENGLISH).replace('_', ' '); sender.sendMessage(_("giveSpawn", stack.getAmount(), itemName, giveTo.getDisplayName())); if (giveTo.isAuthorized("essentials.oversizedstacks")) { InventoryWorkaround.addItem(giveTo.getInventory(), true, ess.getSettings().getOversizedStackSize(), stack); } else { InventoryWorkaround.addItem(giveTo.getInventory(), true, stack); } giveTo.updateInventory(); }
Essentials/src/com/earth2me/essentials/commands/Commandgive.java
satd-removal_data_48
todo - use config to construct a BinningGrid instance of the correct type @Override public void setConf(Configuration conf) { this.conf = conf; // todo - use config to construct a BinningGrid instance of the correct type int numRows = conf.getInt(L3Tool.CONFNAME_L3_NUM_ROWS, -1); binningGrid = new IsinBinningGrid(numRows); } @Override public void setConf(Configuration conf) { this.conf = conf; this.binningGrid = L3Config.getBinningGrid(conf); }
calvalus-experiments/src/main/java/com/bc/calvalus/b3/job/L3Partitioner.java
satd-removal_data_49
TODO: it's confusing that request has fields that get populated but not accepted as input (eg, groupId) public void execute() throws MojoExecutionException, MojoFailureException { Properties executionProperties = session.getExecutionProperties(); ArchetypeGenerationRequest request = new ArchetypeGenerationRequest() .setArchetypeGroupId( archetypeGroupId ) .setArchetypeArtifactId( archetypeArtifactId ) .setArchetypeVersion( archetypeVersion ) .setOutputDirectory( basedir.getAbsolutePath() ) .setLocalRepository( localRepository ) .setArchetypeRepository(archetypeRepository) .setRemoteArtifactRepositories(remoteArtifactRepositories); try { if( interactiveMode.booleanValue() ) { getLog().info( "Generating project in Interactive mode" ); } else { getLog().info( "Generating project in Batch mode" ); } selector.selectArchetype( request, interactiveMode, archetypeCatalog ); // TODO: it's confusing that request has fields that get populated but not accepted as input (eg, groupId) configurator.configureArchetype( request, interactiveMode, executionProperties ); ArchetypeGenerationResult generationResult = archetype.generateProjectFromArchetype( request ); if( generationResult.getCause() != null ) { throw new MojoFailureException( generationResult.getCause(), generationResult.getCause().getMessage(), generationResult.getCause().getMessage() ); } } catch ( MojoFailureException ex ) { throw ex; } catch ( Exception ex ) { throw new MojoFailureException( ex, ex.getMessage(), ex.getMessage() ); } String artifactId = request.getArtifactId(); String postArchetypeGenerationGoals = request.getArchetypeGoals(); if ( StringUtils.isEmpty( postArchetypeGenerationGoals ) ) { postArchetypeGenerationGoals = goals; } if ( StringUtils.isNotEmpty( postArchetypeGenerationGoals ) ) { invokePostArchetypeGenerationGoals( postArchetypeGenerationGoals, artifactId ); } } public void execute() throws MojoExecutionException, MojoFailureException { Properties executionProperties = session.getExecutionProperties(); ArchetypeGenerationRequest request = new ArchetypeGenerationRequest() .setArchetypeGroupId( archetypeGroupId ) .setArchetypeArtifactId( archetypeArtifactId ) .setArchetypeVersion( archetypeVersion ) .setOutputDirectory( basedir.getAbsolutePath() ) .setLocalRepository( localRepository ) .setArchetypeRepository(archetypeRepository) .setRemoteArtifactRepositories(remoteArtifactRepositories); try { if( interactiveMode.booleanValue() ) { getLog().info( "Generating project in Interactive mode" ); } else { getLog().info( "Generating project in Batch mode" ); } selector.selectArchetype( request, interactiveMode, archetypeCatalog ); configurator.configureArchetype( request, interactiveMode, executionProperties ); ArchetypeGenerationResult generationResult = archetype.generateProjectFromArchetype( request ); if( generationResult.getCause() != null ) { throw new MojoFailureException( generationResult.getCause(), generationResult.getCause().getMessage(), generationResult.getCause().getMessage() ); } } catch ( MojoFailureException ex ) { throw ex; } catch ( Exception ex ) { throw new MojoFailureException( ex.getMessage() ); } String artifactId = request.getArtifactId(); String postArchetypeGenerationGoals = request.getArchetypeGoals(); if ( StringUtils.isEmpty( postArchetypeGenerationGoals ) ) { postArchetypeGenerationGoals = goals; } if ( StringUtils.isNotEmpty( postArchetypeGenerationGoals ) ) { invokePostArchetypeGenerationGoals( postArchetypeGenerationGoals, artifactId ); } }
archetype-plugin/src/main/java/org/apache/maven/archetype/mojos/CreateProjectFromArchetypeMojo.java
satd-removal_data_50
@TODO DIRSERVER-1030 make this conditional based on the presence of the CascadeControl public void rename( NextInterceptor next, RenameOperationContext opContext ) throws NamingException { LdapDN name = opContext.getDn(); String newRdn = opContext.getNewRdn(); boolean deleteOldRn = opContext.getDelOldDn(); Attributes entry = nexus.lookup( new LookupOperationContext( name ) ); if ( name.startsWith( schemaBaseDN ) ) { // @TODO DIRSERVER-1030 make this conditional based on the presence of the CascadeControl schemaManager.modifyRn( name, newRdn, deleteOldRn, entry, false ); } next.rename( opContext ); } public void rename( NextInterceptor next, RenameOperationContext opContext ) throws NamingException { LdapDN name = opContext.getDn(); String newRdn = opContext.getNewRdn(); boolean deleteOldRn = opContext.getDelOldDn(); Attributes entry = nexus.lookup( new LookupOperationContext( name ) ); if ( name.startsWith( schemaBaseDN ) ) { schemaManager.modifyRn( name, newRdn, deleteOldRn, entry, opContext.hasRequestControl( CascadeControl.CONTROL_OID ) ); } next.rename( opContext ); }
core/src/main/java/org/apache/directory/server/core/schema/SchemaService.java
satd-removal_data_51
TODO: write better code public void scan(InetAddress address, ScanningResult result) { // create a scanning subject object, which will be used by fetchers // to cache common information ScanningSubject scanningSubject = new ScanningSubject(address); // populate results boolean continueScanning = true; int fetcherIndex = 0; for (Iterator i = fetcherRegistry.getRegisteredFetchers().iterator(); i.hasNext();) { Fetcher fetcher = (Fetcher) i.next(); if (continueScanning) { String value = fetcher.scan(scanningSubject); // TODO: write better code if (!Config.getGlobal().scanDeadHosts && fetcher instanceof PingFetcher) { continueScanning = value != null; // TODO: hardcoded [timeout] //value = value == null ? "[timeout]" : value; } result.setValue(fetcherIndex, value); } // TODO: display something in the else fetcherIndex++; } result.setType(scanningSubject.getResultType()); } public void scan(InetAddress address, ScanningResult result) { // create a scanning subject object, which will be used by fetchers // to cache common information ScanningSubject scanningSubject = new ScanningSubject(address); // populate results int fetcherIndex = 0; for (Iterator i = fetcherRegistry.getRegisteredFetchers().iterator(); i.hasNext();) { Fetcher fetcher = (Fetcher) i.next(); if (!scanningSubject.isScanningAborted()) { String value = fetcher.scan(scanningSubject); if (value == null) value = Labels.getInstance().getString("fetcher.value.nothing"); result.setValue(fetcherIndex, value); } else { result.setValue(fetcherIndex, Labels.getInstance().getString("fetcher.value.aborted")); } fetcherIndex++; } result.setType(scanningSubject.getResultType()); }
src/net/azib/ipscan/core/Scanner.java
satd-removal_data_52
FIXME: Should this also include the classifier? private void processNativeLibraries(final List<String> commands) throws MojoExecutionException { // Examine the native libraries directory for content. This will only be true if: // a) the directory exists // b) it contains at least 1 file final boolean hasValidNativeLibrariesDirectory = nativeLibrariesDirectory != null && nativeLibrariesDirectory.exists() && (nativeLibrariesDirectory.listFiles() != null && nativeLibrariesDirectory.listFiles().length > 0); // Retrieve any native dependencies or attached artifacts. This may include artifacts from the ndk-build MOJO final Set<Artifact> artifacts = getNativeDependenciesArtifacts(); final boolean hasValidBuildNativeLibrariesDirectory = ndkOutputDirectory.exists() && (ndkOutputDirectory.listFiles() != null && ndkOutputDirectory.listFiles().length > 0); if (artifacts.isEmpty() && hasValidNativeLibrariesDirectory && !hasValidBuildNativeLibrariesDirectory) { getLog().debug("No native library dependencies detected, will point directly to " + nativeLibrariesDirectory); // Point directly to the directory in this case - no need to copy files around commands.add("-nf"); commands.add(nativeLibrariesDirectory.getAbsolutePath()); } else if (!artifacts.isEmpty() || hasValidNativeLibrariesDirectory || hasValidBuildNativeLibrariesDirectory) { // In this case, we may have both .so files in it's normal location // as well as .so dependencies // Create the ${project.build.outputDirectory}/libs final File destinationDirectory = new File(outputDirectory.getAbsolutePath()); if (destinationDirectory.exists()) { // TODO: Clean it out? } else { if (!destinationDirectory.mkdir()) { getLog().debug("Could not create output directory " + outputDirectory); } } // Point directly to the newly created directory commands.add("-nf"); commands.add(destinationDirectory.getAbsolutePath()); // If we have a valid native libs, copy those files - these already come in the structure required if (hasValidNativeLibrariesDirectory) { copyLocalNativeLibraries(nativeLibrariesDirectory,destinationDirectory); } if (hasValidBuildNativeLibrariesDirectory) { copyLocalNativeLibraries(ndkOutputDirectory,destinationDirectory); } final File finalDestinationDirectory = new File(destinationDirectory, ndkArchitecture); if (!artifacts.isEmpty()) { getLog().debug("Copying native library dependencies to " + finalDestinationDirectory); if (finalDestinationDirectory.exists()) { } else { if (!finalDestinationDirectory.mkdir()) { getLog().debug("Could not create output directory " + outputDirectory); } } final DefaultArtifactsResolver artifactsResolver = new DefaultArtifactsResolver(this.artifactResolver, this.localRepository, this.remoteRepositories, true); final Set<Artifact> resolvedArtifacts = artifactsResolver.resolve(artifacts, getLog()); for (Artifact resolvedArtifact : resolvedArtifacts) { final File artifactFile = resolvedArtifact.getFile(); try { // FIXME: Should this also include the classifier? final File file = new File(finalDestinationDirectory, "lib" + resolvedArtifact.getArtifactId() + ".so"); getLog().debug("Copying native dependency " + resolvedArtifact.getArtifactId() + " (" + resolvedArtifact.getGroupId() + ") to " + file); org.apache.commons.io.FileUtils.copyFile(artifactFile, file); } catch (Exception e) { getLog().error("Could not copy native dependency: " + e.getMessage(), e); } } } } } private void processNativeLibraries(final List<String> commands) throws MojoExecutionException { // Examine the native libraries directory for content. This will only be true if: // a) the directory exists // b) it contains at least 1 file final boolean hasValidNativeLibrariesDirectory = nativeLibrariesDirectory != null && nativeLibrariesDirectory.exists() && (nativeLibrariesDirectory.listFiles() != null && nativeLibrariesDirectory.listFiles().length > 0); // Retrieve any native dependencies or attached artifacts. This may include artifacts from the ndk-build MOJO final Set<Artifact> artifacts = getNativeDependenciesArtifacts(); final boolean hasValidBuildNativeLibrariesDirectory = nativeLibrariesOutputDirectory.exists() && (nativeLibrariesOutputDirectory.listFiles() != null && nativeLibrariesOutputDirectory.listFiles().length > 0); if (artifacts.isEmpty() && hasValidNativeLibrariesDirectory && !hasValidBuildNativeLibrariesDirectory) { getLog().debug("No native library dependencies or attached artifacts detected, will point directly to " + nativeLibrariesDirectory); // Point directly to the directory in this case - no need to copy files around commands.add("-nf"); commands.add(nativeLibrariesDirectory.getAbsolutePath()); } else if (!artifacts.isEmpty() || hasValidNativeLibrariesDirectory) { // In this case, we may have both .so files in it's normal location // as well as .so dependencies // Create the ${project.build.outputDirectory}/libs File destinationDirectory = new File(nativeLibrariesOutputDirectory.getAbsolutePath()); destinationDirectory.mkdirs(); // Point directly to the directory commands.add("-nf"); commands.add(destinationDirectory.getAbsolutePath()); // If we have a valid native libs, copy those files - these already come in the structure required if (hasValidNativeLibrariesDirectory) { copyLocalNativeLibraries(nativeLibrariesDirectory,destinationDirectory); } if (hasValidBuildNativeLibrariesDirectory) { copyLocalNativeLibraries(nativeLibrariesOutputDirectory,destinationDirectory); } if (!artifacts.isEmpty()) { final DefaultArtifactsResolver artifactsResolver = new DefaultArtifactsResolver(this.artifactResolver, this.localRepository, this.remoteRepositories, true); final Set<Artifact> resolvedArtifacts = artifactsResolver.resolve(artifacts, getLog()); for (Artifact resolvedArtifact : resolvedArtifacts) { final File artifactFile = resolvedArtifact.getFile(); try { final String artifactId = resolvedArtifact.getArtifactId(); final String filename = artifactId.startsWith("lib") ? artifactId + ".so" : "lib" + artifactId + ".so"; final File finalDestinationDirectory = getFinalDestinationDirectoryFor(resolvedArtifact, destinationDirectory); final File file = new File(finalDestinationDirectory, filename); getLog().debug("Copying native dependency " + artifactId + " (" + resolvedArtifact.getGroupId() + ") to " + file ); org.apache.commons.io.FileUtils.copyFile(artifactFile, file); } catch (Exception e) { throw new MojoExecutionException("Could not copy native dependency.", e); } } } } }
src/main/java/com/jayway/maven/plugins/android/phase09package/ApkMojo.java
satd-removal_data_53
TODO: check if in reactor @Override public void execute() throws MojoExecutionException, MojoFailureException { JangarooApps jangarooApps = createJangarooApps(project); Map<String, List<File>> appNamesToDir = new HashMap<>(); for (JangarooApp jangarooApp : jangarooApps.apps) { String senchaAppName = SenchaUtils.getSenchaPackageName(jangarooApp.mavenProject); List<File> appReactorDirs = new ArrayList<>(); do { // TODO: check if in reactor appReactorDirs.add(new File(jangarooApp.mavenProject.getBuild().getDirectory() + SenchaUtils.APP_TARGET_DIRECTORY)); jangarooApp = jangarooApp instanceof JangarooAppOverlay ? ((JangarooAppOverlay) jangarooApp).baseApp : null; } while (jangarooApp != null); appNamesToDir.put(senchaAppName, appReactorDirs); } Dependency rootApp = getRootApp(); String rootAppName = rootApp == null ? null : SenchaUtils.getSenchaPackageName(rootApp.getGroupId(), rootApp.getArtifactId()); FileHelper.createAppsJar(session, archiver, artifactHandlerManager, null, null, appNamesToDir, rootAppName); } @Override public void execute() throws MojoExecutionException, MojoFailureException { JangarooApps jangarooApps = createJangarooApps(project); Map<String, List<File>> appNamesToDirsOrJars = new HashMap<>(); for (JangarooApp jangarooApp : jangarooApps.apps) { String senchaAppName = SenchaUtils.getSenchaPackageName(jangarooApp.mavenProject); List<File> appReactorDirs = new ArrayList<>(); do { appReactorDirs.add(getAppDirOrJar(jangarooApp.mavenProject)); jangarooApp = jangarooApp instanceof JangarooAppOverlay ? ((JangarooAppOverlay) jangarooApp).baseApp : null; } while (jangarooApp != null); appNamesToDirsOrJars.put(senchaAppName, appReactorDirs); } Dependency rootApp = getRootApp(); String rootAppName = rootApp == null ? null : SenchaUtils.getSenchaPackageName(rootApp.getGroupId(), rootApp.getArtifactId()); FileHelper.createAppsJar(session, archiver, artifactHandlerManager, null, null, appNamesToDirsOrJars, rootAppName); }
jangaroo-maven/jangaroo-maven-plugin/src/main/java/net/jangaroo/jooc/mvnplugin/PackageAppsMojo.java
satd-removal_data_54
TODO fix this @Test public void getObjectInstance() throws Exception { Reference resource = new Reference("CassandraClientFactory"); resource.add(new StringRefAddr("url", cassandraUrl)); resource.add(new StringRefAddr("port", Integer.toString(cassandraPort))); Name jndiName = mock(Name.class); Context context = new InitialContext(); Hashtable<String, String> environment = new Hashtable<String, String>(); CassandraClientJndiResourcePool cassandraClientJNDIResourcePool = (CassandraClientJndiResourcePool) factory.getObjectInstance(resource, jndiName, context, environment); //CassandraClient cassandraClient = (CassandraClient) cassandraClientJNDIResourcePool.borrowObject(); // TODO fix this //assertNotNull(cassandraClient); //assertEquals(cassandraUrl, cassandraClient.getCassandraHost().getHost()); //assertEquals(cassandraPort, cassandraClient.getCassandraHost().getPort()); } @Test public void getObjectInstance() throws Exception { Reference resource = new Reference("CassandraClientFactory"); resource.add(new StringRefAddr("hosts", cassandraUrl)); resource.add(new StringRefAddr("clusterName", clusterName)); resource.add(new StringRefAddr("keyspace", "Keyspace1")); resource.add(new StringRefAddr("autoDiscoverHosts", "true")); Name jndiName = mock(Name.class); Context context = new InitialContext(); Hashtable<String, String> environment = new Hashtable<String, String>(); Keyspace keyspace = (Keyspace) factory.getObjectInstance(resource, jndiName, context, environment); assertNotNull(keyspace); assertEquals("Keyspace1",keyspace.getKeyspaceName()); }
core/src/test/java/me/prettyprint/cassandra/jndi/CassandraClientJndiResourceFactoryTest.java
satd-removal_data_55
TODO hosting.com throws 400 when we try to delete a vApp @Test(enabled = true, dependsOnMethods = "testCompareSizes") public void testCreateTwoNodesWithRunScript() throws Exception { try { client.destroyNodesMatching(withTag(tag)); } catch (HttpResponseException e) { // TODO hosting.com throws 400 when we try to delete a vApp } catch (NoSuchElementException e) { } refreshTemplate(); try { nodes = newTreeSet(client.runNodesWithTag(tag, 2, template)); } catch (RunNodesException e) { nodes = newTreeSet(concat(e.getSuccessfulNodes(), e.getNodeErrors().keySet())); throw e; } assertEquals(nodes.size(), 2); checkNodes(nodes, tag); NodeMetadata node1 = nodes.first(); NodeMetadata node2 = nodes.last(); // credentials aren't always the same // assertEquals(node1.getCredentials(), node2.getCredentials()); assertLocationSameOrChild(node1.getLocation(), template.getLocation()); assertLocationSameOrChild(node2.getLocation(), template.getLocation()); checkImageIdMatchesTemplate(node1); checkImageIdMatchesTemplate(node2); checkOsMatchesTemplate(node1); checkOsMatchesTemplate(node2); } @Test(enabled = true, dependsOnMethods = "testCompareSizes") public void testCreateTwoNodesWithRunScript() throws Exception { try { client.destroyNodesMatching(withTag(tag)); } catch (NoSuchElementException e) { } refreshTemplate(); try { nodes = newTreeSet(client.runNodesWithTag(tag, 2, template)); } catch (RunNodesException e) { nodes = newTreeSet(concat(e.getSuccessfulNodes(), e.getNodeErrors().keySet())); throw e; } assertEquals(nodes.size(), 2); checkNodes(nodes, tag); NodeMetadata node1 = nodes.first(); NodeMetadata node2 = nodes.last(); // credentials aren't always the same // assertEquals(node1.getCredentials(), node2.getCredentials()); assertLocationSameOrChild(node1.getLocation(), template.getLocation()); assertLocationSameOrChild(node2.getLocation(), template.getLocation()); checkImageIdMatchesTemplate(node1); checkImageIdMatchesTemplate(node2); checkOsMatchesTemplate(node1); checkOsMatchesTemplate(node2); }
compute/src/test/java/org/jclouds/compute/BaseComputeServiceLiveTest.java
satd-removal_data_56
TODO merge SMS into secondary action private void populateContactAndAboutCard() { Trace.beginSection("bind contact card"); final List<Entry> contactCardEntries = new ArrayList<>(); final List<Entry> aboutCardEntries = new ArrayList<>(); int topContactIndex = 0; for (int i = 0; i < mDataItemsList.size(); ++i) { final List<DataItem> dataItemsByMimeType = mDataItemsList.get(i); final DataItem topDataItem = dataItemsByMimeType.get(0); if (ABOUT_CARD_MIMETYPES.contains(topDataItem.getMimeType())) { aboutCardEntries.addAll(dataItemsToEntries(mDataItemsList.get(i))); } else { // Add most used to the top of the contact card final Entry topEntry = dataItemToEntry(topDataItem); if (topEntry != null) { contactCardEntries.add(topContactIndex++, dataItemToEntry(topDataItem)); } // TODO merge SMS into secondary action if (topDataItem instanceof PhoneDataItem) { final PhoneDataItem phone = (PhoneDataItem) topDataItem; Intent smsIntent = null; if (mSmsComponent != null) { smsIntent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts(CallUtil.SCHEME_SMSTO, phone.getNumber(), null)); smsIntent.setComponent(mSmsComponent); } final int dataId = phone.getId() > Integer.MAX_VALUE ? -1 : (int) phone.getId(); contactCardEntries.add(topContactIndex++, new Entry(dataId, getResources().getDrawable(R.drawable.ic_message_24dp), getResources().getString(R.string.send_message), /* subHeader = */ null, /* text = */ phone.buildDataString( this, topDataItem.getDataKind()), smsIntent, /* isEditable = */ false)); } // Add the rest of the entries to the bottom of the card if (dataItemsByMimeType.size() > 1) { contactCardEntries.addAll(dataItemsToEntries( dataItemsByMimeType.subList(1, dataItemsByMimeType.size()))); } } } if (contactCardEntries.size() > 0) { mContactCard.initialize(contactCardEntries, /* numInitialVisibleEntries = */ MIN_NUM_CONTACT_ENTRIES_SHOWN, /* isExpanded = */ false, mExpandingEntryCardViewListener); mContactCard.setVisibility(View.VISIBLE); } else { mContactCard.setVisibility(View.GONE); } Trace.endSection(); Trace.beginSection("bind about card"); mAboutCard.initialize(aboutCardEntries, /* numInitialVisibleEntries = */ 1, /* isExpanded = */ true, mExpandingEntryCardViewListener); Trace.endSection(); } private void populateContactAndAboutCard() { Trace.beginSection("bind contact card"); final List<List<Entry>> contactCardEntries = new ArrayList<>(); final List<List<Entry>> aboutCardEntries = new ArrayList<>(); for (int i = 0; i < mDataItemsList.size(); ++i) { final List<DataItem> dataItemsByMimeType = mDataItemsList.get(i); final DataItem topDataItem = dataItemsByMimeType.get(0); if (ABOUT_CARD_MIMETYPES.contains(topDataItem.getMimeType())) { List<Entry> aboutEntries = dataItemsToEntries(mDataItemsList.get(i)); if (aboutEntries.size() > 0) { aboutCardEntries.add(aboutEntries); } } else { List<Entry> contactEntries = dataItemsToEntries(mDataItemsList.get(i)); if (contactEntries.size() > 0) { contactCardEntries.add(contactEntries); } } } if (contactCardEntries.size() > 0) { mContactCard.initialize(contactCardEntries, /* numInitialVisibleEntries = */ MIN_NUM_CONTACT_ENTRIES_SHOWN, /* isExpanded = */ false, mExpandingEntryCardViewListener); mContactCard.setVisibility(View.VISIBLE); } else { mContactCard.setVisibility(View.GONE); } Trace.endSection(); Trace.beginSection("bind about card"); mAboutCard.initialize(aboutCardEntries, /* numInitialVisibleEntries = */ 1, /* isExpanded = */ true, mExpandingEntryCardViewListener); Trace.endSection(); }
src/com/android/contacts/quickcontact/QuickContactActivity.java
satd-removal_data_57
TODO check possible weld bug @Test @SpecAssertions({ @SpecAssertion(section = "5.6", id = "e"), @SpecAssertion(section = "5.6.3", id = "b") }) @SuppressWarnings("serial") public void testNewBean() { // TODO check possible weld bug // Instance<List<String>> instance = getInstanceByType(ObtainsNewInstanceBean.class).getStrings(); // assert instance.select(new TypeLiteral<ArrayList<String>>(){}).get() instanceof ArrayList<?>; String instance = getInstanceByType(ObtainsNewInstanceBean.class).getString(); assert instance != null && instance instanceof String; getInstanceByType(ObtainsNewInstanceBean.class).getMap(); } @Test @SpecAssertions({ @SpecAssertion(section = "5.6", id = "e"), @SpecAssertion(section = "5.6.3", id = "b") }) public void testNewBean() { Instance<String> string = getInstanceByType(ObtainsNewInstanceBean.class).getString(); assert !string.isAmbiguous(); assert !string.isUnsatisfied(); assert string.get() != null; assert string.get() instanceof String; Instance<Map<String, String>> map = getInstanceByType(ObtainsNewInstanceBean.class).getMap(); assert !map.isAmbiguous(); assert !map.isUnsatisfied(); Map<String, String> instance = map.get(); assert instance != null; assert instance instanceof HashMap<?, ?>; }
impl/src/main/java/org/jboss/cdi/tck/tests/lookup/dynamic/DynamicLookupTest.java
satd-removal_data_58
todo: alias sub-index public synchronized void initializeCommands() { // ** Load topics from highest to lowest priority order ** // todo: ignore specified plugins Set<String> ignoredPlugins = Collections.emptySet(); // Don't load any automatic help topics if All is ignored if (ignoredPlugins.contains("All")) { return; } // Initialize help topics from the server's command map outer: for (Command command : server.getCommandMap().getCommands()) { if (commandInIgnoredPlugin(command, ignoredPlugins)) { continue; } // Register a topic for (Class<?> c : topicFactoryMap.keySet()) { if (c.isAssignableFrom(command.getClass())) { HelpTopic t = topicFactoryMap.get(c).createTopic(command); if (t != null) addTopic(t); continue outer; } if (command instanceof PluginCommand && c.isAssignableFrom(((PluginCommand) command).getExecutor().getClass())) { HelpTopic t = topicFactoryMap.get(c).createTopic(command); if (t != null) addTopic(t); continue outer; } } addTopic(new GenericCommandHelpTopic(command)); } // todo: help on alias topics // todo: alias sub-index // Initialize plugin-level sub-topics Map<String, Set<HelpTopic>> pluginIndexes = new HashMap<>(); fillPluginIndexes(pluginIndexes, server.getCommandMap().getCommands()); for (Map.Entry<String, Set<HelpTopic>> entry : pluginIndexes.entrySet()) { addTopic(new IndexHelpTopic(entry.getKey(), "All commands for " + entry.getKey(), null, entry.getValue(), "Below is a list of all " + entry.getKey() + " commands:")); } // todo: amended topics from help.yml } public synchronized void initializeCommands() { // Don't load any automatic help topics if All is ignored if (ignoredPlugins.contains("All")) { return; } Collection<Command> commands = server.getCommandMap().getCommands(); // Initialize help topics from the server's command map outer: for (Command command : commands) { if (commandInIgnoredPlugin(command)) { continue; } // Register a topic for (Class<?> c : topicFactoryMap.keySet()) { if (c.isAssignableFrom(command.getClass())) { HelpTopic t = topicFactoryMap.get(c).createTopic(command); if (t != null) addCommandTopic(t); continue outer; } if (command instanceof PluginCommand && c.isAssignableFrom(((PluginCommand) command).getExecutor().getClass())) { HelpTopic t = topicFactoryMap.get(c).createTopic(command); if (t != null) addCommandTopic(t); continue outer; } } addCommandTopic(new GenericCommandHelpTopic(command)); } // Alias topics for commands Set<HelpTopic> aliases = new TreeSet<>(TOPIC_COMPARE); for (Command command : commands) { if (commandInIgnoredPlugin(command)) { continue; } HelpTopic original = getHelpTopic("/" + command.getLabel()); if (original != null) { for (String alias : command.getAliases()) { HelpTopic aliasTopic = new AliasTopic("/" + alias, original); if (!helpTopics.containsKey(aliasTopic.getName())) { aliases.add(aliasTopic); addPrivateTopic(aliasTopic); } } } } // Aliases index topic if (!aliases.isEmpty()) { addTopic(new IndexHelpTopic("Aliases", "Lists command aliases", null, aliases, null)); } // Initialize plugin-level sub-topics Map<String, Set<HelpTopic>> pluginIndexes = new HashMap<>(); for (Command command : commands) { String pluginName = getCommandPluginName(command); if (pluginName != null) { HelpTopic topic = getHelpTopic("/" + command.getLabel()); if (topic != null) { if (!pluginIndexes.containsKey(pluginName)) { pluginIndexes.put(pluginName, new TreeSet<>(TOPIC_COMPARE)); } pluginIndexes.get(pluginName).add(topic); } } } for (Map.Entry<String, Set<HelpTopic>> entry : pluginIndexes.entrySet()) { String key = entry.getKey(); addTopic(new IndexHelpTopic(key, "All commands for " + key, null, entry.getValue(), "Below is a list of all " + key + " commands:")); } }
src/main/java/net/glowstone/util/GlowHelpMap.java
satd-removal_data_59
TODO srowen says cluster is not used? public void testFuzzyKMeansMapper() throws Exception { List<Vector> points = TestKmeansClustering .getPoints(TestKmeansClustering.reference); DistanceMeasure measure = new EuclideanDistanceMeasure(); SoftCluster.config(measure, 0.001); for (int k = 0; k < points.size(); k++) { System.out.println("testKFuzzyKMeansMRJob k= " + k); // pick k initial cluster centers at random List<SoftCluster> clusterList = new ArrayList<SoftCluster>(); for (int i = 0; i < k + 1; i++) { Vector vec = tweakValue(points.get(i)); SoftCluster cluster = new SoftCluster(vec); cluster.addPoint(cluster.getCenter(), 1); clusterList.add(cluster); } // run mapper FuzzyKMeansMapper mapper = new FuzzyKMeansMapper(); mapper.config(clusterList); DummyOutputCollector<Text, Text> mapCollector = new DummyOutputCollector<Text, Text>(); for (Vector point : points) { mapper.map(new Text(), new Text(point.asFormatString()), mapCollector, null); } // now verify mapper output assertEquals("Mapper Keys", k + 1, mapCollector.getData().size()); Map<String, Double> pointTotalProbMap = new HashMap<String, Double>(); for (String key : mapCollector.getKeys()) { //SoftCluster cluster = SoftCluster.decodeCluster(key); // TODO srowen says cluster is not used? List<Text> values = mapCollector.getValue(key); for (Text value : values) { String pointInfo = value.toString(); double pointProb = Double.parseDouble(pointInfo.substring(0, pointInfo.indexOf(":"))); String encodedVector = pointInfo .substring(pointInfo.indexOf(":") + 1); Double val = pointTotalProbMap.get(encodedVector); double probVal = 0.0; if (val != null) { probVal = val; } pointTotalProbMap.put(encodedVector, probVal + pointProb); } } for (Map.Entry<String, Double> entry : pointTotalProbMap.entrySet()) { String key = entry.getKey(); double value = round(entry.getValue(), 1); assertEquals("total Prob for Point:" + key, 1.0, value); } } } public void testFuzzyKMeansMapper() throws Exception { List<Vector> points = TestKmeansClustering .getPoints(TestKmeansClustering.reference); DistanceMeasure measure = new EuclideanDistanceMeasure(); SoftCluster.config(measure, 0.001); for (int k = 0; k < points.size(); k++) { System.out.println("testKFuzzyKMeansMRJob k= " + k); // pick k initial cluster centers at random List<SoftCluster> clusterList = new ArrayList<SoftCluster>(); for (int i = 0; i < k + 1; i++) { Vector vec = tweakValue(points.get(i)); SoftCluster cluster = new SoftCluster(vec); cluster.addPoint(cluster.getCenter(), 1); clusterList.add(cluster); } // run mapper FuzzyKMeansMapper mapper = new FuzzyKMeansMapper(); mapper.config(clusterList); DummyOutputCollector<Text, Text> mapCollector = new DummyOutputCollector<Text, Text>(); for (Vector point : points) { mapper.map(new Text(), new Text(point.asFormatString()), mapCollector, null); } // now verify mapper output assertEquals("Mapper Keys", k + 1, mapCollector.getData().size()); Map<String, Double> pointTotalProbMap = new HashMap<String, Double>(); for (String key : mapCollector.getKeys()) { //SoftCluster cluster = SoftCluster.decodeCluster(key); List<Text> values = mapCollector.getValue(key); for (Text value : values) { String pointInfo = value.toString(); double pointProb = Double.parseDouble(pointInfo.substring(0, pointInfo.indexOf(':'))); String encodedVector = pointInfo .substring(pointInfo.indexOf(':') + 1); Double val = pointTotalProbMap.get(encodedVector); double probVal = 0.0; if (val != null) { probVal = val; } pointTotalProbMap.put(encodedVector, probVal + pointProb); } } for (Map.Entry<String, Double> entry : pointTotalProbMap.entrySet()) { String key = entry.getKey(); double value = round(entry.getValue(), 1); assertEquals("total Prob for Point:" + key, 1.0, value); } } }
core/src/test/java/org/apache/mahout/clustering/fuzzykmeans/TestFuzzyKmeansClustering.java
satd-removal_data_60
TODO: get previous document private void saveDocument(String comment) throws SAXException { try { XWikiContext context = getXWikiContext(); XWikiDocument document = getDocument(); XWikiDocument dbDocument = getDatabaseDocument(); // TODO: get previous document // TODO: diff previous and new document // TODO: if there is differences // TODO: ..apply diff to db document } catch (Exception e) { throw new SAXException("Failed to save document", e); } this.needSave = false; } private void saveDocument(String comment) throws SAXException { try { XWikiContext context = getXWikiContext(); XWikiDocument document = getDocument(); XWikiDocument dbDocument = getDatabaseDocument().clone(); XWikiDocument previousDocument = getPreviousDocument(); if (previousDocument != null) { if (merge(previousDocument, document, dbDocument).isModified()) { context.getWiki().saveDocument(document, comment, context); } } else { if (!dbDocument.isNew()) { document.setVersion(dbDocument.getVersion()); } context.getWiki().saveDocument(document, comment, context); } } catch (Exception e) { throw new SAXException("Failed to save document", e); } }
xwiki-commons-core/xwiki-commons-extension/xwiki-platform-extension-handlers/xwiki-platform-extension-handler-xar/src/main/java/org/xwiki/extension/xar/internal/handler/packager/xml/DocumentImporterHandler.java
satd-removal_data_61
TODO: use return value to determine container exit status @Override protected void runInternal() { // TODO: use return value to determine container exit status ContainerHandler containerHandler = beanFactory.getBean(ContainerHandler.class); try { Object result = containerHandler.handle(this); log.info("Result from container handle: " + result); } catch (Exception e) { log.error("Error handling container", e); } } @Override protected void runInternal() { Exception runtimeException = null; Object result = null; try { ContainerHandler containerHandler = beanFactory.getBean(ContainerHandler.class); result = containerHandler.handle(this); } catch (Exception e) { runtimeException = e; log.error("Error handling container", e); } log.info("Container state based on result=[" + result + "] runtimeException=[" + runtimeException + "]"); if (runtimeException != null) { notifyContainerState(ContainerState.FAILED, 1); } else if (result != null && result instanceof Integer) { int val = ((Integer)result).intValue(); if (val < 0) { notifyContainerState(ContainerState.FAILED, val); } else { notifyContainerState(ContainerState.COMPLETED, val); } } else if (result != null && result instanceof Boolean) { boolean val = ((Boolean)result).booleanValue(); if (val) { notifyContainerState(ContainerState.COMPLETED, 0); } else { notifyContainerState(ContainerState.FAILED, -1); } } else { notifyCompleted(); } }
spring-yarn/spring-yarn-core/src/main/java/org/springframework/yarn/container/DefaultYarnContainer.java
satd-removal_data_62
TODO switch to DOM4J for simplicity and consistency public void transformPom(MavenCoordinates coreCoordinates) throws PomTransformationException{ File pom = new File(rootDir.getAbsolutePath()+"/"+pomFileName); File backupedPom = new File(rootDir.getAbsolutePath()+"/"+pomFileName+".backup"); try { FileUtils.rename(pom, backupedPom); Source xmlSource = new StreamSource(backupedPom); // TODO switch to DOM4J for simplicity and consistency Source xsltSource = new StreamSource(new ClassPathResource("mavenParentReplacer.xsl").getInputStream()); Result result = new StreamResult(pom); TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(xsltSource); transformer.setParameter("parentArtifactId", coreCoordinates.artifactId); transformer.setParameter("parentGroupId", coreCoordinates.groupId); transformer.setParameter("parentVersion", coreCoordinates.version); transformer.transform(xmlSource, result); } catch (Exception e) { throw new PomTransformationException("Error while transforming pom : "+pom.getAbsolutePath(), e); } } public void transformPom(MavenCoordinates coreCoordinates) throws PomTransformationException{ File pom = new File(rootDir.getAbsolutePath()+"/"+pomFileName); File backupedPom = new File(rootDir.getAbsolutePath()+"/"+pomFileName+".backup"); try { FileUtils.rename(pom, backupedPom); Document doc; try { doc = new SAXReader().read(backupedPom); } catch (DocumentException x) { throw new IOException(x); } Element parent = doc.getRootElement().element("parent"); if (parent != null) { Element groupIdElem = parent.element(GROUP_ID_ELEMENT); if (groupIdElem != null) { groupIdElem.setText(coreCoordinates.groupId); } Element artifactIdElem = parent.element(ARTIFACT_ID_ELEMENT); if (artifactIdElem != null) { artifactIdElem.setText(coreCoordinates.artifactId); } Element versionIdElem = parent.element(VERSION_ELEMENT); if (versionIdElem != null) { versionIdElem.setText(coreCoordinates.version); } } writeDocument(pom, doc); } catch (Exception e) { throw new PomTransformationException("Error while transforming pom : "+pom.getAbsolutePath(), e); } }
plugins-compat-tester/src/main/java/org/jenkins/tools/test/model/MavenPom.java
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
1