id
stringlengths
7
14
text
stringlengths
1
106k
1109529_0
String nowTimeImageUrl() throws Exception { String time = DateFormatUtils.format(new Date(), "hhmm"); DefaultHttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = buildDefaultHttpMessage(new HttpGet("http://www.bijint.com/cache/"+ time + ".html")); httpget.setHeader("Referer", "http://www.bijint.com/jp/"); HttpResponse response = httpclient.execute(httpget); if (response.getStatusLine().getStatusCode() != 200) { getLog().error("美人時計忙しいらしいよ。なんか200じゃないの返してくる。"); return null; } String result = IOUtils.toString(response.getEntity().getContent(), "UTF-8"); httpclient.getConnectionManager().shutdown(); return "http://www.bijint.com" + getImagePath(result); }
1109529_1
String getImagePath(String str) throws Exception { DOMParser parser = new DOMParser(); parser.parse(new InputSource(new StringReader(str))); NodeList nodeList = XPathAPI.selectNodeList(parser.getDocument(), "/HTML/BODY/TABLE/TR/TH[1]/IMG"); String path = null; for (int i = 0; i < nodeList.getLength(); i++) { Element element = (Element) nodeList.item(i); path = element.getAttribute("src"); } return path; }
1109529_2
BufferedImage getFittingImage(String url) throws Exception { // 画像を縮小 DefaultHttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = buildDefaultHttpMessage(new HttpGet(url)); httpget.setHeader("Referer", "http://www.bijint.com/jp/"); HttpResponse response = httpclient.execute(httpget); BufferedImage image = ImageIO.read(response.getEntity().getContent()); httpclient.getConnectionManager().shutdown(); int width = image.getWidth() / 10 * 4; int height = image.getHeight() / 10 * 4; BufferedImage resizedImage = null; resizedImage = new BufferedImage(width, height, image.getType()); resizedImage.getGraphics().drawImage( image.getScaledInstance(width, height, Image.SCALE_AREA_AVERAGING), 0, 0, width, height, null); return resizedImage; }
1109529_3
public void execute() throws MojoExecutionException { try { String imgUrl = nowTimeImageUrl(); if (imgUrl == null) { return; } // 表示 getLog().info("\n" + getAsciiArt(getFittingImage(imgUrl))); } catch (Exception e) { e.printStackTrace(); throw new MojoExecutionException("なんかエラー", e); } }
1109529_4
public void makeXlsxFile() throws Exception { String fileName = "test.xlsx"; FileOutputStream fileOut = new FileOutputStream(fileName); Workbook wb = new XSSFWorkbook(); Sheet sheet = wb.createSheet("test"); // シート作成 Row row = sheet.createRow((short)0); Cell cell = row.createCell(0); cell.setCellValue("日本語は通る?"); wb.write(fileOut); fileOut.close(); }
1109529_5
public void dbSelect() throws Exception { Class.forName("org.postgresql.Driver"); String url = "jdbc:postgresql://localhost:5432/np"; Connection con = DriverManager.getConnection(url, "np", "npnpnp"); Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery(getPlainSQL()); / PreparedStatement stmt = con.prepareStatement(getSql()); / Long[] val = getValue(); / for (int i = 0; i < COUNT; i++) { / stmt.setLong(i + 1, val[i]); / } / ResultSet rs = stmt.executeQuery(); / rs.close(); stmt.close(); con.close(); }
1109529_6
public void insertData() { Connection con = null; Statement stmt = null; try { con = ds.getConnection(); stmt = con.createStatement(); int count = sampleLogic.plus(1, 5); for (int i = 0; i < count; i++) { stmt.executeUpdate("INSERT INTO EMP (id, name) values (" + i + ", 'test')"); } } catch (Exception e) { throw new RuntimeException(e); } finally { try { if (stmt != null) { stmt.close(); } if (con != null) { con.close(); } } catch (Exception ex) { throw new RuntimeException(ex); } } }
1109529_7
public List<EmpDto> getEmpAllRecord() { Connection con = null; Statement stmt = null; ResultSet rs = null; try { con = ds.getConnection(); stmt = con.createStatement(); rs = stmt.executeQuery("SELECT * FROM EMP"); List<EmpDto> list = new ArrayList<EmpDto>(); while (rs.next()) { EmpDto dto = new EmpDto(); dto.id = rs.getInt(1); dto.name = rs.getString(2); list.add(dto); } return list; } catch (Exception e) { throw new RuntimeException(e); } finally { try { if (rs != null) { rs.close(); } if (stmt != null) { stmt.close(); } if (con != null) { con.close(); } } catch (Exception ex) { throw new RuntimeException(ex); } } }
1110934_0
public ViewMapVO getViewMapForView(String register, String dataType, long version) throws SQLException { String sql = "SELECT idSKRSViewMapping,tableName,createdDate FROM SKRSViewMapping WHERE register=? AND " + "datatype=? AND version=?"; ArrayListHandler handler = new ArrayListHandler(); QueryRunner qr = new QueryRunner(); Connection conn = null; try { conn = connectionProvider.get(); List<Object[]> viewMaps = qr.query(conn, sql, handler, register, dataType, version); if (viewMaps.size() < 1) { throw new DynamicViewException("View not found for " + register + "/" + dataType + "/" + version); } else if (viewMaps.size() > 1) { throw new DynamicViewException("Multiple views found for " + register + "/" + dataType + "/" + version); } Long id = (Long) viewMaps.get(0)[0]; String tableName = (String) viewMaps.get(0)[1]; Timestamp createTime = (Timestamp) viewMaps.get(0)[2]; List<ColumnMapVO> columnMaps = getColumnMapsForView(conn, id); ViewMapVO viewMap = new ViewMapVO(); viewMap.setCreatedDate(createTime); viewMap.setDatatype(dataType); viewMap.setRegister(register); viewMap.setTableName(tableName); viewMap.setVersion(version); for (ColumnMapVO columnMap : columnMaps) { viewMap.addColumn(columnMap); } return viewMap; } finally { DbUtils.close(conn); } }
1110934_1
public List<String> extractCprNumbersWithoutHeaders(String soapResponse) throws CprAbbsException { try { Document document = createDomTree(soapResponse); NodeList nodeList = extractChangedCprsNodes(document); return convertNodeListToCprStrings(nodeList); } catch (Exception e) { throw new CprAbbsException(e); } }
1110934_2
public List<String> extractCprNumbers(String soapResponse) throws CprAbbsException { int start = soapResponse.indexOf("<?xml"); if(start == -1) { throw new CprAbbsException("Invalid message body on call to CPR Abbs"); } String soapResponseWithoutHeader = soapResponse.substring(start); return extractCprNumbersWithoutHeaders(soapResponseWithoutHeader); }
1116314_0
public void setPhrase( String phrase ) throws IllegalArgumentException { if( phrase == null ) { throw new IllegalArgumentException( "Phrase may not be null " ); } this.phrase = phrase; }
1116314_1
public void setName( String name ) throws IllegalArgumentException { if( name == null ) { throw new IllegalArgumentException( "Name may not be null " ); } this.name = name; }
1116314_2
@Override public int makeBooking( Cargo cargo, Voyage voyage ) { int ok = next.makeBooking( cargo, voyage ); if( ok < 0 ) { return ok; } Property<Integer> gen = generator.sequence(); ok = gen.get(); generator.sequence().set( ok + 1 ); return ok; }
1116314_3
@Override public int makeBooking( Cargo cargo, Voyage voyage ) { int ok = next.makeBooking( cargo, voyage ); if( ok < 0 ) { return ok; } Property<Integer> gen = generator.sequence(); ok = gen.get(); generator.sequence().set( ok + 1 ); return ok; }
1116314_4
@Override public <T> QueryBuilder<T> newQueryBuilder( final Class<T> resultType ) { NotQueryableException.throwIfNotQueryable( resultType ); final ServiceReference<EntityFinder> serviceReference; try { serviceReference = finder.findService( EntityFinder.class ); return new QueryBuilderImpl<>( serviceReference.get(), resultType, null ); } catch( NoSuchServiceTypeException e ) { return new QueryBuilderImpl<>( null, resultType, null ); } }
1116314_5
@Override public <T> QueryBuilder<T> newQueryBuilder( final Class<T> resultType ) { NotQueryableException.throwIfNotQueryable( resultType ); final ServiceReference<EntityFinder> serviceReference; try { serviceReference = finder.findService( EntityFinder.class ); return new QueryBuilderImpl<>( serviceReference.get(), resultType, null ); } catch( NoSuchServiceTypeException e ) { return new QueryBuilderImpl<>( null, resultType, null ); } }
1116314_6
@Override public <T> QueryBuilder<T> newQueryBuilder( final Class<T> resultType ) { NotQueryableException.throwIfNotQueryable( resultType ); final ServiceReference<EntityFinder> serviceReference; try { serviceReference = finder.findService( EntityFinder.class ); return new QueryBuilderImpl<>( serviceReference.get(), resultType, null ); } catch( NoSuchServiceTypeException e ) { return new QueryBuilderImpl<>( null, resultType, null ); } }
1116314_7
@Override public <T> QueryBuilder<T> newQueryBuilder( final Class<T> resultType ) { NotQueryableException.throwIfNotQueryable( resultType ); final ServiceReference<EntityFinder> serviceReference; try { serviceReference = finder.findService( EntityFinder.class ); return new QueryBuilderImpl<>( serviceReference.get(), resultType, null ); } catch( NoSuchServiceTypeException e ) { return new QueryBuilderImpl<>( null, resultType, null ); } }
1116314_8
@Override public <T> QueryBuilder<T> newQueryBuilder( final Class<T> resultType ) { NotQueryableException.throwIfNotQueryable( resultType ); final ServiceReference<EntityFinder> serviceReference; try { serviceReference = finder.findService( EntityFinder.class ); return new QueryBuilderImpl<>( serviceReference.get(), resultType, null ); } catch( NoSuchServiceTypeException e ) { return new QueryBuilderImpl<>( null, resultType, null ); } }
1116314_9
@Override public <T> QueryBuilder<T> newQueryBuilder( final Class<T> resultType ) { NotQueryableException.throwIfNotQueryable( resultType ); final ServiceReference<EntityFinder> serviceReference; try { serviceReference = finder.findService( EntityFinder.class ); return new QueryBuilderImpl<>( serviceReference.get(), resultType, null ); } catch( NoSuchServiceTypeException e ) { return new QueryBuilderImpl<>( null, resultType, null ); } }
1146205_0
protected AbstractMuxStore(URI id, BlobStore ... stores) { super(id); setBackingStores(Arrays.asList(stores)); }
1146205_1
@Override public void close() { super.close(); if (cons != null) { for (BlobStoreConnection con : cons.values()) con.close(); cons.clear(); cons = null; } }
1146205_2
public AbstractMuxConnection(BlobStore store, Transaction txn) { super(store); this.txn = txn; }
1146205_3
public Set<BlobStore> getStores(String prefix) { return new HashSet<BlobStore>(((AbstractMuxStore) getBlobStore()).getBackingStores()); }
1146205_4
protected BlobStoreConnection getConnection(BlobStore store, Map<String, String> hints) throws IOException { if (store == null) return null; if (cons == null) throw new IllegalStateException("Connection closed."); BlobStoreConnection con = cons.get(store.getId()); if (con == null) { con = store.openConnection(txn, hints); cons.put(store.getId(), con); } return con; }
1146205_5
@Override public Iterator<URI> listBlobIds(String filterPrefix) throws IOException { List<Iterator<URI>> iterators = new ArrayList<Iterator<URI>>(); for (BlobStore store : getStores(filterPrefix)) iterators.add(getConnection(store, null).listBlobIds(filterPrefix)); return Iterators.concat(iterators.iterator()); }
1146205_6
@Override public URI getCanonicalId() throws IOException { URI internalId = delegate.getCanonicalId(); if (internalId == null) return null; return mapper.getExternalId(internalId); }
1146205_7
@Override public URI getCanonicalId() throws IOException { URI internalId = delegate.getCanonicalId(); if (internalId == null) return null; return mapper.getExternalId(internalId); }
1146205_8
@Override public BlobStoreConnection openConnection(Transaction tx, Map<String, String> hints) throws UnsupportedOperationException, IOException { RemoteConnection con = (tx == null) ? server.openConnection(hints) : new ClientTransactionListener(server.startTransactionListener(hints), tx).getConnection(); return new ClientConnection(this, streamManager, con); }
1146205_9
public boolean hasNext() { return load().hasNext(); }
1149947_0
static int getPort() { int port = DEFAULT_PORT; final String portAsStr = System.getProperty(DEFAULT_PORT_PROPERTY); if (portAsStr != null) { port = Integer.parseInt(portAsStr); } return port; }
1149947_1
static int getPort() { int port = DEFAULT_PORT; final String portAsStr = System.getProperty(DEFAULT_PORT_PROPERTY); if (portAsStr != null) { port = Integer.parseInt(portAsStr); } return port; }
1149947_2
@Override @SuppressWarnings("unchecked") public void mapTo(Context context, HttpBindingData target) throws Exception { Map<String, List<String>> httpHeaders = target.getHeaders(); for (Property property : context.getProperties()) { String name = property.getName(); Object value = property.getValue(); if ((value != null) && (matches(name) || property.hasLabel(EndpointLabel.HTTP.label()))) { if (HTTP_RESPONSE_STATUS.equalsIgnoreCase(name) && (target instanceof HttpResponseBindingData)) { HttpResponseBindingData response = (HttpResponseBindingData)target; if (value instanceof String) { response.setStatus(Integer.parseInt((String) value)); } else if (value instanceof Integer) { response.setStatus((Integer) value); } } else { if (value instanceof List) { // We need to check through the list for non-string values and map .toString() // values to those entries List<String> vals = new ArrayList<String>(); List valueList = (List)value; for (Object obj : valueList) { if (obj instanceof String) { vals.add((String) obj); } else { vals.add(obj.toString()); } } httpHeaders.put(name, vals); } else if (value instanceof String) { List<String> list = new ArrayList<String>(); list.add(String.valueOf(value)); httpHeaders.put(name, list); } } } } }
1149947_3
@Override @SuppressWarnings("unchecked") public void mapTo(Context context, HttpBindingData target) throws Exception { Map<String, List<String>> httpHeaders = target.getHeaders(); for (Property property : context.getProperties()) { String name = property.getName(); Object value = property.getValue(); if ((value != null) && (matches(name) || property.hasLabel(EndpointLabel.HTTP.label()))) { if (HTTP_RESPONSE_STATUS.equalsIgnoreCase(name) && (target instanceof HttpResponseBindingData)) { HttpResponseBindingData response = (HttpResponseBindingData)target; if (value instanceof String) { response.setStatus(Integer.parseInt((String) value)); } else if (value instanceof Integer) { response.setStatus((Integer) value); } } else { if (value instanceof List) { // We need to check through the list for non-string values and map .toString() // values to those entries List<String> vals = new ArrayList<String>(); List valueList = (List)value; for (Object obj : valueList) { if (obj instanceof String) { vals.add((String) obj); } else { vals.add(obj.toString()); } } httpHeaders.put(name, vals); } else if (value instanceof String) { List<String> list = new ArrayList<String>(); list.add(String.valueOf(value)); httpHeaders.put(name, list); } } } } }
1149947_4
public static org.w3c.dom.Node unwrapMessagePart(org.w3c.dom.Element content) { org.w3c.dom.NodeList nl=content.getChildNodes(); for (int i=0; i < nl.getLength(); i++) { if (nl.item(i) instanceof org.w3c.dom.Element) { org.w3c.dom.NodeList nl2=((org.w3c.dom.Element)nl.item(i)).getChildNodes(); for (int j=0; j < nl2.getLength(); j++) { if (nl2.item(j) instanceof org.w3c.dom.Element) { return ((org.w3c.dom.Node)nl2.item(j)); } } if (nl2.getLength() > 0) { return (nl2.item(0)); } return (null); } } return (null); }
1149947_5
public static org.w3c.dom.Node unwrapMessagePart(org.w3c.dom.Element content) { org.w3c.dom.NodeList nl=content.getChildNodes(); for (int i=0; i < nl.getLength(); i++) { if (nl.item(i) instanceof org.w3c.dom.Element) { org.w3c.dom.NodeList nl2=((org.w3c.dom.Element)nl.item(i)).getChildNodes(); for (int j=0; j < nl2.getLength(); j++) { if (nl2.item(j) instanceof org.w3c.dom.Element) { return ((org.w3c.dom.Node)nl2.item(j)); } } if (nl2.getLength() > 0) { return (nl2.item(0)); } return (null); } } return (null); }
1149947_6
public static org.w3c.dom.Node unwrapMessagePart(org.w3c.dom.Element content) { org.w3c.dom.NodeList nl=content.getChildNodes(); for (int i=0; i < nl.getLength(); i++) { if (nl.item(i) instanceof org.w3c.dom.Element) { org.w3c.dom.NodeList nl2=((org.w3c.dom.Element)nl.item(i)).getChildNodes(); for (int j=0; j < nl2.getLength(); j++) { if (nl2.item(j) instanceof org.w3c.dom.Element) { return ((org.w3c.dom.Node)nl2.item(j)); } } if (nl2.getLength() > 0) { return (nl2.item(0)); } return (null); } } return (null); }
1149947_7
public static org.w3c.dom.Element wrapRequestMessagePart(org.w3c.dom.Element content, javax.wsdl.Operation operation) { return (wrapMessagePart(content, operation, operation.getInput().getMessage().getParts(), false)); }
1149947_8
public static org.w3c.dom.Element wrapResponseMessagePart(org.w3c.dom.Element content, javax.wsdl.Operation operation) { return (wrapMessagePart(content, operation, operation.getOutput().getMessage().getParts(), false)); }
1149947_9
public static Map<String, Object> deepClone(Map<String, Object> sourceMap) { Map<String, Object> map = new LinkedHashMap<String, Object>(); Set<Map.Entry<String,Object>> mapEntries = sourceMap.entrySet(); for (Map.Entry<String,Object> entry : mapEntries) { map.put(entry.getKey(), deepClone(entry.getValue())); } return map; }
1155836_0
@Override public LogLevel getLogLevel() { Level level = m_delegate.getEffectiveLevel(); return getLogLevel(level); }
1155836_1
@Override public LogLevel getLogLevel() { Level level = m_delegate.getEffectiveLevel(); return getLogLevel(level); }
1155961_0
private i18n () { }
1155961_1
public List<Contact> findByBasicAttributes ( String firstName, String midInitials, String lastName, String email ) { Contact templateObj = new Contact ( firstName, midInitials, lastName, email ); Example tplCriterion = Example.create ( templateObj ); tplCriterion.enableLike ( MatchMode.ANYWHERE ); tplCriterion.ignoreCase (); Session session = getSession (); Criteria criteria = session.createCriteria ( Contact.class ); criteria.add ( tplCriterion ); return criteria.list (); }
1155961_2
public List<Contact> findByBasicAttributes ( String firstName, String midInitials, String lastName, String email ) { Contact templateObj = new Contact ( firstName, midInitials, lastName, email ); Example tplCriterion = Example.create ( templateObj ); tplCriterion.enableLike ( MatchMode.ANYWHERE ); tplCriterion.ignoreCase (); Session session = getSession (); Criteria criteria = session.createCriteria ( Contact.class ); criteria.add ( tplCriterion ); return criteria.list (); }
1155961_3
public List<Property<FactorValue>> getFactorsForStudy(Long studyId) { Query query = entityManager.createQuery("SELECT distinct p " + "FROM AssayResult ar join ar.cascadedPropertyValues pv, Factor p " + "WHERE " + "ar.study.id =:studyId " + "AND pv.type = p.id ") .setParameter("studyId", studyId); return query.getResultList(); }
1155961_4
public List<Property<CharacteristicValue>> getCharacteristicsForStudy(Long studyId) { Query query = entityManager.createQuery("SELECT distinct p " + "FROM AssayResult ar join ar.cascadedPropertyValues pv, Characteristic p " + "WHERE " + "ar.study.id =:studyId " + "AND pv.type = p.id ") .setParameter("studyId", studyId); return query.getResultList(); }
1155961_5
public List<PropertyValue> getValuesOfPropertyForStudyId(Long studyId, String propertyName) { return entityManager.createQuery("SELECT distinct pv " + "FROM AssayResult ar join ar.cascadedPropertyValues pv, Property p " + "WHERE " + "ar.study.id =:studyId " + "AND pv.type = p.id " + "AND lower(p.value) like lower(:name)") .setParameter("studyId", studyId) .setParameter("name", propertyName) .getResultList(); }
1155961_6
public List<PropertyValue> getValuesOfPropertyForStudyAcc(String studyAcc, String propertyName) { return entityManager.createQuery("SELECT distinct pv " + "FROM AssayResult ar join ar.cascadedPropertyValues pv, Property p " + "WHERE " + "ar.study.acc =:studyId " + "AND pv.type = p.id " + "AND lower(p.value) like lower(:name)") .setParameter("studyId", studyAcc) .setParameter("name", propertyName) .getResultList(); }
1155961_7
public List<String> filterByOntologyTermAndRefName(String termAcc, String refSourceName) { return entityManager.createQuery("SELECT distinct study.acc " + "FROM Study study, AssayResult ar join ar.cascadedPropertyValues pv join pv.ontologyTerms ot " + "WHERE " + "study.id = ar.study.id " + "AND ot.acc =:termAcc " + "AND lower(ot.source.name) = lower(:refSourceName)") .setParameter("termAcc", termAcc) .setParameter("refSourceName", refSourceName) .getResultList(); }
1155961_8
public List<String> getOwnedStudiesForUser(String userName) { //ToDo: problem with this query: returns only those Studies which have a user attached, if a Study is public //but doesn't have attached user, it will not be returned Query query = entityManager.createQuery("SELECT distinct s.acc " + "FROM Study s join s.users user " + "WHERE " + "user.userName =:userName") .setParameter("userName", userName); return query.getResultList(); }
1155961_9
public Study getByAccForUser(String acc, String userName) { Query query = entityManager.createQuery("SELECT s " + "FROM Study s join s.users user " + "WHERE " + "s.acc =:acc AND (user.userName =:userName" + " OR s.status =:status)" ) .setParameter("acc", acc) .setParameter("status", VisibilityStatus.PUBLIC) .setParameter("userName", userName); Study study; try { study = (Study) query.getSingleResult(); } catch (NoResultException e) { throw new BIIDAOException("Study with acc " + acc + " doesn't exist for user " + userName, e); } return study; }
1156021_0
public FormatSetInstance load() throws IOException { // Load the Investigation file loadInvestigation(); // Load the studies in Investigation.studyFileName loadStudies(); // For all the assay files named in the assays, load the file loadAssays(); log.debug("Finished loading Assays"); return getFormatSetInstance(); }
1156021_1
public Person createNewUserFromOptions(String login, CommandLine cmdl) { String forename = cmdl.getOptionValue("n"); String surname = cmdl.getOptionValue("s"); String pwd = cmdl.getOptionValue("p"); String affiliation = cmdl.getOptionValue("f"); String addr = cmdl.getOptionValue("a"); String email = cmdl.getOptionValue("e"); String dates = cmdl.getOptionValue("d"); Date date = null; if (dates != null) { try { date = DateUtils.parseDate(dates, VALID_DATE_FORMATS); } catch (ParseException ex) { throw new TabInvalidValueException("Date '" + dates + "' is invalid"); } } String role = cmdl.getOptionValue("r"); if (role != null && !"submitter".equalsIgnoreCase(role) && !"curator".equalsIgnoreCase(role)) { throw new TabInvalidValueException("role value: '" + role + "' is invalid"); } Person result = new Person(); result.setUserName(login); result.setFirstName(forename); result.setLastName(surname); if (pwd != null) { result.setPassword(StringEncryption.getInstance().encrypt(pwd)); } result.setAffiliation(affiliation); result.setAddress(addr); result.setEmail(email); result.setJoinDate(date); if ("submitter".equalsIgnoreCase(role)) { result.setRole(UserRole.SUBMITTER); } else if ("curator".equalsIgnoreCase(role)) { result.setRole(UserRole.CURATOR); } return result; }
1156021_2
public void validateUser(Person user) { if (user == null) { throw new TabInvalidValueException("Cannot add a null user to the BII db!"); } if (StringUtils.trimToNull(user.getUserName()) == null || StringUtils.trimToNull(user.getPassword()) == null || StringUtils.trimToNull(user.getFirstName()) == null || StringUtils.trimToNull(user.getLastName()) == null || StringUtils.trimToNull(user.getAffiliation()) == null || StringUtils.trimToNull(user.getEmail()) == null || user.getRole() == null) { throw new TabMissingValueException("Invalid user, missing required attribute(s)"); } }
1156021_3
public void validateUser(Person user) { if (user == null) { throw new TabInvalidValueException("Cannot add a null user to the BII db!"); } if (StringUtils.trimToNull(user.getUserName()) == null || StringUtils.trimToNull(user.getPassword()) == null || StringUtils.trimToNull(user.getFirstName()) == null || StringUtils.trimToNull(user.getLastName()) == null || StringUtils.trimToNull(user.getAffiliation()) == null || StringUtils.trimToNull(user.getEmail()) == null || user.getRole() == null) { throw new TabMissingValueException("Invalid user, missing required attribute(s)"); } }
1156021_4
public void validateUser(Person user) { if (user == null) { throw new TabInvalidValueException("Cannot add a null user to the BII db!"); } if (StringUtils.trimToNull(user.getUserName()) == null || StringUtils.trimToNull(user.getPassword()) == null || StringUtils.trimToNull(user.getFirstName()) == null || StringUtils.trimToNull(user.getLastName()) == null || StringUtils.trimToNull(user.getAffiliation()) == null || StringUtils.trimToNull(user.getEmail()) == null || user.getRole() == null) { throw new TabMissingValueException("Invalid user, missing required attribute(s)"); } }
1156021_5
public long addUser(Person user) { UserDAO dao = daoFactory.getUserDAO(); User u = dao.getByUsername(user.getUserName()); if (u != null) { throw new TabInvalidValueException("Login '" + user.getUserName() + "' already exists!"); } validateUser(user); return dao.save(user); }
1156021_6
public void updateUser(Person user) { String login = StringUtils.trimToNull(user.getUserName()); if (login == null) { throw new TabMissingValueException("Cannot update user: user login is null"); } Person userDB = getUserByLogin(login); mergeProps(user, userDB, "address", "firstName", "lastName", "affiliation", "password", "email"); UserRole role = user.getRole(); if (role != null) { userDB.setRole(role); } Date date = user.getJoinDate(); if (date != null) { userDB.setJoinDate(date); } validateUser(userDB); daoFactory.getUserDAO().update(userDB); }
1156021_7
public void deleteUser(String login) { if (login == null) { throw new TabMissingValueException("Cannot update user: user login is null"); } Person userDB = getUserByLogin(login); daoFactory.getUserDAO().deleteById(userDB.getId()); }
1156021_8
public void setStudyOwners(CommandLine cmdl) { String specs[] = cmdl.getOptionValues("o"); if (specs == null) { return; } for (String spec : specs) { setStudyOwners(spec); } }
1156021_9
public void setPublic(String spec) { spec = StringUtils.trimToNull(spec); if (spec == null) { throw new TabInvalidValueException("Invalid syntax for the study list: '" + spec + "'"); } String accs[] = spec.split("\\,"); if (accs == null || accs.length == 0) { throw new TabInvalidValueException("Invalid syntax for the study list: '" + spec + "'"); } setPublic(accs); }
1156136_0
public void setRemoteException(Throwable remoteException) { StringBuilder sb = new StringBuilder(); Set<Throwable> causes = new HashSet(); while (remoteException != null) { sb.append(remoteException.toString()); StackTraceElement[] stackTraceElements = remoteException.getStackTrace(); if (stackTraceElements != null && stackTraceElements.length > 0) { for (StackTraceElement ste : stackTraceElements) { sb.append("\n\t at ").append(ste.toString()); } sb.append("\nsuppressed: "); sb.append(Arrays.toString(remoteException.getSuppressed())); if (remoteException.getCause() != null) { sb.append("\ncaused by: "); remoteException = remoteException.getCause(); // break if causes already contains exception to stop infinite loop if (!causes.add(remoteException)) { break; } } else { break; } } } remoteExceptionString = sb.append('\n').toString(); }
1156136_1
public static String parseString(String string) { if (string == null) return null; StringBuilder sb = new StringBuilder(); int currentIndex = 0; while (currentIndex < string.length()) { int propertyIndex = string.indexOf("${", currentIndex); int expressionIndex = string.indexOf("#{", currentIndex); int nextIndex = propertyIndex < 0 ? (expressionIndex < 0 ? string.length() : expressionIndex) : (expressionIndex < 0 ? propertyIndex : Math.min(expressionIndex, propertyIndex)); sb.append(string.substring(currentIndex, nextIndex)); currentIndex = nextIndex + 2; if (nextIndex == propertyIndex) { nextIndex = string.indexOf('}', currentIndex); if (nextIndex < 0) { throw new IllegalArgumentException(string); } sb.append(evalProperty(string, currentIndex, nextIndex)); currentIndex = nextIndex + 1; } else if (nextIndex == expressionIndex) { Stack<Operator> operators = new Stack<>(); Stack<Value> operands = new Stack<>(); Tokenizer tokenizer = new Tokenizer(string, Operator.symbols(), true, false, currentIndex); boolean closed = false; // we set this to true because if '-' is on the beginning, is interpreted as sign boolean lastTokenIsOperator = true; boolean negativeSign = false; while (tokenizer.hasMoreTokens()) { String token = tokenizer.nextToken(); Operator op = Operator.from(token); if (op == null) { operands.push(new Value(negativeSign ? "-" + token : token)); lastTokenIsOperator = false; continue; } else if (op.isWhite()) { // do not set lastTokenIsOperator continue; } else if (op == Operator.OPENVAR) { if (!tokenizer.hasMoreTokens()) throw new IllegalArgumentException(string); StringBuilder var = new StringBuilder(); while (tokenizer.hasMoreTokens()) { token = tokenizer.nextToken(); if ((op = Operator.from(token)) == null || op.isWhite()) { var.append(token); } else { break; } } if (op != Operator.CLOSEVAR) { throw new IllegalArgumentException("Expected '}' but found " + token + " in " + string); } operands.push(evalProperty(var.toString(), 0, var.length())); lastTokenIsOperator = false; continue; } else if (op == Operator.CLOSEVAR) { // end of expression to be evaluated closed = true; break; } else if (op.isFunction()) { operators.push(op); } else if (op == Operator.OPENPAR) { operators.push(op); } else if (op == Operator.CLOSEPAR) { while ((op = operators.pop()) != Operator.OPENPAR) { op.exec(operands); if (operators.isEmpty()) throw new IllegalStateException("Cannot find matching '('"); } while (!operators.isEmpty() && operators.peek().isFunction()) { op = operators.pop(); op.exec(operands); } } else if (op == Operator.MINUS && lastTokenIsOperator) { negativeSign = true; } else { while (true) { if (operators.isEmpty() || operators.peek() == Operator.OPENPAR || operators.peek().precedence() < op.precedence()) { operators.push(op); break; } operators.pop().exec(operands); } lastTokenIsOperator = true; } } if (!closed) { throw new IllegalArgumentException("Expression is missing closing '}': " + string); } while (!operators.empty()) { operators.pop().exec(operands); } sb.append(operands.pop()); if (!operands.empty()) { throw new IllegalArgumentException(operands.size() + " operands not processed: top=" + operands.pop() + " all=" + operands); } currentIndex = tokenizer.getPosition(); } } return sb.toString(); }
1156136_2
public boolean isXsltAttribute(String file) { boolean xslt = false; if (file != null && !file.trim().isEmpty()) { xslt = file.toLowerCase().startsWith(XSLT_PREFIX); } return xslt; }
1156136_3
@Override public DistStageAck executeOnWorker() { if (!isServiceRunning()) { return successfulResponse(); } long startTime = TimeService.currentTimeMillis(); for (; ; ) { long now = TimeService.currentTimeMillis(); if (now >= startTime + timeout) { return errorResponse("The topology has not settled within timeout."); } boolean settled = true; if (checkEvents.contains(HistoryType.TOPOLOGY)) { settled = settled && checkEventHistory(history.getTopologyChangeHistory(cacheName), "Topology change", now); } if (checkEvents.contains(HistoryType.REHASH)) { settled = settled && checkEventHistory(history.getRehashHistory(cacheName), "Rehash", now); } if (checkEvents.contains(HistoryType.CACHE_STATUS)) { settled = settled && checkEventHistory(history.getCacheStatusChangeHistory(cacheName), "Cache status change", now); } if (checkMembership) { List<Clustered.Membership> membershipHistory = clustered == null ? null : clustered.getMembershipHistory(); settled = settled && checkMembership(membershipHistory, now); } if (settled) { return successfulResponse(); } else { try { Thread.sleep(1000); } catch (InterruptedException e) { return errorResponse("Waiting interrupted", e); } } } }
1156136_4
@Override protected boolean invokeLogic(long keyId) throws Exception { Operation operation = getOperation(operationTypeRandom); OperationTimestampPair prevOperation = timestamps.get(keyId); // first we have to get the value PrivateLogValue prevValue = checkedGetValue(keyId); PrivateLogValue backupValue = null; if (prevOperation != null) { if (prevValue == null || !prevValue.contains(prevOperation.operationId)) { // non-cleaned old value or stale read, try backup backupValue = checkedGetValue(~keyId); boolean txEnabled = manager.getGeneralConfiguration().getTransactionSize() > 0; // Modifying the same key within a single transaction may cause false stale reads, avoid it by checking maxPrunedOperationIds boolean valuePruned = maxPrunedOperationIds.get(keyId) != null && maxPrunedOperationIds.get(keyId) >= prevOperation.operationId; if ((backupValue == null || !backupValue.contains(prevOperation.operationId)) && (!txEnabled || !valuePruned)) { // definitely stale read log.debugf("Detected stale read, keyId=%s, previousValue=%s, complementValue=%s", keyId, prevValue, backupValue); waitForStaleRead(prevOperation.timestamp); return false; } else { if (!txEnabled || !valuePruned) { // pretend that we haven't read it at all prevValue = null; } } } } if (operation == BasicOperations.GET) { // especially GETs are not allowed here, because these would break the deterministic order // - each operationId must be written somewhere throw new UnsupportedOperationException("Only PUT and REMOVE operations are allowed for this logic"); } else if (prevValue == null || operation == BasicOperations.PUT) { PrivateLogValue nextValue; if (prevValue != null) { nextValue = getNextValue(keyId, prevValue); } else { // the value may have been removed, look for backup if (backupValue == null) { backupValue = checkedGetValue(~keyId); } if (backupValue == null) { nextValue = new PrivateLogValue(stressor.id, operationId); } else { nextValue = getNextValue(keyId, backupValue); } } if (nextValue == null) { return false; } checkedPutValue(keyId, nextValue); if (backupValue != null) { delayedRemoveValue(~keyId, backupValue); } } else if (operation == BasicOperations.REMOVE) { PrivateLogValue nextValue = getNextValue(keyId, prevValue); if (nextValue == null) { return false; } checkedPutValue(~keyId, nextValue); delayedRemoveValue(keyId, prevValue); } if (transactionSize > 0) { txModifications.add(new KeyOperationPair(keyId, operationId)); } else { long now = TimeService.currentTimeMillis(); timestamps.put(keyId, new OperationTimestampPair(operationId, now)); log.tracef("Operation %d on %08X finished at %d", operationId, keyId, now); } return true; }
1156136_5
@Override public void addValue(double value, double deviation, Comparable seriesName, double xValue, String xString) { YIntervalSeries series = seriesMap.get(seriesName); if (series == null) { seriesMap.put(seriesName, series = new YIntervalSeries(seriesName)); dataset.addSeries(series); } // don't let the chart scale according to deviation (values wouldn't be seen) upperRange = Math.max(upperRange, Math.min(value + deviation, 3 * value)); series.add(xValue, value, value - deviation, value + deviation); if (xString != null) { iterationValues.put(xValue, xString); } }
1158118_0
public static String decrypt(String input) { if (isEmpty(input)) { return input; } char[] inputChars = input.toCharArray(); int length = inputChars.length; char[] inputCharsCopy = new char[length]; int j = 0; int i = 0; while (j < length) { inputCharsCopy[j] = ((char) (inputChars[j] - '\1' ^ i)); i = (char) (i + 1); j++; } return new String(inputCharsCopy); }
1158315_0
@Override public String getNamespace(String prefix) { String namespace; mappingsLock.readLock().lock(); try { namespace = prefixMap.get(prefix); } finally { mappingsLock.readLock().unlock(); } if(namespace == null){ ServiceReference[] refs = getSortedProviderReferences(); for(int i=0;namespace == null && i<refs.length;i++){ NamespacePrefixProvider provider = getService(refs[i]); if(provider != null){ namespace = provider.getNamespace(prefix); } } } return namespace; }
1158315_1
@Override public String getFullName(String shortNameOrUri) { String prefix = NamespaceMappingUtils.getPrefix(shortNameOrUri); if(prefix != null){ String namespace = getNamespace(prefix); if(namespace != null){ return namespace+shortNameOrUri.substring(prefix.length()+1); } else { //no mapping return null return null; } } else { //not a shortName ... return the parsed return shortNameOrUri; } }
1158315_2
PermissionInfo[] retrievePermissions(String location) { List<PermissionInfo> permInfoList = new ArrayList<PermissionInfo>(); Iterator<Triple> ownerTriples = systemGraph.filter(new IRI(location), OSGI.owner, null); if (ownerTriples.hasNext()) { BlankNodeOrIRI user = (BlankNodeOrIRI) ownerTriples.next().getObject(); lookForPermissions(user, permInfoList); } if (permInfoList.isEmpty()) { return null; } return permInfoList.toArray(new PermissionInfo[permInfoList.size()]); }
1158315_3
PermissionInfo[] retrievePermissions(String location) { List<PermissionInfo> permInfoList = new ArrayList<PermissionInfo>(); Iterator<Triple> ownerTriples = systemGraph.filter(new IRI(location), OSGI.owner, null); if (ownerTriples.hasNext()) { BlankNodeOrIRI user = (BlankNodeOrIRI) ownerTriples.next().getObject(); lookForPermissions(user, permInfoList); } if (permInfoList.isEmpty()) { return null; } return permInfoList.toArray(new PermissionInfo[permInfoList.size()]); }
1158315_4
public static OWLOntologyID guessOntologyID(InputStream content, Parser parser, String format) throws IOException { return guessOntologyID(content, parser, format, _LOOKAHEAD_LIMIT_DEFAULT); }
1158315_5
public static OWLOntologyID guessOntologyID(InputStream content, Parser parser, String format) throws IOException { return guessOntologyID(content, parser, format, _LOOKAHEAD_LIMIT_DEFAULT); }
1158315_6
public static OWLOntologyID guessOntologyID(InputStream content, Parser parser, String format) throws IOException { return guessOntologyID(content, parser, format, _LOOKAHEAD_LIMIT_DEFAULT); }
1158315_7
public static OWLOntologyID guessOntologyID(InputStream content, Parser parser, String format) throws IOException { return guessOntologyID(content, parser, format, _LOOKAHEAD_LIMIT_DEFAULT); }
1158315_8
public static OWLOntologyID guessOntologyID(InputStream content, Parser parser, String format) throws IOException { return guessOntologyID(content, parser, format, _LOOKAHEAD_LIMIT_DEFAULT); }
1158315_9
public static OWLOntologyID guessOntologyID(InputStream content, Parser parser, String format) throws IOException { return guessOntologyID(content, parser, format, _LOOKAHEAD_LIMIT_DEFAULT); }
1161604_0
@Override public TriplestoreReader getReader() { if (m_reader == null){ try{ open(); } catch(TrippiException e){ logger.error(e.toString(),e); } } return m_reader; }
1161604_1
@Override public TriplestoreWriter getWriter() { if (m_reader == null){ try{ open(); } catch(TrippiException e){ logger.error(e.toString(),e); } } if (m_writer == null) { throw new UnsupportedOperationException( "This MulgaraConnector is read-only!"); } else { return m_writer; } }
1163141_0
public ValidationResult validate(String pid) { if (pid == null) { throw new NullPointerException("pid may not be null."); } ObjectInfo object = null; try { object = objectSource.getValidationObject(pid); } catch (ObjectSourceException e) { // This falls into the case of object==null. } if (object == null) { ValidationResult result = new ValidationResult(new BasicObjectInfo(pid)); result.addNote(ValidationResultNotation.objectNotFound(pid)); return result; } else { return validate(object); } }
1163141_1
public ValidationResult validate(String pid) { if (pid == null) { throw new NullPointerException("pid may not be null."); } ObjectInfo object = null; try { object = objectSource.getValidationObject(pid); } catch (ObjectSourceException e) { // This falls into the case of object==null. } if (object == null) { ValidationResult result = new ValidationResult(new BasicObjectInfo(pid)); result.addNote(ValidationResultNotation.objectNotFound(pid)); return result; } else { return validate(object); } }
1163141_2
public ValidationResult validate(String pid) { if (pid == null) { throw new NullPointerException("pid may not be null."); } ObjectInfo object = null; try { object = objectSource.getValidationObject(pid); } catch (ObjectSourceException e) { // This falls into the case of object==null. } if (object == null) { ValidationResult result = new ValidationResult(new BasicObjectInfo(pid)); result.addNote(ValidationResultNotation.objectNotFound(pid)); return result; } else { return validate(object); } }
1163141_3
public ValidationResult validate(String pid) { if (pid == null) { throw new NullPointerException("pid may not be null."); } ObjectInfo object = null; try { object = objectSource.getValidationObject(pid); } catch (ObjectSourceException e) { // This falls into the case of object==null. } if (object == null) { ValidationResult result = new ValidationResult(new BasicObjectInfo(pid)); result.addNote(ValidationResultNotation.objectNotFound(pid)); return result; } else { return validate(object); } }
1163141_4
public ValidationResult validate(String pid) { if (pid == null) { throw new NullPointerException("pid may not be null."); } ObjectInfo object = null; try { object = objectSource.getValidationObject(pid); } catch (ObjectSourceException e) { // This falls into the case of object==null. } if (object == null) { ValidationResult result = new ValidationResult(new BasicObjectInfo(pid)); result.addNote(ValidationResultNotation.objectNotFound(pid)); return result; } else { return validate(object); } }
1163141_5
public static OptionDefinition get(String id, InstallOptions options) { String label = _PROPS.getProperty(id + ".label"); String description = _PROPS.getProperty(id + ".description"); String[] validValues = getArray(id + ".validValues"); String defaultValue = _PROPS.getProperty(id + ".defaultValue"); // If label, description, validValues and defaultValue are all null, // assume that no definition for the id exists. //if (label == null && description == null && validValues == null && // defaultValue == null) { // return null; //} // Use the environment variable FEDORA_HOME as the default, if defined if (id.equals(InstallOptions.FEDORA_HOME)) { String eFH = System.getenv("FEDORA_HOME"); if (eFH != null && eFH.length() != 0) { defaultValue = eFH; } } // Use CATALINA_HOME as the default, if defined. if (id.equals(InstallOptions.TOMCAT_HOME)) { String eCH = System.getenv("CATALINA_HOME"); if (eCH != null && eCH.length() != 0) { defaultValue = eCH; } else if (options.getValue(InstallOptions.SERVLET_ENGINE) .equals(InstallOptions.INCLUDED)) { defaultValue = options.getValue(InstallOptions.FEDORA_HOME) + File.separator + "tomcat"; } } return new OptionDefinition(id, label, description, validValues, defaultValue, options); }
1163141_6
public void update() throws InstallationFailedException { setHTTPPort(); setShutdownPort(); setSSLPort(); setURIEncoding(); }
1163141_7
public void validate(File objectAsFile) throws ObjectValidityException, GeneralException { try { validate(new StreamSource(new FileInputStream(objectAsFile))); } catch (IOException e) { String msg = "DOValidatorXMLSchema returned error.\n" + "The underlying exception was a " + e.getClass().getName() + ".\n" + "The message was " + "\"" + e.getMessage() + "\""; throw new GeneralException(msg); } }
1163141_8
public void validate(File objectAsFile) throws ObjectValidityException, GeneralException { try { validate(new StreamSource(new FileInputStream(objectAsFile))); } catch (IOException e) { String msg = "DOValidatorXMLSchema returned error.\n" + "The underlying exception was a " + e.getClass().getName() + ".\n" + "The message was " + "\"" + e.getMessage() + "\""; throw new GeneralException(msg); } }
1163141_9
public void validate(File objectAsFile) throws ObjectValidityException, GeneralException { try { validate(new StreamSource(new FileInputStream(objectAsFile))); } catch (IOException e) { String msg = "DOValidatorXMLSchema returned error.\n" + "The underlying exception was a " + e.getClass().getName() + ".\n" + "The message was " + "\"" + e.getMessage() + "\""; throw new GeneralException(msg); } }
1163806_0
@Override public ChangeLogSet parse(final Run build, final RepositoryBrowser<?> browser, final File changelogFile) throws IOException, SAXException { try (FileInputStream stream = new FileInputStream(changelogFile); Reader reader = new InputStreamReader(stream, Charset.defaultCharset())) { return parse(build, browser, reader); } }
1163806_1
@Override public ChangeLogSet parse(final Run build, final RepositoryBrowser<?> browser, final File changelogFile) throws IOException, SAXException { try (FileInputStream stream = new FileInputStream(changelogFile); Reader reader = new InputStreamReader(stream, Charset.defaultCharset())) { return parse(build, browser, reader); } }
1163806_2
@Override public ChangeLogSet parse(final Run build, final RepositoryBrowser<?> browser, final File changelogFile) throws IOException, SAXException { try (FileInputStream stream = new FileInputStream(changelogFile); Reader reader = new InputStreamReader(stream, Charset.defaultCharset())) { return parse(build, browser, reader); } }
1163806_3
static String createAuthorization(final StandardUsernamePasswordCredentials credentials) { final String username = credentials.getUsername(); final Secret secretPassword = credentials.getPassword(); final String password = secretPassword.getPlainText(); final String credPair = username + ":" + password; final byte[] credBytes = credPair.getBytes(MediaType.UTF_8); final String base64enc = DatatypeConverter.printBase64Binary(credBytes); final String result = "Basic " + base64enc; return result; }
1163806_4
public String ping() throws IOException { final URI requestUri; if (isTeamServices) { requestUri = UriHelper.join(collectionUri, "_apis", "connectiondata"); } else { requestUri = UriHelper.join(collectionUri, "_home", "About"); } return request(String.class, HttpMethod.GET, requestUri, null); }
1163806_5
@Override public String toString() { return UriHelper.serializeParameters(this); }
1163806_6
@Override public String toString() { return UriHelper.serializeParameters(this); }
1163806_7
@Override public String toString() { return UriHelper.serializeParameters(this); }