_id stringlengths 2 7 | title stringlengths 3 140 | partition stringclasses 3
values | text stringlengths 73 34.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q175400 | FysatHeader.readPIB | test | boolean readPIB(RandomAccessFile raf) throws IOException {
this.firstHeader = new AwxFileFirstHeader();
int pos = 0;
raf.seek(pos);
// gini header process
byte[] buf = new byte[FY_AWX_PIB_LEN];
int count = raf.read(buf);
EndianByteBuffer byteBuffer;
if (count == FY_AWX_PIB_LEN) {
byteBuffer = new EndianByteBuffer(buf, this.firstHeader.byteOrder);
this.firstHeader.fillHeader(byteBuffer);
} else {
return false;
}
if (!((this.firstHeader.fileName.endsWith(".AWX") || this.firstHeader.fileName.endsWith(".awx"))
&& this.firstHeader.firstHeaderLength == FY_AWX_PIB_LEN)) {
return false;
}
// skip the fills of the first record
// raf.seek(FY_AWX_PIB_LEN + this.firstHeader.fillSectionLength);
buf = new byte[this.firstHeader.secondHeaderLength];
raf.readFully(buf);
byteBuffer = new EndianByteBuffer(buf, this.firstHeader.byteOrder);
switch (this.firstHeader.typeOfProduct) {
case AwxFileFirstHeader.AWX_PRODUCT_TYPE_UNDEFINED:
throw new UnsupportedDatasetException();
case AwxFileFirstHeader.AWX_PRODUCT_TYPE_GEOSAT_IMAGE:
secondHeader = new AwxFileGeoSatelliteSecondHeader();
secondHeader.fillHeader(byteBuffer);
break;
case AwxFileFirstHeader.AWX_PRODUCT_TYPE_POLARSAT_IMAGE:
throw new UnsupportedDatasetException();
case AwxFileFirstHeader.AWX_PRODUCT_TYPE_GRID:
secondHeader = new AwxFileGridProductSecondHeader();
secondHeader.fillHeader(byteBuffer);
break;
case AwxFileFirstHeader.AWX_PRODUCT_TYPE_DISCREET:
throw new UnsupportedDatasetException();
case AwxFileFirstHeader.AWX_PRODUCT_TYPE_GRAPH_ANALIYSIS:
throw new UnsupportedDatasetException();
}
return true;
} | java | {
"resource": ""
} |
q175401 | InvDatasetImpl.finish | test | public boolean finish() {
boolean ok = true;
java.util.Iterator iter;
logger.debug("Now finish " + getName() + " id= " + getID());
authorityName = null;
dataType = null;
dataFormatType = null;
defaultService = null;
gc = null;
tc = null;
docs = new ArrayList<>();
metadata = new ArrayList<>();
properties = new ArrayList<>();
creators = new ArrayList<>();
contributors = new ArrayList<>();
dates = new ArrayList<>();
keywords = new ArrayList<>();
projects = new ArrayList<>();
publishers = new ArrayList<>();
variables = new ArrayList<>();
canonicalize(); // canonicalize thredds metadata
transfer2PublicMetadata(tm, true); // add local metadata
transfer2PublicMetadata(tmi, true); // add local inherited metadata
transferInheritable2PublicMetadata((InvDatasetImpl) getParent()); // add inheritable metadata from parents
// build the expanded access list
access = new ArrayList<>();
// add access element if urlPath is specified
if ((urlPath != null) && (getServiceDefault() != null)) {
InvAccessImpl a = new InvAccessImpl(this, urlPath, getServiceDefault());
a.setSize(size);
a.finish();
addExpandedAccess(a);
}
// add local access elements
iter = accessLocal.iterator();
while (iter.hasNext()) {
InvAccessImpl a = (InvAccessImpl) iter.next();
a.finish();
addExpandedAccess(a);
}
// recurse into child datasets.
if (!(this instanceof InvCatalogRef)) {
for (InvDataset invDataset : this.getDatasets()) {
InvDatasetImpl curDs = (InvDatasetImpl) invDataset;
ok &= curDs.finish();
}
}
return ok;
} | java | {
"resource": ""
} |
q175402 | InvDatasetImpl.transferInheritable2PublicMetadata | test | private void transferInheritable2PublicMetadata(InvDatasetImpl parent) {
if (parent == null) return;
logger.debug(" inheritFromParent= " + parent.getID());
transfer2PublicMetadata(parent.getLocalMetadataInheritable(), true);
//transfer2PublicMetadata(parent.getCat6Metadata(), true);
/* look through local metadata, find inherited InvMetadata elements
ThreddsMetadata tmd = parent.getLocalMetadata();
Iterator iter = tmd.getMetadata().iterator();
while (iter.hasNext()) {
InvMetadata meta = (InvMetadata) iter.next();
if (meta.isInherited()) {
if (!meta.isThreddsMetadata()) {
metadata.add(meta);
} else {
if (debugInherit) System.out.println(" inheritMetadata Element " + tmd.isInherited() + " " + meta.isInherited());
meta.finish(); // make sure XLink is read in.
transfer2PublicMetadata(meta.getThreddsMetadata(), false);
}
}
} */
// recurse
transferInheritable2PublicMetadata((InvDatasetImpl) parent.getParent());
} | java | {
"resource": ""
} |
q175403 | InvDatasetImpl.transferMetadata | test | public void transferMetadata(InvDatasetImpl fromDs, boolean copyInheritedMetadataFromParents) {
if (fromDs == null) return;
logger.debug(" transferMetadata= " + fromDs.getName());
if (this != fromDs)
getLocalMetadata().add(fromDs.getLocalMetadata(), false);
transferInheritableMetadata(fromDs, getLocalMetadataInheritable(), copyInheritedMetadataFromParents);
setResourceControl(fromDs.getRestrictAccess());
} | java | {
"resource": ""
} |
q175404 | InvDatasetImpl.transferInheritableMetadata | test | private void transferInheritableMetadata(InvDatasetImpl fromDs, ThreddsMetadata target,
boolean copyInheritedMetadataFromParents) {
if (fromDs == null) return;
logger.debug(" transferInheritedMetadata= " + fromDs.getName());
target.add(fromDs.getLocalMetadataInheritable(), true);
/* look through local metadata, find inherited InvMetadata elements
ThreddsMetadata tmd = fromDs.getLocalMetadata();
Iterator iter = tmd.getMetadata().iterator();
while (iter.hasNext()) {
InvMetadata meta = (InvMetadata) iter.next();
if (meta.isInherited()) {
if (!meta.isThreddsMetadata()) {
tmc.addMetadata( meta);
} else {
logger.debug(" transferInheritedMetadata "+meta.hashCode()+" = "+meta);
meta.finish(); // LOOK ?? make sure XLink is read in.
tmc.add( meta.getThreddsMetadata(), true);
}
}
} */
// now do the same for the parents
if (copyInheritedMetadataFromParents)
transferInheritableMetadata((InvDatasetImpl) fromDs.getParent(), target, true);
} | java | {
"resource": ""
} |
q175405 | InvDatasetImpl.setContributors | test | public void setContributors(List<ThreddsMetadata.Contributor> a) {
List<ThreddsMetadata.Contributor> dest = tm.getContributors();
for (ThreddsMetadata.Contributor item : a) {
if (!dest.contains(item))
dest.add(item);
}
hashCode = 0;
} | java | {
"resource": ""
} |
q175406 | InvDatasetImpl.addDataset | test | public void addDataset(int index, InvDatasetImpl ds) {
if (ds == null) return;
ds.setParent(this);
datasets.add(index, ds);
hashCode = 0;
} | java | {
"resource": ""
} |
q175407 | InvDatasetImpl.removeDataset | test | public boolean removeDataset(InvDatasetImpl ds) {
if (this.datasets.remove(ds)) {
ds.setParent(null);
InvCatalogImpl cat = (InvCatalogImpl) getParentCatalog();
if (cat != null)
cat.removeDatasetByID(ds);
return (true);
}
return (false);
} | java | {
"resource": ""
} |
q175408 | InvDatasetImpl.replaceDataset | test | public boolean replaceDataset(InvDatasetImpl remove, InvDatasetImpl add) {
for (int i = 0; i < datasets.size(); i++) {
InvDataset dataset = datasets.get(i);
if (dataset.equals(remove)) {
datasets.set(i, add);
InvCatalogImpl cat = (InvCatalogImpl) getParentCatalog();
if (cat != null) {
cat.removeDatasetByID(remove);
cat.addDatasetByID(add);
}
return true;
}
}
return false;
} | java | {
"resource": ""
} |
q175409 | InvDatasetImpl.addService | test | public void addService(InvService service) {
// System.out.println("--add dataset service= "+service.getName());
servicesLocal.add(service);
services.add(service);
// add nested servers
for (InvService nested : service.getServices()) {
services.add(nested);
// System.out.println("--add expanded service= "+nested.getName());
}
hashCode = 0;
} | java | {
"resource": ""
} |
q175410 | InvDatasetImpl.removeService | test | public void removeService(InvService service) {
servicesLocal.remove(service);
services.remove(service);
// remove nested servers
for (InvService nested : service.getServices()) {
services.remove(nested);
}
} | java | {
"resource": ""
} |
q175411 | InvDatasetImpl.setServicesLocal | test | public void setServicesLocal(java.util.List<InvService> s) {
this.services = new ArrayList<>();
this.servicesLocal = new ArrayList<>();
for (InvService elem : s) {
addService(elem);
}
hashCode = 0;
} | java | {
"resource": ""
} |
q175412 | InvDatasetImpl.removeLocalMetadata | test | public boolean removeLocalMetadata(InvMetadata metadata) {
InvDatasetImpl parentDataset = ((InvDatasetImpl) metadata.getParentDataset());
List localMdata = parentDataset.getLocalMetadata().getMetadata();
if (localMdata.contains(metadata)) {
if (localMdata.remove(metadata)) {
hashCode = 0; // Need to recalculate the hash code.
return (true);
}
}
return (false);
} | java | {
"resource": ""
} |
q175413 | InvDatasetImpl.getUserProperty | test | public Object getUserProperty(Object key) {
if (userMap == null) return null;
return userMap.get(key);
} | java | {
"resource": ""
} |
q175414 | DatasetNamer.validate | test | boolean validate(StringBuilder out) {
this.isValid = true;
// If log from construction has content, append to validation output msg.
if (this.msgLog.length() > 0) {
out.append(this.msgLog);
}
// Check that name is not null (it can be an empty string).
if (this.getName() == null) {
this.isValid = false;
out.append(" ** DatasetNamer (1): null value for name is not valid.");
}
// Check that addLevel is not null.
// boolean can't be null
//if ( this.getAddLevel() == null)
//{
// this.isValid = false;
// out.append(" ** DatasetNamer (2): null value for addLevel is not valid.");
//}
// Check that type is not null.
if (this.getType() == null) {
this.isValid = false;
out.append(" ** DatasetNamer (3): null value for type is not valid (set with bad string?).");
}
if ( this.getType() == DatasetNamerType.REGULAR_EXPRESSION
&& ( this.getMatchPattern() == null || this.getSubstitutePattern() == null ))
{
this.isValid = false;
out.append(" ** DatasetNamer (4): invalid datasetNamer <" + this.getName() + ">;" +
" type is " + this.getType().toString() + ": matchPattern(" + this.getMatchPattern() + ") and substitutionPattern(" + this.getSubstitutePattern() + ") " +
"must not be null.");
}
if ( this.getType() == DatasetNamerType.DODS_ATTRIBUTE
&& ( this.getAttribContainer() == null || this.getAttribName() == null ) )
{
this.isValid = false;
out.append(" ** DatasetNamer (5): invalid datasetNamer <" + this.getName() + ">;" +
" type is " + this.getType().toString() + ": attriuteContainer(" + this.getAttribContainer() + ") and attributeName(" + this.getAttribName() + ") must not be null.");
}
return (this.isValid);
} | java | {
"resource": ""
} |
q175415 | BufrDataDescriptionSection.getDescriptors | test | public final List<String> getDescriptors() {
List<String> desc = new ArrayList<String>();
for (short fxy : descriptors)
desc.add(Descriptor.makeString(fxy));
return desc;
} | java | {
"resource": ""
} |
q175416 | WFSController.constructServerPath | test | public static String constructServerPath(HttpServletRequest hsreq) {
return hsreq.getScheme() + "://" + hsreq.getServerName() + ":" + hsreq.getServerPort() + "/thredds/wfs/";
} | java | {
"resource": ""
} |
q175417 | WFSController.getCapabilities | test | private void getCapabilities(PrintWriter out, HttpServletRequest hsreq, SimpleGeometryCSBuilder sgcs) {
WFSGetCapabilitiesWriter gcdw = new WFSGetCapabilitiesWriter(out, WFSController.constructServerPath(hsreq));
gcdw.startXML();
gcdw.addOperation(WFSRequestType.GetCapabilities); gcdw.addOperation(WFSRequestType.DescribeFeatureType); gcdw.addOperation(WFSRequestType.GetFeature);
gcdw.writeOperations();
List<String> seriesNames = sgcs.getGeometrySeriesNames();
for(String name : seriesNames) {
gcdw.addFeature(new WFSFeature(TDSNAMESPACE + ":" + name, name));
}
gcdw.writeFeatureTypes();
gcdw.finishXML();
} | java | {
"resource": ""
} |
q175418 | WFSController.getFeature | test | private WFSExceptionWriter getFeature(PrintWriter out, HttpServletRequest hsreq, SimpleGeometryCSBuilder sgcs, String ftName, String fullFtName) {
List<SimpleGeometry> geometryList = new ArrayList<SimpleGeometry>();
GeometryType geoT = sgcs.getGeometryType(ftName);
if(geoT == null){
return new WFSExceptionWriter("Feature Type of " + fullFtName + " not found.", "GetFeature" , "OperationProcessingFailed");
}
try {
switch(geoT) {
case POINT:
Point pt = sgcs.getPoint(ftName, 0);
int j = 0;
while(pt != null) {
geometryList.add(pt);
j++;
pt = sgcs.getPoint(ftName, j);
}
break;
case LINE:
Line line = sgcs.getLine(ftName, 0);
int k = 0;
while(line != null) {
geometryList.add(line);
k++;
line = sgcs.getLine(ftName, k);
}
break;
case POLYGON:
Polygon poly = sgcs.getPolygon(ftName, 0);
int i = 0;
while(poly != null) {
geometryList.add(poly);
i++;
poly = sgcs.getPolygon(ftName, i);
}
break;
}
}
// Perhaps will change this to be implemented in the CFPolygon class
catch(ArrayIndexOutOfBoundsException aout){
}
WFSGetFeatureWriter gfdw = new WFSGetFeatureWriter(out, WFSController.constructServerPath(hsreq), WFSController.getXMLNamespaceXMLNSValue(hsreq), geometryList, ftName);
gfdw.startXML();
gfdw.writeMembers();
gfdw.finishXML();
return null;
} | java | {
"resource": ""
} |
q175419 | WFSController.checkParametersForError | test | private WFSExceptionWriter checkParametersForError(String request, String version, String service, String typeName) {
// The SERVICE parameter is required. If not specified, is an error (throw exception through XML).
if(service != null) {
// For the WFS servlet it must be WFS if not, write out an InvalidParameterValue exception.
if(!service.equalsIgnoreCase("WFS")) {
return new WFSExceptionWriter("WFS Server error. SERVICE parameter must be of value WFS.", "service", "InvalidParameterValue");
}
}
else {
return new WFSExceptionWriter("WFS server error. SERVICE parameter is required.", "request", "MissingParameterValue");
}
// The REQUEST Parameter is required. If not specified, is an error (throw exception through XML).
if(request != null) {
// Only go through version checks if NOT a Get Capabilities request, the VERSION parameter is required for all operations EXCEPT GetCapabilities section 7.6.25 of WFS 2.0 Interface Standard
if(!request.equalsIgnoreCase(WFSRequestType.GetCapabilities.toString())) {
if(version != null ) {
// If the version is not failed report exception VersionNegotiationFailed, from OGC Web Services Common Standard section 7.4.1
// Get each part
String[] versionParts = version.split("\\.");
for(int ind = 0; ind < versionParts.length; ind++) {
// Check if number will throw NumberFormatException if not.
try {
Integer.valueOf(versionParts[ind]);
}
/* Version parameters are only allowed to consist of numbers and periods. If this is not the case then
* It qualifies for InvalidParameterException
*/
catch (NumberFormatException excep){
return new WFSExceptionWriter("WFS server error. VERSION parameter consists of invalid characters.", "version", "InvalidParameterValue");
}
}
/* Now the version parts are all constructed from the parameter
* Analyze for correctness.
*/
boolean validVersion = false;
// If just number 2 is specified, assume 2.0.0, pass the check
if(versionParts.length == 1) if(versionParts[0].equals("2")) validVersion = true;
// Two or more version parts specified, make sure it's 2.0.#.#...
if(versionParts.length >= 2) if(versionParts[0].equals("2") && versionParts[1].equals("0")) validVersion = true;
/* Another exception VersionNegotiationFailed is specified by OGC Web Services Common
* for version mismatches. If the version check failed print this exception
*/
if(!validVersion){
return new WFSExceptionWriter("WFS Server error. Version requested is not supported.", null, "VersionNegotiationFailed");
}
}
else {
return new WFSExceptionWriter("WFS server error. VERSION parameter is required.", "request", "MissingParameterValue");
}
// Last check to see if typenames is specified, must be for GetFeature, DescribeFeatureType
if(typeName == null) {
return new WFSExceptionWriter("WFS server error. For the specifed request, parameter typename or typenames must be specified.", request, "MissingParameterValue");
}
}
WFSRequestType reqToProc = WFSRequestType.getWFSRequestType(request);
if(reqToProc == null) return new WFSExceptionWriter("WFS server error. REQUEST parameter is not valid. Possible values: GetCapabilities, "
+ "DescribeFeatureType, GetFeature", "request", "InvalidParameterValue");
}
else{
return new WFSExceptionWriter("WFS server error. REQUEST parameter is required.", "request", "MissingParameterValue");
}
return null;
} | java | {
"resource": ""
} |
q175420 | WFSController.httpHandler | test | @RequestMapping("**")
public void httpHandler(HttpServletRequest hsreq, HttpServletResponse hsres) {
try {
PrintWriter wr = hsres.getWriter();
List<String> paramNames = new LinkedList<String>();
Enumeration<String> paramNamesE = hsreq.getParameterNames();
while(paramNamesE.hasMoreElements()) paramNames.add(paramNamesE.nextElement());
// Prepare parameters
String request = null;
String version = null;
String service = null;
String typeNames = null;
String datasetReqPath = null;
String actualPath = null;
String actualFTName = null;
NetcdfDataset dataset = null;
if(hsreq.getServletPath().length() > 4) {
datasetReqPath = hsreq.getServletPath().substring(4, hsreq.getServletPath().length());
}
actualPath = TdsRequestedDataset.getLocationFromRequestPath(datasetReqPath);
if(actualPath != null) dataset = NetcdfDataset.openDataset(actualPath);
else return;
List<CoordinateSystem> csList = dataset.getCoordinateSystems();
SimpleGeometryCSBuilder cs = new SimpleGeometryCSBuilder(dataset, csList.get(0), null);
/* Look for parameter names to assign values
* in order to avoid casing issues with parameter names (such as a mismatch between reQUEST and request and REQUEST).
*/
for(String paramName : paramNames) {
if(paramName.equalsIgnoreCase("REQUEST")) {
request = hsreq.getParameter(paramName);
}
if(paramName.equalsIgnoreCase("VERSION")) {
version = hsreq.getParameter(paramName);
}
if(paramName.equalsIgnoreCase("SERVICE")) {
service = hsreq.getParameter(paramName);
}
if(paramName.equalsIgnoreCase("TYPENAMES") || paramName.equalsIgnoreCase("TYPENAME")) {
typeNames = hsreq.getParameter(paramName);
// Remove namespace header for getFeature
if(typeNames != null) if(typeNames.length() > TDSNAMESPACE.length()) {
actualFTName = typeNames.substring(TDSNAMESPACE.length() + 1, typeNames.length());
}
}
}
WFSExceptionWriter paramError = checkParametersForError(request, version, service, typeNames);
WFSExceptionWriter requestProcessingError = null;
// If parameter checks all pass launch the request
if(paramError == null) {
WFSRequestType reqToProc = WFSRequestType.getWFSRequestType(request);
switch(reqToProc) {
case GetCapabilities:
getCapabilities(wr, hsreq, cs);
break;
case DescribeFeatureType:
describeFeatureType(wr, hsreq, actualFTName);
break;
case GetFeature:
requestProcessingError = getFeature(wr, hsreq, cs, actualFTName, typeNames);
break;
}
}
// Parameter checks did not all pass, print the error and return
else {
paramError.write(hsres);
return;
}
/* Specifically writes out exceptions that were incurred
* while processing requests.
*/
if(requestProcessingError != null){
requestProcessingError.write(hsres);
return;
}
}
catch(IOException io) {
throw new RuntimeException("The writer may not have been able to been have retrieved"
+ " or the requested dataset was not found", io);
}
} | java | {
"resource": ""
} |
q175421 | HttpDSP.getCapabilities | test | public String
getCapabilities(String url)
throws IOException
{
// Save the original url
String saveurl = this.xuri.getOriginal();
parseURL(url);
String fdsurl = buildURL(this.xuri.assemble(XURI.URLALL), DSRSUFFIX, null, null);
try {
// Make the request and return an input stream for accessing the databuffer
// Should fill in context bigendian and stream fields
InputStream stream = callServer(fdsurl);
// read the result, convert to string and return.
byte[] bytes = DapUtil.readbinaryfile(stream);
String document = new String(bytes, DapUtil.UTF8);
return document;
} finally {
parseURL(saveurl);
}
} | java | {
"resource": ""
} |
q175422 | CrawlableDatasetAmazonS3.length | test | @Override
public long length() {
// If the summary is already in the cache, return it.
// It'll have been added by a listDatasets() call on the parent directory.
S3ObjectSummary objectSummary = objectSummaryCache.getIfPresent(s3uri);
if (objectSummary != null) {
return objectSummary.getSize();
}
/* Get the metadata directly from S3. This will be expensive.
* We get punished hard if length() and/or lastModified() is called on a bunch of datasets without
* listDatasets() first being called on their parent directory.
*
* So, is the right thing to do here "getParentDataset().listDatasets()" and then query the cache again?
* Perhaps, but listDatasets() throws an IOException, and length() and lastModified() do not.
* We would have to change their signatures and the upstream client code to make it work.
*/
ObjectMetadata metadata = threddsS3Client.getObjectMetadata(s3uri);
if (metadata != null) {
return metadata.getContentLength();
} else {
// "this" may be a collection or non-existent. In both cases, we return 0.
return 0;
}
} | java | {
"resource": ""
} |
q175423 | CrawlableDatasetAmazonS3.lastModified | test | @Override
public Date lastModified() {
S3ObjectSummary objectSummary = objectSummaryCache.getIfPresent(s3uri);
if (objectSummary != null) {
return objectSummary.getLastModified();
}
ObjectMetadata metadata = threddsS3Client.getObjectMetadata(s3uri);
if (metadata != null) {
return metadata.getLastModified();
} else {
// "this" may be a collection or non-existent. In both cases, we return null.
return null;
}
} | java | {
"resource": ""
} |
q175424 | Generator.dataset | test | public void
dataset(DapDataset dmr)
throws DapException
{
// Iterate over the variables in order
for(DapVariable var : this.dmr.getTopVariables()) {
if(!this.ce.references(var))
continue;
variable(var);
}
} | java | {
"resource": ""
} |
q175425 | ServletUtil.returnFile | test | public static void returnFile(HttpServlet servlet, String contentPath, String path,
HttpServletRequest req, HttpServletResponse res, String contentType) throws IOException {
String filename = ServletUtil.formFilename(contentPath, path);
log.debug("returnFile(): returning file <" + filename + ">.");
// No file, nothing to view
if (filename == null) {
res.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
// dontallow ..
if (filename.contains("..")) {
res.sendError(HttpServletResponse.SC_FORBIDDEN);
return;
}
// dont allow access to WEB-INF or META-INF
String upper = filename.toUpperCase();
if (upper.contains("WEB-INF") || upper.contains("META-INF")) {
res.sendError(HttpServletResponse.SC_FORBIDDEN);
return;
}
returnFile(servlet, req, res, new File(filename), contentType);
} | java | {
"resource": ""
} |
q175426 | ServletUtil.returnString | test | public static void returnString(String contents, HttpServletResponse res)
throws IOException {
try {
ServletOutputStream out = res.getOutputStream();
IO.copy(new ByteArrayInputStream(contents.getBytes(CDM.utf8Charset)), out);
} catch (IOException e) {
log.error(" IOException sending string: ", e);
res.sendError(HttpServletResponse.SC_NOT_FOUND, "Problem sending string: " + e.getMessage());
}
} | java | {
"resource": ""
} |
q175427 | ServletUtil.setResponseContentLength | test | public static int setResponseContentLength(HttpServletResponse response, String s) throws UnsupportedEncodingException {
int length = s.getBytes(response.getCharacterEncoding()).length;
response.setContentLength(length);
return length;
} | java | {
"resource": ""
} |
q175428 | ServletUtil.getRequestURI | test | public static URI getRequestURI(HttpServletRequest req) {
try {
return new URI(getRequestBase(req));
} catch (URISyntaxException e) {
e.printStackTrace();
return null;
}
} | java | {
"resource": ""
} |
q175429 | ServletUtil.getRequestPath | test | public static String getRequestPath(HttpServletRequest req) {
StringBuilder buff = new StringBuilder();
if (req.getServletPath() != null)
buff.append(req.getServletPath());
if (req.getPathInfo() != null)
buff.append(req.getPathInfo());
return buff.toString();
} | java | {
"resource": ""
} |
q175430 | ServletUtil.getRequest | test | public static String getRequest(HttpServletRequest req) {
String query = req.getQueryString();
return getRequestBase(req) + (query == null ? "" : "?" + query);
} | java | {
"resource": ""
} |
q175431 | ServletUtil.getParameterIgnoreCase | test | public static String getParameterIgnoreCase(HttpServletRequest req, String paramName) {
Enumeration e = req.getParameterNames();
while (e.hasMoreElements()) {
String s = (String) e.nextElement();
if (s.equalsIgnoreCase(paramName))
return req.getParameter(s);
}
return null;
} | java | {
"resource": ""
} |
q175432 | CatalogChooser.save | test | public void save() {
if (catListBox != null) catListBox.save();
if (prefs != null) {
if (fileChooser != null)
fileChooser.save();
if (catgenFileChooser != null)
catgenFileChooser.save();
prefs.putInt(HDIVIDER, split.getDividerLocation());
}
} | java | {
"resource": ""
} |
q175433 | HtmlWriting.writeDirectory | test | public int writeDirectory(HttpServletResponse res, File dir, String path) throws IOException {
// error checking
if (dir == null) {
res.sendError(HttpServletResponse.SC_NOT_FOUND);
return 0;
}
if (!dir.exists() || !dir.isDirectory()) {
res.sendError(HttpServletResponse.SC_NOT_FOUND);
return 0;
}
// Get directory as HTML
String dirHtmlString = getDirectory(path, dir);
thredds.servlet.ServletUtil.setResponseContentLength(res, dirHtmlString);
res.setContentType(ContentType.html.getContentHeader());
PrintWriter writer = res.getWriter();
writer.write(dirHtmlString);
writer.flush();
return dirHtmlString.length();
} | java | {
"resource": ""
} |
q175434 | BitCounterUncompressed.setBitOffset | test | public void setBitOffset(DataDescriptor dkey) {
if (bitPosition == null)
bitPosition = new HashMap<DataDescriptor, Integer>(2 * parent.getSubKeys().size());
bitPosition.put(dkey, bitOffset);
bitOffset += dkey.getBitWidth();
} | java | {
"resource": ""
} |
q175435 | BitCounterUncompressed.makeNested | test | public BitCounterUncompressed makeNested(DataDescriptor subKey, int n, int row, int replicationCountSize) {
if (subCounters == null)
subCounters = new HashMap<DataDescriptor, BitCounterUncompressed[]>(5); // assumes DataDescriptor.equals is ==
BitCounterUncompressed[] subCounter = subCounters.get(subKey);
if (subCounter == null) {
subCounter = new BitCounterUncompressed[nrows]; // one for each row in this table
subCounters.put(subKey, subCounter);
}
BitCounterUncompressed rc = new BitCounterUncompressed(subKey, n, replicationCountSize);
subCounter[row] = rc;
return rc;
} | java | {
"resource": ""
} |
q175436 | BitCounterUncompressed.countBits | test | int countBits(int startBit) {
countBits = replicationCountSize;
this.startBit = new int[nrows];
for (int i=0; i<nrows; i++) {
this.startBit[i] = startBit + countBits;
if (debug) System.out.println(" BitCounterUncompressed row "+i+" startBit="+ this.startBit[i]);
for (DataDescriptor nd : parent.subKeys) {
BitCounterUncompressed[] bitCounter = (subCounters == null) ? null : subCounters.get(nd);
if (bitCounter == null) // a regular field
countBits += nd.getBitWidth();
else {
if (debug) System.out.println(" ---------> nested "+nd.getFxyName()+" starts at ="+ (startBit + countBits));
countBits += bitCounter[i].countBits(startBit + countBits);
if (debug) System.out.println(" <--------- nested "+nd.getFxyName()+" ends at ="+ (startBit + countBits));
}
}
}
return countBits;
} | java | {
"resource": ""
} |
q175437 | TextHistoryPane.appendLine | test | public void appendLine( String line) {
if (count >= nlines) {
try {
int remove = Math.max(removeIncr, count - nlines); // nlines may have changed
int offset = ta.getLineEndOffset( remove);
ta.replaceRange( "", 0, offset);
} catch (Exception e) {
log.error("Problem in TextHistoryPane", e);
}
count = nlines - removeIncr;
}
ta.append(line);
ta.append("\n");
count++;
// scroll to end
ta.setCaretPosition(ta.getText().length());
} | java | {
"resource": ""
} |
q175438 | FeatureDatasetCapabilitiesWriter.makeStationCollectionDocument | test | public Document makeStationCollectionDocument(LatLonRect bb, String[] names) throws IOException {
List<DsgFeatureCollection> list = fdp.getPointFeatureCollectionList();
DsgFeatureCollection fc = list.get(0); // LOOK maybe should pass in the dsg?
if (!(fc instanceof StationTimeSeriesFeatureCollection)) {
throw new UnsupportedOperationException(fc.getClass().getName() + " not a StationTimeSeriesFeatureCollection");
}
StationTimeSeriesFeatureCollection sobs = (StationTimeSeriesFeatureCollection) fc;
Element rootElem = new Element("stationCollection");
Document doc = new Document(rootElem);
List<StationFeature> stations;
if (bb != null)
stations = sobs.getStationFeatures(bb);
else if (names != null)
stations = sobs.getStationFeatures(Arrays.asList(names));
else
stations = sobs.getStationFeatures();
for (Station s : stations) {
Element sElem = new Element("station");
sElem.setAttribute("name", s.getName());
if (s.getWmoId() != null)
sElem.setAttribute("wmo_id", s.getWmoId());
if ((s.getDescription() != null) && (s.getDescription().length() > 0))
sElem.addContent(new Element("description").addContent(s.getDescription()));
sElem.addContent(new Element("longitude").addContent(Double.toString(s.getLongitude())));
sElem.addContent(new Element("latitide").addContent(Double.toString(s.getLatitude())));
if (!Double.isNaN(s.getAltitude()))
sElem.addContent(new Element("altitude").addContent(Double.toString(s.getAltitude())));
rootElem.addContent(sElem);
}
return doc;
} | java | {
"resource": ""
} |
q175439 | FeatureDatasetCapabilitiesWriter.getCapabilitiesDocument | test | public Document getCapabilitiesDocument() {
Element rootElem = new Element("capabilities");
Document doc = new Document(rootElem);
if (null != path) {
rootElem.setAttribute("location", path);
Element elem = new Element("featureDataset");
FeatureType ft = fdp.getFeatureType();
elem.setAttribute("type", ft.toString().toLowerCase());
String url = path.replace("dataset.xml", ft.toString().toLowerCase() + ".xml");
elem.setAttribute("url", url);
rootElem.addContent(elem);
}
List<DsgFeatureCollection> list = fdp.getPointFeatureCollectionList();
DsgFeatureCollection fc = list.get(0); // LOOK maybe should pass in the dsg?
rootElem.addContent(writeTimeUnit(fc.getTimeUnit()));
rootElem.addContent(new Element("AltitudeUnits").addContent(fc.getAltUnits()));
// data variables
List<? extends VariableSimpleIF> vars = fdp.getDataVariables();
Collections.sort(vars);
for (VariableSimpleIF v : vars) {
rootElem.addContent(writeVariable(v));
}
/* CollectionInfo info;
try {
info = new DsgCollectionHelper(fc).calcBounds();
} catch (IOException e) {
throw new RuntimeException(e);
} */
LatLonRect bb = fc.getBoundingBox();
if (bb != null)
rootElem.addContent(writeBoundingBox(bb));
// add date range
CalendarDateRange dateRange = fc.getCalendarDateRange();
if (dateRange != null) {
Element drElem = new Element("TimeSpan"); // from KML
drElem.addContent(new Element("begin").addContent(dateRange.getStart().toString()));
drElem.addContent(new Element("end").addContent(dateRange.getEnd().toString()));
if (dateRange.getResolution() != null)
drElem.addContent(new Element("resolution").addContent(dateRange.getResolution().toString()));
rootElem.addContent(drElem);
}
/* add accept list
Element elem = new Element("AcceptList");
//elem.addContent(new Element("accept").addContent("raw"));
elem.addContent(new Element("accept").addContent("csv").setAttribute("displayName", "csv"));
elem.addContent(new Element("accept").addContent("text/csv").setAttribute("displayName", "csv (file)"));
elem.addContent(new Element("accept").addContent("xml").setAttribute("displayName", "xml"));
elem.addContent(new Element("accept").addContent("text/xml").setAttribute("displayName", "xml (file)"));
elem.addContent(new Element("accept").addContent("waterml2").setAttribute("displayName", "WaterML 2.0"));
elem.addContent(new Element("accept").addContent("netcdf").setAttribute("displayName", "CF/NetCDF-3"));
//elem.addContent(new Element("accept").addContent("ncstream"));
rootElem.addContent(elem); */
return doc;
} | java | {
"resource": ""
} |
q175440 | VariableIndex.getRecordAt | test | @Nullable
synchronized Record getRecordAt(SubsetParams coords) {
int[] want = new int[getRank()];
int count = 0;
int runIdx = -1;
for (Coordinate coord : getCoordinates()) {
int idx = -1;
switch (coord.getType()) {
case runtime:
CalendarDate runtimeCooord = coords.getRunTime();
idx = coord.getIndex(runtimeCooord);
runIdx = idx;
break;
case timeIntv:
double[] timeIntv = coords.getTimeOffsetIntv();
idx = coord.getIndex(new TimeCoordIntvValue((int) timeIntv[0], (int) timeIntv[1]));
break;
case time:
Double timeOffset = coords.getTimeOffset(); // Double
int coordInt = timeOffset.intValue();
idx = coord.getIndex(coordInt);
break;
case time2D:
timeIntv = coords.getTimeOffsetIntv();
if (timeIntv != null) {
TimeCoordIntvValue coordTinv = new TimeCoordIntvValue((int) timeIntv[0], (int) timeIntv[1]);
idx = ((CoordinateTime2D) coord).findTimeIndexFromVal(runIdx, coordTinv); // LOOK can only use if orthogonal
break;
}
Double timeCoord = coords.getTimeOffset();
if (timeCoord != null) {
coordInt = timeCoord.intValue();
idx = ((CoordinateTime2D) coord).findTimeIndexFromVal(runIdx, coordInt);
break;
}
// the OneTime case
CoordinateTime2D coord2D = (CoordinateTime2D) coord;
if (coord2D.getNtimes() == 1) {
idx = 0;
break;
}
throw new IllegalStateException("time2D must have timeOffset ot timeOffsetIntv coordinare");
case vert:
double[] vertIntv = coords.getVertCoordIntv();
if (vertIntv != null) {
VertCoordValue coordVert = new VertCoordValue(vertIntv[0], vertIntv[1]);
idx = coord.getIndex(coordVert);
break;
}
Double vertCoord = coords.getVertCoord();
if (vertCoord != null) {
VertCoordValue coordVert = new VertCoordValue(vertCoord);
idx = coord.getIndex(coordVert);
}
break;
case ens:
Double ensVal = coords.getEnsCoord();
idx = ((CoordinateEns) coord).getIndexByMember(ensVal);
break;
default:
logger.warn("GribCollectionImmutable: missing CoordVal for {}%n", coord.getName());
}
if (idx < 0) {
logger.debug("Cant find index for value in axis {} in variable {}", coord.getName(), name);
return null;
}
want[count++] = idx;
}
return sa.getContent(want);
} | java | {
"resource": ""
} |
q175441 | VariableIndex.getCoordinate | test | public Coordinate getCoordinate(int index) {
int grpIndex = coordIndex.get(index);
return group.coords.get(grpIndex);
} | java | {
"resource": ""
} |
q175442 | ComboBox.addItem | test | public void addItem( Object item) {
if (item == null) return;
for (int i=0; i<getItemCount(); i++) {
if (item.equals( getItemAt(i))) {
if (i == 0) {
setSelectedIndex(0);
return; // already there
}
removeItemAt(i);
}
}
// add as first in the list
insertItemAt( item, 0);
setSelectedIndex(0);
} | java | {
"resource": ""
} |
q175443 | TdsErrorHandling.handle | test | @ExceptionHandler(Throwable.class)
public ResponseEntity<String> handle(Throwable ex) throws Throwable {
// If the exception is annotated with @ResponseStatus rethrow it and let
// the framework handle it - like the OrderNotFoundException example
// at the start of this post.
// AnnotationUtils is a Spring Framework utility class.
// see https://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc
if (AnnotationUtils.findAnnotation(ex.getClass(), ResponseStatus.class) != null)
throw ex;
logger.error("uncaught exception", ex);
// ex.printStackTrace(); // temporary - remove in production
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentType(MediaType.TEXT_PLAIN);
String msg = ex.getMessage();
StringWriter sw = new StringWriter();
PrintWriter p = new PrintWriter(sw);
ex.printStackTrace(p);
p.close();
sw.close();
msg = sw.toString();
return new ResponseEntity<>("Throwable exception handled : " + htmlEscape(msg), responseHeaders, HttpStatus.INTERNAL_SERVER_ERROR);
} | java | {
"resource": ""
} |
q175444 | Odometer.slice | test | public Slice
slice(int i)
{
if(i < 0 || i >= this.rank)
throw new IllegalArgumentException();
return this.slices.get(i);
} | java | {
"resource": ""
} |
q175445 | Odometer.step | test | public int
step(int firstpos, int lastpos)
{
for(int i = lastpos - 1; i >= firstpos; i--) { // walk backwards
if(this.index.indices[i] > this.endpoint[i])
this.index.indices[i] = this.slices.get(i).getFirst(); // reset this position
else {
this.index.indices[i] += this.slices.get(i).getStride(); // move to next indices
return i;
}
}
return -1;
} | java | {
"resource": ""
} |
q175446 | NcepTables.getNcepGenProcess | test | @Nullable
public static Map<Integer, String> getNcepGenProcess() {
if (genProcessMap != null) return genProcessMap;
String path = "resources/grib1/ncep/ncepTableA.xml";
try (InputStream is = GribResourceReader.getInputStream(path)) {
SAXBuilder builder = new SAXBuilder();
org.jdom2.Document doc = builder.build(is);
Element root = doc.getRootElement();
HashMap<Integer, String> result = new HashMap<>(200);
List<Element> params = root.getChildren("parameter");
for (Element elem1 : params) {
int code = Integer.parseInt(elem1.getAttributeValue("code"));
String desc = elem1.getChildText("description");
result.put(code, desc);
}
return Collections.unmodifiableMap(result); // all at once - thread safe
} catch (IOException | JDOMException ioe) {
logger.error("Cant read NCEP Table 1 = " + path, ioe);
return null;
}
} | java | {
"resource": ""
} |
q175447 | CdmrFeatureDataset.isCdmrfEndpoint | test | public static FeatureType isCdmrfEndpoint(String endpoint) throws IOException {
HTTPSession httpClient = HTTPFactory.newSession(endpoint);
String url = endpoint + "?req=featureType";
// get the header
try (HTTPMethod method = HTTPFactory.Get(httpClient, url)) {
method.setFollowRedirects(true);
int statusCode = method.execute();
if (statusCode != 200) return null;
String content = method.getResponseAsString();
return FeatureType.getType(content);
} catch (Throwable t) {
t.printStackTrace();
return null;
}
} | java | {
"resource": ""
} |
q175448 | OptSwitch.SetHasValue | test | public void SetHasValue(int type) {
this.type = type;
if (debug) {
System.out.println("sw = " + (char) sw + "; type = " + type +
"; set = " + set + "; val = " + val);
}
} | java | {
"resource": ""
} |
q175449 | Grib1GdsPredefined.factory | test | public static Grib1Gds factory(int center, int gridNumber) {
if (center == 7) {
return factoryNCEP(gridNumber);
} else
throw new IllegalArgumentException("Dont have predefined GDS " + gridNumber + " from " + center);
} | java | {
"resource": ""
} |
q175450 | IO.copyB | test | static public long copyB(InputStream in, OutputStream out, int bufferSize) throws IOException {
long totalBytesRead = 0;
int done = 0, next = 1;
byte[] buffer = new byte[bufferSize];
while (true) {
int n = in.read(buffer);
if (n == -1) break;
out.write(buffer, 0, n);
totalBytesRead += n;
if (showCopy) {
done += n;
if (done > 1000 * 1000 * next) {
System.out.println(next + " Mb");
next++;
}
}
}
out.flush();
return totalBytesRead;
} | java | {
"resource": ""
} |
q175451 | IO.readContents | test | static public String readContents(InputStream is, String charset) throws IOException {
ByteArrayOutputStream bout = new ByteArrayOutputStream(10 * default_file_buffersize);
IO.copy(is, bout);
return bout.toString(charset);
} | java | {
"resource": ""
} |
q175452 | IO.readContentsToByteArray | test | static public byte[] readContentsToByteArray(InputStream is) throws IOException {
ByteArrayOutputStream bout = new ByteArrayOutputStream(10 * default_file_buffersize);
IO.copy(is, bout);
return bout.toByteArray();
} | java | {
"resource": ""
} |
q175453 | IO.writeContents | test | static public void writeContents(String contents, OutputStream os) throws IOException {
ByteArrayInputStream bin = new ByteArrayInputStream(contents.getBytes(CDM.utf8Charset));
IO.copy(bin, os);
} | java | {
"resource": ""
} |
q175454 | IO.copyFileB | test | static public void copyFileB(File fileIn, OutputStream out, int bufferSize) throws IOException {
try (FileInputStream fin = new FileInputStream(fileIn)) {
InputStream in = new BufferedInputStream(fin);
IO.copyB(in, out, bufferSize);
}
} | java | {
"resource": ""
} |
q175455 | IO.copyRafB | test | static public long copyRafB(ucar.unidata.io.RandomAccessFile raf, long offset, long length, OutputStream out, byte[] buffer) throws IOException {
int bufferSize = buffer.length;
long want = length;
raf.seek(offset);
while (want > 0) {
int len = (int) Math.min(want, bufferSize);
int bytesRead = raf.read(buffer, 0, len);
if (bytesRead <= 0) break;
out.write(buffer, 0, bytesRead);
want -= bytesRead;
}
out.flush();
return length - want;
} | java | {
"resource": ""
} |
q175456 | IO.copyDirTree | test | static public void copyDirTree(String fromDirName, String toDirName) throws IOException {
File fromDir = new File(fromDirName);
File toDir = new File(toDirName);
if (!fromDir.exists())
return;
if (!toDir.exists()) {
if (!toDir.mkdirs()) {
throw new IOException("Could not create directory: " + toDir);
}
}
File[] files = fromDir.listFiles();
if (files != null)
for (File f : files) {
if (f.isDirectory())
copyDirTree(f.getAbsolutePath(), toDir.getAbsolutePath() + "/" + f.getName());
else
copyFile(f.getAbsolutePath(), toDir.getAbsolutePath() + "/" + f.getName());
}
} | java | {
"resource": ""
} |
q175457 | IO.readFileToByteArray | test | static public byte[] readFileToByteArray(String filename) throws IOException {
try (FileInputStream fin = new FileInputStream(filename)) {
InputStream in = new BufferedInputStream(fin);
return readContentsToByteArray(in);
}
} | java | {
"resource": ""
} |
q175458 | IO.readFile | test | static public String readFile(String filename) throws IOException {
try (FileInputStream fin = new FileInputStream(filename)) {
InputStreamReader reader = new InputStreamReader(fin, CDM.utf8Charset);
StringWriter swriter = new StringWriter(50000);
UnsynchronizedBufferedWriter writer = new UnsynchronizedBufferedWriter(swriter);
writer.write(reader);
return swriter.toString();
}
} | java | {
"resource": ""
} |
q175459 | IO.writeToFile | test | static public void writeToFile(String contents, File file) throws IOException {
try (FileOutputStream fout = new FileOutputStream(file)) {
OutputStreamWriter fw = new OutputStreamWriter(fout, CDM.utf8Charset);
UnsynchronizedBufferedWriter writer = new UnsynchronizedBufferedWriter(fw);
writer.write(contents);
writer.flush();
}
} | java | {
"resource": ""
} |
q175460 | IO.writeToFile | test | static public void writeToFile(String contents, String fileOutName) throws IOException {
writeToFile(contents, new File(fileOutName));
} | java | {
"resource": ""
} |
q175461 | IO.writeToFile | test | static public long writeToFile(InputStream in, String fileOutName) throws IOException {
try (FileOutputStream fout = new FileOutputStream( fileOutName)) {
OutputStream out = new BufferedOutputStream(fout);
return IO.copy(in, out);
} finally {
if (null != in) in.close();
}
} | java | {
"resource": ""
} |
q175462 | DTSServlet.parseExceptionHandler | test | public void parseExceptionHandler(ParseException pe, HttpServletResponse response)
{
//log.error("DODSServlet.parseExceptionHandler", pe);
if(Debug.isSet("showException")) {
log.error(pe.toString());
printThrowable(pe);
}
try {
BufferedOutputStream eOut = new BufferedOutputStream(response.getOutputStream());
response.setHeader("Content-Description", "dods-error");
// This should probably be set to "plain" but this works, the
// C++ slients don't barf as they would if I sent "plain" AND
// the C++ don't expect compressed data if I do this...
response.setHeader("Content-Encoding", "");
// response.setContentType("text/plain");
// Strip any double quotes out of the parser error message.
// These get stuck in auto-magically by the javacc generated parser
// code and they break our error parser (bummer!)
String msg = pe.getMessage().replace('\"', '\'');
DAP2Exception de2 = new DAP2Exception(opendap.dap.DAP2Exception.CANNOT_READ_FILE, msg);
de2.print(eOut);
} catch (IOException ioe) {
log.error("Cannot respond to client! IO Error: " + ioe.getMessage());
}
} | java | {
"resource": ""
} |
q175463 | DTSServlet.dap2ExceptionHandler | test | public void dap2ExceptionHandler(DAP2Exception de, HttpServletResponse response)
{
//log.info("DODSServlet.dodsExceptionHandler (" + de.getErrorCode() + ") " + de.getErrorMessage());
if(Debug.isSet("showException")) {
log.error(de.toString());
de.printStackTrace();
printDODSException(de);
}
// Convert Dap2Excaption code to an HttpCode
switch (de.getErrorCode()) {
case DAP2Exception.NO_SUCH_FILE:
case DAP2Exception.CANNOT_READ_FILE:
response.setStatus(HttpStatus.SC_NOT_FOUND);
break;
case DAP2Exception.NO_AUTHORIZATION:
response.setStatus(HttpStatus.SC_UNAUTHORIZED);
break;
case DAP2Exception.NO_SUCH_VARIABLE:
case DAP2Exception.MALFORMED_EXPR:
case DAP2Exception.UNKNOWN_ERROR: // fall thru
default:
response.setStatus(HttpStatus.SC_BAD_REQUEST);
break;
}
try {
BufferedOutputStream eOut = new BufferedOutputStream(response.getOutputStream());
response.setHeader("Content-Description", "dods-error");
// This should probably be set to "plain" but this works, the
// C++ slients don't barf as they would if I sent "plain" AND
// the C++ don't expect compressed data if I do this...
response.setHeader("Content-Encoding", "");
de.print(eOut);
} catch (IOException ioe) {
log.error("Cannot respond to client! IO Error: " + ioe.getMessage());
}
} | java | {
"resource": ""
} |
q175464 | DTSServlet.badURL | test | public void badURL(HttpServletRequest request, HttpServletResponse response)
throws Exception
{
if(Debug.isSet("showResponse")) {
log.debug("Sending Bad URL Page.");
}
//log.info("DODSServlet.badURL " + rs.getRequest().getRequestURI());
response.setContentType("text/html");
response.setHeader("XDODS-Server", getServerVersion());
response.setHeader("Content-Description", "dods-error");
// Commented because of a bug in the OPeNDAP C++ stuff...
//rs.getResponse().setHeader("Content-Encoding", "plain");
PrintWriter pw = new PrintWriter(new OutputStreamWriter(response.getOutputStream(), Util.UTF8));
printBadURLPage(pw);
printHelpPage(pw);
pw.flush();
response.setStatus(HttpServletResponse.SC_OK);
} | java | {
"resource": ""
} |
q175465 | DTSServlet.doGetCatalog | test | public void doGetCatalog(ReqState rs)
throws Exception
{
rs.getResponse().setHeader("XDODS-Server", getServerVersion());
rs.getResponse().setContentType("text/xml");
rs.getResponse().setHeader("Content-Description", "dods-catalog");
PrintWriter pw = new PrintWriter(new OutputStreamWriter(rs.getResponse().getOutputStream(), Util.UTF8));
printCatalog(rs, pw);
pw.flush();
rs.getResponse().setStatus(HttpServletResponse.SC_OK);
} | java | {
"resource": ""
} |
q175466 | DTSServlet.printCatalog | test | protected void printCatalog(ReqState rs, PrintWriter os)
throws IOException
{
os.println("Catalog not available for this server");
os.println("Server version = " + getServerVersion());
} | java | {
"resource": ""
} |
q175467 | DTSServlet.printStatus | test | protected void printStatus(PrintWriter os)
{
os.println("<h2>Server version = " + getServerVersion() + "</h2>");
os.println("<h2>Number of Requests Received = " + HitCounter + "</h2>");
if(track) {
int n = prArr.size();
int pending = 0;
StringBuilder preqs = new StringBuilder();
for(int i = 0; i < n; i++) {
ReqState rs = (ReqState) prArr.get(i);
RequestDebug reqD = (RequestDebug) rs.getUserObject();
if(!reqD.done) {
preqs.append("<pre>-----------------------\n");
preqs.append("Request[");
preqs.append(reqD.reqno);
preqs.append("](");
preqs.append(reqD.threadDesc);
preqs.append(") is pending.\n");
preqs.append(rs.toString());
preqs.append("</pre>");
pending++;
}
}
os.println("<h2>" + pending + " Pending Request(s)</h2>");
os.println(preqs.toString());
}
} | java | {
"resource": ""
} |
q175468 | DTSServlet.printBadURLPage | test | private void printBadURLPage(PrintWriter pw)
{
pw.println("<h3>Error in URL</h3>");
pw.println("The URL extension did not match any that are known by this");
pw.println("server. Below is a list of the five extensions that are be recognized by");
pw.println("all OPeNDAP servers. If you think that the server is broken (that the URL you");
pw.println("submitted should have worked), then please contact the");
pw.println("OPeNDAP user support coordinator at: ");
pw.println("<a href=\"mailto:support@unidata.ucar.edu\">support@unidata.ucar.edu</a><p>");
} | java | {
"resource": ""
} |
q175469 | Grib2SectionIdentification.getReferenceDate | test | public CalendarDate getReferenceDate() {
return CalendarDate.of(null, year, month, day, hour, minute, second);
} | java | {
"resource": ""
} |
q175470 | NcStreamIosp.readVlenData | test | private Array readVlenData(Variable v, Section section, DataStorage dataStorage) throws IOException, InvalidRangeException {
raf.seek(dataStorage.filePos);
int nelems = readVInt(raf);
Array[] result = new Array[nelems];
for (int elem = 0; elem < nelems; elem++) {
int dsize = readVInt(raf);
byte[] data = new byte[dsize];
raf.readFully(data);
Array dataArray = Array.factory(v.getDataType(), (int[]) null, ByteBuffer.wrap(data));
result[elem] = dataArray;
}
// return Array.makeObjectArray(v.getDataType(), result[0].getClass(), new int[]{nelems}, result);
return Array.makeVlenArray(new int[]{nelems}, result);
//return dataArray.section(section.getRanges());
} | java | {
"resource": ""
} |
q175471 | NcmlCollectionReader.readNcML | test | static public NcmlCollectionReader readNcML(String ncmlString, Formatter errlog) throws IOException {
StringReader reader = new StringReader(ncmlString);
org.jdom2.Document doc;
try {
SAXBuilder builder = new SAXBuilder();
if (debugURL) System.out.println(" NetcdfDataset NcML String = <" + ncmlString + ">");
doc = builder.build(new StringReader(ncmlString));
} catch (JDOMException e) {
throw new IOException(e.getMessage());
}
if (debugXML) System.out.println(" SAXBuilder done");
return readXML(doc, errlog, null);
} | java | {
"resource": ""
} |
q175472 | NcmlCollectionReader.open | test | static public NcmlCollectionReader open(String ncmlLocation, Formatter errlog) throws IOException {
if (!ncmlLocation.startsWith("http:") && !ncmlLocation.startsWith("file:"))
ncmlLocation = "file:" + ncmlLocation;
URL url = new URL(ncmlLocation);
org.jdom2.Document doc;
try {
SAXBuilder builder = new SAXBuilder();
if (debugURL) System.out.println(" NetcdfDataset URL = <" + url + ">");
doc = builder.build(url);
} catch (JDOMException e) {
throw new IOException(e.getMessage());
}
if (debugXML) System.out.println(" SAXBuilder done");
return readXML(doc, errlog, ncmlLocation);
} | java | {
"resource": ""
} |
q175473 | StringUtil2.allow | test | static public String allow(String x, String allowChars, char replaceChar) {
boolean ok = true;
for (int pos = 0; pos < x.length(); pos++) {
char c = x.charAt(pos);
if (!(Character.isLetterOrDigit(c) || (0 <= allowChars.indexOf(c)))) {
ok = false;
break;
}
}
if (ok)
return x;
// gotta do it
StringBuilder sb = new StringBuilder(x);
for (int pos = 0; pos < sb.length(); pos++) {
char c = sb.charAt(pos);
if (Character.isLetterOrDigit(c) || (0 <= allowChars.indexOf(c))) {
continue;
}
sb.setCharAt(pos, replaceChar);
}
return sb.toString();
} | java | {
"resource": ""
} |
q175474 | StringUtil2.cleanup | test | public static String cleanup(byte[] h) {
byte[] bb = new byte[h.length];
int count = 0;
for (byte b : h) {
if (b >= 32 && b < 127)
bb[count++] = b;
}
return new String(bb, 0, count, CDM.utf8Charset);
} | java | {
"resource": ""
} |
q175475 | StringUtil2.filter | test | static public String filter(String x, String okChars) {
boolean ok = true;
for (int pos = 0; pos < x.length(); pos++) {
char c = x.charAt(pos);
if (!(Character.isLetterOrDigit(c) || (0 <= okChars.indexOf(c)))) {
ok = false;
break;
}
}
if (ok) {
return x;
}
// gotta do it
StringBuilder sb = new StringBuilder(x.length());
for (int pos = 0; pos < x.length(); pos++) {
char c = x.charAt(pos);
if (Character.isLetterOrDigit(c) || (0 <= okChars.indexOf(c))) {
sb.append(c);
}
}
return sb.toString();
} | java | {
"resource": ""
} |
q175476 | StringUtil2.filter7bits | test | static public String filter7bits(String s) {
if (s == null) return null;
char[] bo = new char[s.length()];
int count = 0;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if ((c < 128) && (c > 31) || ((c == '\n') || (c == '\t'))) {
bo[count++] = c;
}
}
return new String(bo, 0, count);
} | java | {
"resource": ""
} |
q175477 | StringUtil2.makeValidCdmObjectName | test | static public String makeValidCdmObjectName(String name) {
name = name.trim();
// common case no change
boolean ok = true;
for (int i = 0; i < name.length(); i++) {
int c = name.charAt(i);
if (c < 0x20) ok = false;
if (c == '/') ok = false;
if (c == ' ') ok = false;
if (!ok) break;
}
if (ok) return name;
StringBuilder sbuff = new StringBuilder(name.length());
for (int i = 0, len = name.length(); i < len; i++) {
int c = name.charAt(i);
if ((c == '/') || (c == ' '))
sbuff.append('_');
else if (c >= 0x20)
sbuff.append((char) c);
}
return sbuff.toString();
} | java | {
"resource": ""
} |
q175478 | StringUtil2.match | test | static public int match(String s1, String s2) {
int i = 0;
while ((i < s1.length()) && (i < s2.length())) {
if (s1.charAt(i) != s2.charAt(i)) {
break;
}
i++;
}
return i;
} | java | {
"resource": ""
} |
q175479 | StringUtil2.padLeft | test | public static String padLeft(String s, int desiredLength,
String padString) {
while (s.length() < desiredLength) {
s = padString + s;
}
return s;
} | java | {
"resource": ""
} |
q175480 | StringUtil2.padRight | test | public static String padRight(String s, int desiredLength,
String padString) {
StringBuilder ret = new StringBuilder(s);
while (ret.length() < desiredLength) {
ret.append(padString);
}
return ret.toString();
} | java | {
"resource": ""
} |
q175481 | StringUtil2.remove | test | static public String remove(String s, String sub) {
int len = sub.length();
int pos;
while (0 <= (pos = s.indexOf(sub))) {
s = s.substring(0, pos) + s.substring(pos + len);
}
return s;
} | java | {
"resource": ""
} |
q175482 | StringUtil2.remove | test | static public String remove(String s, int c) {
if (0 > s.indexOf(c)) { // none
return s;
}
StringBuilder buff = new StringBuilder(s);
int i = 0;
while (i < buff.length()) {
if (buff.charAt(i) == c) {
buff.deleteCharAt(i);
} else {
i++;
}
}
return buff.toString();
} | java | {
"resource": ""
} |
q175483 | StringUtil2.removeFromEnd | test | static public String removeFromEnd(String s, int c) {
if (0 > s.indexOf(c)) // none
return s;
int len = s.length();
while ((s.charAt(len - 1) == c) && (len > 0))
len--;
if (len == s.length())
return s;
return s.substring(0, len);
} | java | {
"resource": ""
} |
q175484 | StringUtil2.collapseWhitespace | test | static public String collapseWhitespace(String s) {
int len = s.length();
StringBuilder b = new StringBuilder(len);
for (int i = 0; i < len; i++) {
char c = s.charAt(i);
if (!Character.isWhitespace(c)) {
b.append(c);
} else {
b.append(' ');
while ((i + 1 < len) && Character.isWhitespace(s.charAt(i + 1))) {
i++; /// skip further whitespace
}
}
}
return b.toString();
} | java | {
"resource": ""
} |
q175485 | StringUtil2.replace | test | static public String replace(String s, char out, String in) {
if (s.indexOf(out) < 0) {
return s;
}
// gotta do it
StringBuilder sb = new StringBuilder(s);
replace(sb, out, in);
return sb.toString();
} | java | {
"resource": ""
} |
q175486 | StringUtil2.replace | test | static public String replace(String x, char[] replaceChar, String[] replaceWith) {
// common case no replacement
boolean ok = true;
for (char aReplaceChar : replaceChar) {
int pos = x.indexOf(aReplaceChar);
ok = (pos < 0);
if (!ok)
break;
}
if (ok)
return x;
// gotta do it
StringBuilder sb = new StringBuilder(x);
for (int i = 0; i < replaceChar.length; i++) {
int pos = x.indexOf(replaceChar[i]);
if (pos >= 0) {
replace(sb, replaceChar[i], replaceWith[i]);
}
}
return sb.toString();
} | java | {
"resource": ""
} |
q175487 | StringUtil2.replace | test | public static String replace(String string, String pattern, String value) {
if (pattern.length() == 0)
return string;
if (!string.contains(pattern)) return string;
// ok gotta do it
StringBuilder returnValue = new StringBuilder();
int patternLength = pattern.length();
while (true) {
int idx = string.indexOf(pattern);
if (idx < 0)
break;
returnValue.append(string.substring(0, idx));
if (value != null)
returnValue.append(value);
string = string.substring(idx + patternLength);
}
returnValue.append(string);
return returnValue.toString();
} | java | {
"resource": ""
} |
q175488 | StringUtil2.substitute | test | static public String substitute(String original, String match, String subst) {
String s = original;
int pos;
while (0 <= (pos = s.indexOf(match))) {
StringBuilder sb = new StringBuilder(s);
s = sb.replace(pos, pos + match.length(), subst).toString();
}
return s;
} | java | {
"resource": ""
} |
q175489 | StringUtil2.substitute | test | static public String substitute(String original, String[] match, String[] subst) {
boolean ok = true;
for (String aMatch : match) {
if (original.contains(aMatch)) {
ok = false;
break;
}
}
if (ok) {
return original;
}
// gotta do it;
StringBuilder sb = new StringBuilder(original);
for (int i = 0; i < match.length; i++) {
substitute(sb, match[i], subst[i]);
}
return sb.toString();
} | java | {
"resource": ""
} |
q175490 | StringUtil2.remove | test | static public void remove(StringBuilder sb, String out) {
int i = 0;
while (i < sb.length()) {
int c = sb.charAt(i);
boolean ok = true;
for (int j = 0; j < out.length(); j++) {
if (out.charAt(j) == c) {
sb.delete(i, i + 1);
ok = false;
break;
}
}
if (ok) i++;
}
} | java | {
"resource": ""
} |
q175491 | StringUtil2.unreplace | test | static public void unreplace(StringBuilder sb, String out, char in) {
int pos;
while (0 <= (pos = sb.indexOf(out))) {
sb.setCharAt(pos, in);
sb.delete(pos + 1, pos + out.length());
}
} | java | {
"resource": ""
} |
q175492 | StringUtil2.replace | test | static public void replace(StringBuilder sb, String out, String in) {
for (int i = 0; i < sb.length(); i++) {
int c = sb.charAt(i);
for (int j = 0; j < out.length(); j++) {
if (out.charAt(j) == c)
sb.setCharAt(i, in.charAt(j));
}
}
} | java | {
"resource": ""
} |
q175493 | StringUtil2.substitute | test | static public void substitute(StringBuilder sbuff, String match, String subst) {
int pos, fromIndex = 0;
int substLen = subst.length();
int matchLen = match.length();
while (0 <= (pos = sbuff.indexOf(match, fromIndex))) {
sbuff.replace(pos, pos + matchLen, subst);
fromIndex = pos + substLen; // make sure dont get into an infinite loop
}
} | java | {
"resource": ""
} |
q175494 | StringUtil2.trim | test | static public String trim(String s, int bad) {
int len = s.length();
int st = 0;
while ((st < len) && (s.charAt(st) == bad)) {
st++;
}
while ((st < len) && (s.charAt(len - 1) == bad)) {
len--;
}
return ((st > 0) || (len < s.length())) ? s.substring(st, len) : s;
} | java | {
"resource": ""
} |
q175495 | InvDatasetFeatureCollection.processEvent | test | @Subscribe
public void processEvent(CollectionUpdateEvent event) {
if (!config.collectionName.equals(event.getCollectionName())) return; // not for me
try {
update(event.getType());
} catch (IOException e) {
logger.error("Error processing event", e);
}
} | java | {
"resource": ""
} |
q175496 | InvDatasetFeatureCollection.checkState | test | protected State checkState() throws IOException {
State localState;
synchronized (lock) {
if (first) {
firstInit();
updateCollection(state, config.updateConfig.updateType);
// makeDatasetTop(state);
first = false;
}
localState = state.copy();
}
return localState;
} | java | {
"resource": ""
} |
q175497 | InvDatasetFeatureCollection.update | test | protected void update(CollectionUpdateType force) throws IOException { // this may be called from a background thread, or from checkState() request thread
State localState;
synchronized (lock) {
if (first) {
state = checkState();
state.lastInvChange = System.currentTimeMillis();
return;
}
// do the update in a local object
localState = state.copy();
}
updateCollection(localState, force);
// makeDatasetTop(localState);
localState.lastInvChange = System.currentTimeMillis();
// switch to live
synchronized (lock) {
state = localState;
}
} | java | {
"resource": ""
} |
q175498 | Grib2ReportPanel.doUniqueTemplates | test | private void doUniqueTemplates(Formatter f, MCollection dcm, boolean useIndex) throws IOException {
f.format("Show Unique GDS and PDS templates%n");
Map<Integer, FileList> gdsSet = new HashMap<>();
Map<Integer, FileList> pdsSet = new HashMap<>();
Map<Integer, FileList> drsSet = new HashMap<>();
for (MFile mfile : dcm.getFilesSorted()) {
f.format(" %s%n", mfile.getPath());
doUniqueTemplates(mfile, gdsSet, pdsSet, drsSet, f);
}
List<FileList> sorted = new ArrayList<>(gdsSet.values());
Collections.sort(sorted);
for (FileList gdsl : sorted) {
f.format("%nGDS %s template= %d %n", gdsl.name, gdsl.template);
for (FileCount fc : gdsl.fileList) {
f.format(" %5d %s %n", fc.countRecords, fc.f.getPath());
}
}
List<FileList> sortedPds = new ArrayList<>(pdsSet.values());
Collections.sort(sortedPds);
for (FileList pdsl : sortedPds) {
f.format("%n===================================================%n");
f.format("%nPDS %s template= %d %n", pdsl.name, pdsl.template);
for (FileCount fc : pdsl.fileList) {
f.format(" %5d %s %n", fc.countRecords, fc.f.getPath());
}
}
List<FileList> sortedDrs = new ArrayList<>(drsSet.values());
Collections.sort(sortedDrs);
for (FileList pdsl : sortedDrs) {
f.format("%n===================================================%n");
f.format("%nDRS %s template= %d %n", pdsl.name, pdsl.template);
for (FileCount fc : pdsl.fileList) {
f.format(" %5d %s %n", fc.countRecords, fc.f.getPath());
}
}
} | java | {
"resource": ""
} |
q175499 | InvCatalogRef.getDatasets | test | @Override
public java.util.List<InvDataset> getDatasets() {
read();
return useProxy ? proxy.getDatasets() : super.getDatasets();
} | java | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.