001/* 002 * Copyright (c) 1998-2010 The Regents of the University of California. 003 * All rights reserved. 004 * 005 * '$Author: welker $' 006 * '$Date: 2010-05-06 05:21:26 +0000 (Thu, 06 May 2010) $' 007 * '$Revision: 24234 $' 008 * 009 * Permission is hereby granted, without written agreement and without 010 * license or royalty fees, to use, copy, modify, and distribute this 011 * software and its documentation for any purpose, provided that the above 012 * copyright notice and the following two paragraphs appear in all copies 013 * of this software. 014 * 015 * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY 016 * FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES 017 * ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF 018 * THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF 019 * SUCH DAMAGE. 020 * 021 * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES, 022 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 023 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE 024 * PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF 025 * CALIFORNIA HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, 026 * ENHANCEMENTS, OR MODIFICATIONS. 027 * 028 */ 029 030package org.geon; 031 032import java.io.BufferedInputStream; 033import java.io.BufferedOutputStream; 034import java.io.BufferedReader; 035import java.io.File; 036import java.io.FileInputStream; 037import java.io.FileNotFoundException; 038import java.io.FileOutputStream; 039import java.io.FileReader; 040import java.io.IOException; 041import java.io.InputStream; 042import java.io.Reader; 043import java.math.BigDecimal; 044import java.net.HttpURLConnection; 045import java.net.URL; 046import java.util.Calendar; 047import java.util.HashMap; 048import java.util.Map; 049import java.util.StringTokenizer; 050import java.util.zip.ZipEntry; 051import java.util.zip.ZipInputStream; 052 053import javax.xml.bind.JAXBContext; 054import javax.xml.bind.JAXBException; 055import javax.xml.bind.Marshaller; 056 057import org.apache.commons.net.ftp.FTP; 058import org.dlese.adn.ADNmetadataType; 059import org.dlese.adn.ADType; 060import org.dlese.adn.BodyType; 061import org.dlese.adn.BoundBoxType; 062import org.dlese.adn.CatalogEntriesType; 063import org.dlese.adn.CatalogType; 064import org.dlese.adn.ContributorLifecycleType; 065import org.dlese.adn.ContributorsLifecycleType; 066import org.dlese.adn.CoordinateSystemType; 067import org.dlese.adn.DateInfoType; 068import org.dlese.adn.GeneralType; 069import org.dlese.adn.GeospatialCoverageType; 070import org.dlese.adn.GeospatialCoveragesType; 071import org.dlese.adn.KeywordType; 072import org.dlese.adn.KeywordsType; 073import org.dlese.adn.LifecycleType; 074import org.dlese.adn.MetaMetadataType; 075import org.dlese.adn.ObjectFactory; 076import org.dlese.adn.ObjectsInSpaceType; 077import org.dlese.adn.OnlineType; 078import org.dlese.adn.OrganizationType; 079import org.dlese.adn.PeriodType; 080import org.dlese.adn.PeriodsType; 081import org.dlese.adn.PersonType; 082import org.dlese.adn.ProjectionType; 083import org.dlese.adn.RelationsType; 084import org.dlese.adn.RelativeType; 085import org.dlese.adn.RequirementType; 086import org.dlese.adn.RequirementsType; 087import org.dlese.adn.RightsType; 088import org.dlese.adn.StatusOfType; 089import org.dlese.adn.SubjectsType; 090import org.dlese.adn.TechnicalType; 091import org.dlese.adn.TemporalCoveragesType; 092import org.dlese.adn.TermsOfUseType; 093import org.dlese.adn.TimeADType; 094import org.dlese.adn.TimeAndPeriodType; 095import org.dlese.adn.TimeBCType; 096import org.dlese.adn.TimeInfoType; 097import org.dlese.adn.TimeRelativeType; 098 099import ptolemy.actor.TypedAtomicActor; 100import ptolemy.actor.TypedIOPort; 101import ptolemy.data.StringToken; 102import ptolemy.data.type.BaseType; 103import ptolemy.kernel.CompositeEntity; 104import ptolemy.kernel.util.IllegalActionException; 105import ptolemy.kernel.util.NameDuplicationException; 106import uk.ac.leeds.ccg.shapefile.Shapefile; 107import uk.ac.leeds.ccg.shapefile.ShapefileException; 108import util.UUIDGen; 109 110////////////////////////////////////////////////////////////////////////// 111////XMLToADN 112/** 113 * This actor converts XML name-value pairs to ADN schema 114 * 115 * @author Efrat Jaeger 116 * @version $Id: XMLToADN.java 24234 2010-05-06 05:21:26Z welker $ 117 * @since Ptolemy II 3.0.2 118 */ 119public class XMLToADN extends TypedAtomicActor { 120 121 /** 122 * Construct an actor with the given container and name. 123 * 124 * @param container 125 * The container. 126 * @param name 127 * The name of this actor. 128 * @exception IllegalActionException 129 * If the actor cannot be contained by the proposed 130 * container. 131 * @exception NameDuplicationException 132 * If the container already has an actor with this name. 133 */ 134 public XMLToADN(CompositeEntity container, String name) 135 throws NameDuplicationException, IllegalActionException { 136 super(container, name); 137 138 datasetURL = new TypedIOPort(this, "datasetURL", true, false); 139 datasetURL.setTypeEquals(BaseType.STRING); 140 141 input = new TypedIOPort(this, "input", true, false); 142 input.setTypeEquals(BaseType.STRING); 143 144 output = new TypedIOPort(this, "output", false, true); 145 output.setTypeEquals(BaseType.STRING); 146 147 _attachText("_iconDescription", "<svg>\n" 148 + "<polygon points=\"-15,-15 15,15 15,-15 -15,15\" " 149 + "style=\"fill:white\"/>\n" + "</svg>\n"); 150 } 151 152 // ///////////////////////////////////////////////////////////////// 153 // // public variables //// 154 155 /** Dataset URL. */ 156 public TypedIOPort datasetURL; 157 158 /** XML name-value input string. */ 159 public TypedIOPort input; 160 161 /** ADN schema string. */ 162 public TypedIOPort output; 163 164 // ///////////////////////////////////////////////////////////////// 165 // // public methods //// 166 167 /** 168 * Consume an XML string representing name value pairs and converts it to an 169 * ADN schema. 170 * 171 * @exception IllegalActionException 172 * If there is no director. FIXME: Either verify that it does 173 * check for the director, or remove this statement. This 174 * statement occurs in other conversion actor(s) as well. 175 */ 176 public void fire() throws IllegalActionException { 177 shpfis = null; 178 String xmlInput = ((StringToken) input.get(0)).stringValue(); 179 shpURL = ((StringToken) datasetURL.get(0)).stringValue(); 180 181 // Note: Following line may assume 1 byte per character, not sure. 182 String outputValue = process(xmlInput); 183 String adnContent = ""; 184 try { 185 File adn = new File(outputValue); 186 Reader in = new FileReader(adn); 187 BufferedReader br = new BufferedReader(in); 188 String line; 189 while ((line = br.readLine()) != null) { 190 adnContent += line + "\n"; 191 } 192 br.close(); 193 in = null; 194 // adn.delete(); 195 _deleteFiles(); 196 } catch (Exception ex) { 197 _debug(ex.getMessage()); 198 _deleteFiles(); 199 } 200 output.send(0, new StringToken(adnContent)); 201 } 202 203 private String process(String xmlString) { 204 205 Map metadata = new HashMap(); 206 207 // Extracting user input (name/value pairs) into a hashmap. 208 int nameStartInd = xmlString.toLowerCase().indexOf("<name>"); 209 while (nameStartInd != -1) { 210 int nameEndInd = xmlString.toLowerCase().indexOf("</name>"); 211 String name = xmlString.substring(nameStartInd + 6, nameEndInd); 212 xmlString = xmlString.substring(nameEndInd + 7); 213 int valueStartInd = xmlString.toLowerCase().indexOf("<value>"); 214 int valueEndInd = xmlString.toLowerCase().indexOf("</value>"); 215 String value = xmlString.substring(valueStartInd + 7, valueEndInd); 216 xmlString = xmlString.substring(valueEndInd + 8); 217 metadata.put(name, value); 218 nameStartInd = xmlString.toLowerCase().indexOf("<name>"); 219 } 220 221 String errMsg = ""; 222 223 String title = (String) metadata.get("title"); 224 String subjectss = (String) metadata.get("subjects"); 225 String keywords = (String) metadata.get("keywords"); 226 String permission = (String) metadata.get("permission"); 227 String description = (String) metadata.get("description"); 228 229 String personOrOrg1 = (String) metadata.get("person1"); 230 String role1 = (String) metadata.get("role1"); 231 String nametitle1 = (String) metadata.get("nametitle1"); 232 String firstname1 = (String) metadata.get("firstname1"); 233 String middlename1 = (String) metadata.get("middlename1"); 234 String lastname1 = (String) metadata.get("lastname1"); 235 String org1 = (String) metadata.get("org1"); 236 237 String email1 = (String) metadata.get("email1"); 238 String homepage1 = (String) metadata.get("homepage1"); 239 240 // handle spatial coverage 241 // String min_altitude = (String) metadata.get("min_altitude"); 242 // String max_altitude = (String) metadata.get("max_altitude"); 243 244 String hrizontal = (String) metadata.get("hrizontal"); 245 String projection = (String) metadata.get("projection"); 246 String coordinate = (String) metadata.get("coordinate"); 247 248 // handle temporal coverage 249 String time = (String) metadata.get("time"); 250 251 String geologic_time = (String) metadata.get("geologic_time"); 252 String begin_age = (String) metadata.get("begin_age"); 253 String end_age = (String) metadata.get("end_age"); 254 255 // handle present coverage 256 String begin_date = (String) metadata.get("begindate"); 257 String end_date = (String) metadata.get("enddate"); 258 259 String t = time.trim(); 260 261 StringTokenizer stb = !time.equals("present") ? null 262 : new StringTokenizer(begin_date, "/"); 263 264 int bm = !time.equals("present") ? 0 : Integer 265 .parseInt(stb.nextToken()); 266 int bd = !time.equals("present") ? 0 : Integer 267 .parseInt(stb.nextToken()); 268 int by = !time.equals("present") ? 0 : Integer 269 .parseInt(stb.nextToken()); 270 271 StringTokenizer ste = !t.equals("present") ? null 272 : new StringTokenizer(end_date, "/"); 273 274 int em; 275 if (!t.equals("present")) { 276 em = 0; 277 } else { 278 em = Integer.parseInt(ste.nextToken()); 279 } 280 281 int ed; 282 if (!t.equals("present")) { 283 ed = 0; 284 } else { 285 ed = Integer.parseInt(ste.nextToken()); 286 } 287 288 int ey; 289 if (!t.equals("present")) { 290 ey = 0; 291 } else { 292 ey = Integer.parseInt(ste.nextToken()); 293 } 294 295 String begin_hour = (String) metadata.get("begin_hour"); 296 String end_hour = (String) metadata.get("end_hour"); 297 String begin_min = (String) metadata.get("begin_min"); 298 String end_min = (String) metadata.get("end_min"); 299 String begin_sec = (String) metadata.get("begin_sec"); 300 String end_sec = (String) metadata.get("end_sec"); 301 302 int bHour = Integer.parseInt(begin_hour); 303 int bMin = Integer.parseInt(begin_min); 304 int bSec = Integer.parseInt(begin_sec); 305 306 int eHour = Integer.parseInt(end_hour); 307 int eMin = Integer.parseInt(end_min); 308 int eSec = Integer.parseInt(end_sec); 309 310 String begin_month; 311 String begin_day; 312 String begin_year; 313 314 String end_month; 315 String end_day; 316 String end_year; 317 318 boolean earlier = true; 319 320 if ((by < ey) 321 || (by == ey && bm < em) 322 || (by == ey && bm == em && bd < ed) 323 || (by == ey && bm == em && bd == ed && bHour < eHour) 324 || (by == ey && bm == em && bd == ed && bHour == eHour && bMin < eMin) 325 || (by == ey && bm == em && bd == ed && bHour == eHour 326 && bMin == eMin && bSec <= eSec)) { 327 328 // begin date and time is earlier 329 begin_month = Integer.toString(bm); 330 begin_day = Integer.toString(bd); 331 begin_year = Integer.toString(by); 332 333 end_month = Integer.toString(em); 334 end_day = Integer.toString(ed); 335 end_year = Integer.toString(ey); 336 337 } else { 338 339 earlier = false; 340 341 begin_month = Integer.toString(em); 342 begin_day = Integer.toString(ed); 343 begin_year = Integer.toString(ey); 344 345 end_month = Integer.toString(bm); 346 end_day = Integer.toString(bd); 347 end_year = Integer.toString(by); 348 349 String tmp = begin_hour; 350 begin_hour = end_hour; 351 end_hour = tmp; 352 353 tmp = begin_min; 354 begin_min = end_min; 355 end_min = tmp; 356 357 tmp = begin_sec; 358 begin_sec = end_sec; 359 end_sec = tmp; 360 361 } 362 363 String time_choice; 364 if (by >= 0 && ey >= 0) { 365 time_choice = "AD"; 366 } else if (by < 0 && ey < 0) { 367 time_choice = "BC"; 368 } else { 369 time_choice = "direct"; 370 } 371 372 String bc_begin_year = earlier ? Integer.toString(-by) : Integer 373 .toString(-ey); 374 String bc_end_year = earlier ? Integer.toString(-ey) : Integer 375 .toString(-by); 376 377 String d_begin_year = earlier ? Integer.toString(-by) : Integer 378 .toString(-ey); 379 String d_end_year = earlier ? Integer.toString(ey) : Integer 380 .toString(by); 381 382 try { 383 ObjectFactory factory = new ObjectFactory(); 384 385 ADNmetadataType itemRecord = (ADNmetadataType) factory 386 .newInstance(Class.forName("org.dlese.adn.ItemRecord")); 387 388 // ////////////////////////////////////////////////////////// 389 // // 390 // // general 391 // // 392 // ///////////////////////////////////////////////////////// 393 GeneralType general = (GeneralType) factory.newInstance(Class 394 .forName("org.dlese.adn.GeneralType")); 395 general.setTitle(title); 396 general.setDescription(description); 397 general.setLanguage("en"); 398 399 // subjects 400 SubjectsType subjects = (SubjectsType) factory.newInstance(Class 401 .forName("org.dlese.adn.SubjectsType")); 402 general.setSubjects(subjects); 403 subjects.getSubject().add(subjectss); 404 405 // keywords 406 if (keywords != null) { 407 KeywordsType keywordsType = (KeywordsType) factory 408 .newInstance(Class 409 .forName("org.dlese.adn.KeywordsType")); 410 411 general.setKeywords(keywordsType); 412 StringTokenizer st = new StringTokenizer(keywords, ","); 413 while (st.hasMoreTokens()) { 414 String tmp = st.nextToken().trim(); 415 KeywordType keyword = (KeywordType) factory 416 .newInstance(Class 417 .forName("org.dlese.adn.KeywordType")); 418 keyword.setValue(tmp); 419 keywordsType.getKeyword().add(keyword); 420 } 421 } 422 // lifecycle 423 LifecycleType lifecycle = (LifecycleType) factory.newInstance(Class 424 .forName("org.dlese.adn.LifecycleType")); 425 426 // set the first contributor 427 ContributorsLifecycleType contributors = (ContributorsLifecycleType) factory 428 .newInstance(Class 429 .forName("org.dlese.adn.ContributorsLifecycleType")); 430 lifecycle.setContributors(contributors); 431 432 ContributorLifecycleType author = (ContributorLifecycleType) factory 433 .newInstance(Class 434 .forName("org.dlese.adn.ContributorLifecycleType")); 435 author.setRole(role1); 436 437 if (personOrOrg1.equals("Person")) { 438 PersonType person = (PersonType) factory.newInstance(Class 439 .forName("org.dlese.adn.PersonType")); 440 person.setNameTitle(nametitle1); 441 person.setNameFirst(firstname1); 442 person.setNameMiddle(middlename1); 443 person.setNameLast(lastname1); 444 person.setInstName(org1); 445 person.setEmailPrimary(email1); 446 author.setPerson(person); 447 448 contributors.getContributor().add(author); 449 } else { 450 OrganizationType org = (OrganizationType) factory 451 .newInstance(Class 452 .forName("org.dlese.adn.OrganizationType")); 453 org.setInstName(org1); 454 contributors.getContributor().add(org); 455 } 456 457 // ////////////////////////////////////////////////////////// 458 // // 459 // // metametadata 460 // // 461 // ///////////////////////////////////////////////////////// 462 MetaMetadataType metaMetadata = (MetaMetadataType) factory 463 .newInstance(Class 464 .forName("org.dlese.adn.MetaMetadataType")); 465 CatalogEntriesType catalogEntries = (CatalogEntriesType) factory 466 .newInstance(Class 467 .forName("org.dlese.adn.CatalogEntriesType")); 468 469 CatalogType catalog = (CatalogType) factory.newInstance(Class 470 .forName("org.dlese.adn.CatalogType")); 471 catalog.setValue("shapefile"); 472 473 // get unique id 474 // UUIDGenerator ug = UUIDGenerator.getInstance(); 475 // UUID uuid = ug.generateTimeBasedUUID(); 476 477 UUIDGen uuidgen = new UUIDGen(); 478 String uuid = uuidgen.generateUUID(); 479 480 catalog.setEntry("GEON-" + uuid); 481 catalogEntries.getCatalog().add(catalog); 482 metaMetadata.setCatalogEntries(catalogEntries); 483 484 DateInfoType dateInfo = (DateInfoType) factory.newInstance(Class 485 .forName("org.dlese.adn.DateInfoType")); 486 Calendar now = Calendar.getInstance(); 487 // dateInfo.setCreated(now.get(Calendar.YEAR)+"-"+now.get(Calendar.MONTH)+"-"+now.get(Calendar.DAY_OF_MONTH)); 488 dateInfo.setCreated(now); 489 dateInfo.setValue("Registered"); 490 metaMetadata.setDateInfo(dateInfo); 491 492 StatusOfType statusOf = (StatusOfType) factory.newInstance(Class 493 .forName("org.dlese.adn.StatusOfType")); 494 statusOf.setStatus("Submitted"); 495 statusOf.setValue("Submitted"); 496 metaMetadata.setStatusOf(statusOf); 497 498 metaMetadata.setLanguage("en"); 499 metaMetadata.setCopyright("No"); 500 metaMetadata.setScheme("No scheme"); 501 502 TermsOfUseType termsOfUse = (TermsOfUseType) factory 503 .newInstance(Class.forName("org.dlese.adn.TermsOfUseType")); 504 termsOfUse.setValue("Terms of use consistent with GEON policy."); 505 metaMetadata.setTermsOfUse(termsOfUse); 506 507 // ////////////////////////////////////////////////////////// 508 // // 509 // // technical 510 // // 511 // ///////////////////////////////////////////////////////// 512 TechnicalType technical = (TechnicalType) factory.newInstance(Class 513 .forName("org.dlese.adn.TechnicalType")); 514 OnlineType online = (OnlineType) factory.newInstance(Class 515 .forName("org.dlese.adn.OnlineType")); 516 online.setPrimaryURL("http://www.geongrid.org"); 517 518 RequirementsType requirements = (RequirementsType) factory 519 .newInstance(Class 520 .forName("org.dlese.adn.RequirementsType")); 521 online.setRequirements(requirements); 522 523 RequirementType requirement = (RequirementType) factory 524 .newInstance(Class.forName("org.dlese.adn.RequirementType")); 525 requirement 526 .setReqType("DLESE:General:No specific technical requirements"); 527 requirements.getRequirement().add(requirement); 528 529 technical.setOnline(online); 530 531 // ////////////////////////////////////////////////////////// 532 // // 533 // // right 534 // // 535 // ///////////////////////////////////////////////////////// 536 RightsType rights = (RightsType) factory.newInstance(Class 537 .forName("org.dlese.adn.RightsType")); 538 539 rights.setDescription(permission); 540 rights.setCost("DLESE:No"); 541 542 // ////////////////////////////////////////////////////////// 543 // // 544 // // relation 545 // // 546 // ///////////////////////////////////////////////////////// 547 RelationsType relations = (RelationsType) factory.newInstance(Class 548 .forName("org.dlese.adn.RelationsType")); 549 550 // ////////////////////////////////////////////////////////// 551 // // 552 // // spatial coverage 553 // // 554 // ///////////////////////////////////////////////////////// 555 GeospatialCoveragesType geospatialCoverages = (GeospatialCoveragesType) factory 556 .newInstance(Class 557 .forName("org.dlese.adn.GeospatialCoveragesType")); 558 559 GeospatialCoverageType geospatialCoverage = (GeospatialCoverageType) factory 560 .newInstance(Class 561 .forName("org.dlese.adn.GeospatialCoverageType")); 562 563 BodyType body = (BodyType) factory.newInstance(Class 564 .forName("org.dlese.adn.BodyType")); 565 body.setPlanet("Earth"); 566 geospatialCoverage.setBody(body); 567 568 geospatialCoverage.setGeodeticDatumGlobalOrHorz(hrizontal); 569 570 ProjectionType proj = (ProjectionType) factory.newInstance(Class 571 .forName("org.dlese.adn.ProjectionType")); 572 proj.setType(projection); 573 proj.setValue("Some projections here"); 574 geospatialCoverage.setProjection(proj); 575 576 CoordinateSystemType coord = (CoordinateSystemType) factory 577 .newInstance(Class 578 .forName("org.dlese.adn.CoordinateSystemType")); 579 coord.setType(coordinate); 580 coord.setValue("Some cordinate system here"); 581 geospatialCoverage.setCoordinateSystem(coord); 582 583 BoundBoxType box = (BoundBoxType) factory.newInstance(Class 584 .forName("org.dlese.adn.BoundBoxType")); 585 box.setBbSrcName("Cataloger supplied"); 586 587 /* 588 * VertType vert = 589 * (VertType)factory.newInstance(Class.forName("org.dlese.adn.VertType" 590 * )); VertMinMaxType min = 591 * (VertMinMaxType)factory.newInstance(Class 592 * .forName("org.dlese.adn.VertMinMaxType")); 593 * min.setUnits("centimeters (cm)"); min.setValue(new 594 * BigDecimal(min_altitude[0])); 595 * 596 * VertMinMaxType max = 597 * (VertMinMaxType)factory.newInstance(Class.forName 598 * ("org.dlese.adn.VertMinMaxType")); 599 * max.setUnits("centimeters (cm)"); max.setValue(new 600 * BigDecimal(max_altitude[0])); 601 * 602 * vert.setVertMin(min); vert.setVertMax(max); 603 * vert.setGeodeticDatumGlobalOrVert("DLESE:CGD28-CDN"); 604 * vert.setVertBase("Datum level"); 605 * 606 * box.setBbVert(vert); 607 */ 608 609 geospatialCoverage.setBoundBox(box); 610 // geospatialCoverage.setDetGeos(); 611 612 geospatialCoverages.getGeospatialCoverage().add(geospatialCoverage); 613 614 // ////////////////////////////////////////////////////////// 615 // // 616 // // temporal coverage 617 // // 618 // ///////////////////////////////////////////////////////// 619 TemporalCoveragesType temporalCoverages = (TemporalCoveragesType) factory 620 .newInstance(Class 621 .forName("org.dlese.adn.TemporalCoveragesType")); 622 TimeAndPeriodType timeAndPeriod = (TimeAndPeriodType) factory 623 .newInstance(Class 624 .forName("org.dlese.adn.TimeAndPeriodType")); 625 temporalCoverages.getTimeAndPeriod().add(timeAndPeriod); 626 627 // set time directly into relativeTime 628 TimeInfoType timeInfo = (TimeInfoType) factory.newInstance(Class 629 .forName("org.dlese.adn.TimeInfoType")); 630 631 timeAndPeriod.setTimeInfo(timeInfo); 632 633 if (time.equals("notpresent")) { 634 if (geologic_time.equals("other")) { 635 636 TimeRelativeType timeRelative = (TimeRelativeType) factory 637 .newInstance(Class 638 .forName("org.dlese.adn.TimeRelativeType")); 639 timeInfo.setTimeRelative(timeRelative); 640 641 RelativeType begin = (RelativeType) factory 642 .newInstance(Class 643 .forName("org.dlese.adn.RelativeType")); 644 timeRelative.setBegin(begin); 645 begin.setValue(new BigDecimal(begin_age)); 646 begin.setUnits("ma"); 647 648 RelativeType end = (RelativeType) factory.newInstance(Class 649 .forName("org.dlese.adn.RelativeType")); 650 timeRelative.setEnd(end); 651 end.setValue(new BigDecimal(end_age)); 652 end.setUnits("ma"); 653 654 } else { 655 656 TimeRelativeType timeRelative = (TimeRelativeType) factory 657 .newInstance(Class 658 .forName("org.dlese.adn.TimeRelativeType")); 659 timeInfo.setTimeRelative(timeRelative); 660 661 RelativeType begin = (RelativeType) factory 662 .newInstance(Class 663 .forName("org.dlese.adn.RelativeType")); 664 timeRelative.setBegin(begin); 665 begin.setValue(new BigDecimal(0)); 666 begin.setUnits("ma"); 667 668 RelativeType end = (RelativeType) factory.newInstance(Class 669 .forName("org.dlese.adn.RelativeType")); 670 timeRelative.setEnd(end); 671 end.setValue(new BigDecimal(0)); 672 end.setUnits("ma"); 673 674 // set time to periods 675 PeriodsType periods = (PeriodsType) factory 676 .newInstance(Class 677 .forName("org.dlese.adn.PeriodsType")); 678 timeAndPeriod.setPeriods(periods); 679 680 PeriodType period = (PeriodType) factory.newInstance(Class 681 .forName("org.dlese.adn.PeriodType")); 682 periods.getPeriod().add(period); 683 period.setName(geologic_time); 684 period.setSource("USGS-Geologic-Time-Scale"); 685 686 } 687 } else if (time.equals("present")) { 688 689 // set time directly into timeAD or timeBC 690 if (time_choice.equals("AD")) { 691 692 TimeADType timeAD = (TimeADType) factory.newInstance(Class 693 .forName("org.dlese.adn.TimeADType")); 694 timeInfo.setTimeAD(timeAD); 695 696 Calendar begin = Calendar.getInstance(); 697 begin.clear(); 698 699 begin.add(Calendar.YEAR, 700 Integer.parseInt(begin_year) - 1970); 701 begin 702 .add(Calendar.MONTH, 703 Integer.parseInt(begin_month) - 1); 704 begin.add(Calendar.DAY_OF_MONTH, Integer 705 .parseInt(begin_day) - 1); 706 707 Calendar bt = Calendar.getInstance(); 708 bt.clear(); 709 710 bt.add(Calendar.HOUR, Integer.parseInt(begin_hour)); 711 bt.add(Calendar.MINUTE, Integer.parseInt(begin_min)); 712 bt.add(Calendar.SECOND, Integer.parseInt(begin_sec)); 713 714 Calendar end = Calendar.getInstance(); 715 end.clear(); 716 end.add(Calendar.YEAR, Integer.parseInt(end_year) - 1970); 717 end.add(Calendar.MONTH, Integer.parseInt(end_month) - 1); 718 end.add(Calendar.DAY_OF_MONTH, 719 Integer.parseInt(end_day) - 1); 720 721 Calendar et = Calendar.getInstance(); 722 et.clear(); 723 724 et.add(Calendar.HOUR, Integer.parseInt(end_hour)); 725 et.add(Calendar.MINUTE, Integer.parseInt(end_min)); 726 et.add(Calendar.SECOND, Integer.parseInt(end_sec)); 727 728 ADType tmp = (ADType) factory.newInstance(Class 729 .forName("org.dlese.adn.ADType")); 730 tmp.setDate(begin); 731 tmp.setTime(bt); 732 tmp.setValue(""); 733 timeAD.setBegin(tmp); 734 735 tmp = (ADType) factory.newInstance(Class 736 .forName("org.dlese.adn.ADType")); 737 tmp.setDate(end); 738 tmp.setTime(et); 739 tmp.setValue(""); 740 timeAD.setEnd(tmp); 741 742 } else if (time_choice.equals("BC")) { 743 744 TimeBCType timeBC = (TimeBCType) factory.newInstance(Class 745 .forName("org.dlese.adn.TimeBCType")); 746 timeInfo.setTimeBC(timeBC); 747 748 timeBC.setBegin(bc_begin_year); 749 timeBC.setEnd(bc_end_year); 750 751 } else if (time_choice.equals("direct")) { 752 753 TimeRelativeType timeRelative = (TimeRelativeType) factory 754 .newInstance(Class 755 .forName("org.dlese.adn.TimeRelativeType")); 756 timeInfo.setTimeRelative(timeRelative); 757 758 RelativeType begin = (RelativeType) factory 759 .newInstance(Class 760 .forName("org.dlese.adn.RelativeType")); 761 timeRelative.setBegin(begin); 762 begin.setValue(new BigDecimal("-" + d_begin_year)); 763 begin.setUnits("year"); 764 765 RelativeType end = (RelativeType) factory.newInstance(Class 766 .forName("org.dlese.adn.RelativeType")); 767 timeRelative.setEnd(end); 768 end.setValue(new BigDecimal(d_end_year)); 769 end.setUnits("year"); 770 771 } 772 } 773 774 // handle object in space 775 ObjectsInSpaceType objectsInSpace = (ObjectsInSpaceType) factory 776 .newInstance(Class 777 .forName("org.dlese.adn.ObjectsInSpaceType")); 778 779 itemRecord.setGeneral(general); 780 itemRecord.setLifecycle(lifecycle); 781 itemRecord.setMetaMetadata(metaMetadata); 782 itemRecord.setRights(rights); 783 itemRecord.setTechnical(technical); 784 // itemRecord.setRelations(relations); 785 itemRecord.setGeospatialCoverages(geospatialCoverages); 786 if (!time.equals("any")) { 787 itemRecord.setTemporalCoverages(temporalCoverages); 788 } 789 itemRecord.setObjectsInSpace(objectsInSpace); 790 791 // marshall 792 JAXBContext jc = JAXBContext.newInstance("org.dlese.adn"); 793 Marshaller m = jc.createMarshaller(); 794 m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); 795 796 // create and save target 797 798 // save into a directory 799 File dir = new File("adn/" + uuid); // TODO: remove adn folder once 800 // all the files have been 801 // removed. 802 dir.mkdirs(); 803 dirPath = dir.getAbsolutePath(); 804 805 // unzip the uploaded file 806 String shpFile = shpURL; 807 String unzipFileName = ""; 808 if (shpFile.trim().startsWith("http://")) { 809 URL shpURL = new URL(shpFile); 810 HttpURLConnection huc = (HttpURLConnection) shpURL 811 .openConnection(); 812 huc.connect(); 813 InputStream in = huc.getInputStream(); 814 File zip = new File(dir, "tmp.zip"); 815 FileOutputStream out = new FileOutputStream(zip); 816 byte[] buffer = new byte[1024]; 817 int count = in.read(buffer); 818 while (count > 0) { 819 out.write(buffer, 0, count); 820 count = in.read(buffer); 821 } 822 huc.disconnect(); 823 out.close(); 824 unzipFileName = unzip(dir, zip); // Unzipping the ftpped file to 825 // dir. 826 zip.delete(); // the zip file is no longer necessary. 827 } else if (shpFile.trim().startsWith("ftp://")) { 828 shpFile = shpFile.substring(6); 829 String username = "anonymous"; 830 String password = "geon@geongrid.org"; 831 int index = shpFile.indexOf("/"); 832 String hostname = shpFile.substring(0, index); 833 String filename = shpFile.substring(index); 834 org.apache.commons.net.ftp.FTPClient f = new org.apache.commons.net.ftp.FTPClient(); 835 f.connect(hostname); 836 f.login(username, password); 837 f.setFileType(FTP.BINARY_FILE_TYPE); 838 File zip = new File(dir, "tmp.zip"); 839 FileOutputStream fos = new FileOutputStream(zip); 840 f.retrieveFile(filename, fos); 841 f.disconnect(); 842 fos.close(); 843 unzipFileName = unzip(dir, zip); // Unzipping the ftpped file to 844 // dir. 845 zip.delete(); // the zip file is no longer necessary. 846 847 } else { // file is local.. 848 java.io.File zip = new java.io.File(shpFile); 849 unzipFileName = unzip(dir, zip); 850 } 851 852 if (!unzipFileName.equals("")) { 853 // calculate the binding box and set the adn schema 854 shpfis = new FileInputStream(dirPath + "/" + unzipFileName 855 + ".shp"); 856 Shapefile shape = new Shapefile(shpfis); 857 double[] bounds = shape.getBounds(); 858 859 box.setWestCoord(new BigDecimal(bounds[0])); 860 box.setNorthCoord(new BigDecimal(bounds[1])); 861 box.setEastCoord(new BigDecimal(bounds[2])); 862 box.setSouthCoord(new BigDecimal(bounds[3])); 863 864 shpfis.close(); 865 // Object x = (Object) shape; 866 867 // shape = new Shapefile(); 868 869 /* 870 * File shp = new File(dir, unzipFileName + ".shp"); File shx = 871 * new File(dir, unzipFileName + ".shx"); File dbf = new 872 * File(dir, unzipFileName + ".dbf"); 873 * 874 * 875 * shp.delete(); shx.delete(); dbf.delete(); //dir.delete(); 876 */ 877 } 878 /* 879 * // calculate the schema and ask for more explanation DBase db = 880 * new DBase(dirName); db.openTable(fileName); String [] columns = 881 * db.getColumnNames(); ArrayList list = new ArrayList(); for (int 882 * i=0; i<columns.length; i++) { list.add(columns[i]); } 883 */// save its metadata 884 File adn = new File(dir, uuid + ".adn"); 885 FileOutputStream fos = new FileOutputStream(adn); 886 m.marshal(itemRecord, fos); 887 fos.close(); 888 889 /* 890 * } catch (Exception e) { 891 * 892 * try { PrintWriter pw = new PrintWriter(new 893 * FileWriter("/home/jaeger/log.txt", true)); e.printStackTrace(pw); 894 * pw.flush(); } catch (Exception ex) {} 895 * 896 * throw new JspException(e.getMessage()); } return SKIP_BODY; } 897 * 898 * 899 * 900 * private String label(String string) { return 901 * "<table width=90% cellpadding=1 cellspacing=0 border=0>\n"+ 902 * "<tr><td bgcolor=Gainsboro>\n"+ 903 * "<font face=\"arial,sans-serif\" size=-1 color=#777777>\n"+ 904 * " <b>"+string+"</b>\n"+ "</font>\n"+ "</td></tr>\n"+ 905 * "</table>\n"; } 906 * 907 * 908 * private String message(String key, String val) { return 909 * " <tr>\n" + 910 * " <td align=right width=150><div class=label><b>" 911 * +key+":</b></div></td>\n" + 912 * " <td align=left>"+val+"</td>\n" + " </tr>\n"; } 913 * 914 * 915 * private String messagePadding(String key, String val) { return 916 * " <tr>\n" + 917 * " <td align=right width=150><div class=label> " 918 * +key+":</div></td>\n" + " <td align=left>"+val+"</td>\n" + 919 * " </tr>\n"; } 920 */ 921 return adn.getAbsolutePath(); 922 } catch (ClassNotFoundException cnfex) { 923 cnfex.printStackTrace(); 924 _deleteFiles(); 925 } catch (JAXBException jex) { 926 jex.printStackTrace(); 927 _deleteFiles(); 928 } catch (FileNotFoundException fnex) { 929 fnex.printStackTrace(); 930 _deleteFiles(); 931 } catch (IOException ioex) { 932 ioex.printStackTrace(); 933 _deleteFiles(); 934 } catch (ShapefileException shex) { 935 shex.printStackTrace(); 936 _deleteFiles(); 937 } catch (Exception ex) { 938 ex.printStackTrace(); 939 _deleteFiles(); 940 } 941 return ""; 942 943 } 944 945 public static String unzip(java.io.File dst, java.io.File zip) 946 throws Exception { 947 948 System.out.println("dst folder = " + dst.getAbsolutePath() 949 + " , zip file = " + zip.getAbsolutePath()); 950 int BUFFER = 2048; 951 BufferedOutputStream dest = null; 952 FileInputStream fis = new FileInputStream(zip); 953 ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis)); 954 ZipEntry entry; 955 String name = null; 956 boolean error = false; 957 while ((entry = zis.getNextEntry()) != null) { 958 959 if (entry.isDirectory()) { 960 continue; 961 } 962 963 String tmp = entry.getName(); 964 String nm = tmp; 965 966 int index = tmp.lastIndexOf("/"); 967 if (index != -1) { 968 tmp = tmp.substring(index + 1); 969 nm = tmp; 970 } 971 972 if (tmp.endsWith("dbf") || tmp.endsWith("shp") 973 || tmp.endsWith("shx")) { 974 975 tmp = tmp.substring(0, tmp.length() - 4); 976 if (name == null) { 977 name = tmp; 978 } else if (name.equals(tmp)) { 979 980 } else { 981 continue; 982 } 983 } 984 985 int count; 986 byte data[] = new byte[BUFFER]; 987 988 // write the files to the disk 989 java.io.File file = new java.io.File(dst, nm); 990 FileOutputStream fos = new FileOutputStream(file); 991 dest = new BufferedOutputStream(fos, BUFFER); 992 while ((count = zis.read(data, 0, BUFFER)) != -1) { 993 dest.write(data, 0, count); 994 } 995 dest.flush(); 996 dest.close(); 997 } 998 zis.close(); 999 fis.close(); 1000 1001 return name; 1002 1003 } 1004 1005 private void _deleteFiles() { 1006 shpfis = null; 1007 File dir = new File(dirPath); 1008 String fileNames[] = dir.list(); 1009 for (int i = 0; i < fileNames.length; i++) { 1010 System.out.println(fileNames[i]); 1011 File file = new File(dir, fileNames[i]); 1012 file.delete(); 1013 } 1014 File parent = dir.getParentFile(); 1015 dir.delete(); 1016 // if this is the adn dir and its empty - delete it. 1017 if (parent.getName().equals("adn") && parent.list().length == 0) { 1018 parent.delete(); 1019 } 1020 } 1021 1022 private FileInputStream shpfis = null; 1023 private String dirPath = ""; 1024 private String shpURL = ""; 1025 1026}