Parse SVG data from an Android application asset.

@param assetMngr the Android asset manager.
@param svgPath the path to the SVG file in the application's assets.
@throws IOException if there was a problem reading the file.
178671
public SVGBuilder readFromAsset(AssetManager assetMngr, String svgPath) throws IOException {
		this.data = assetMngr.open(svgPath);
		return this;
	}
835001
@Override
    public Asset assetAt(String path) {
        // The simplest implementation is to delegate to the provider and see if they return something.
        for (AssetProvider provider : providers) {
            Asset asset = provider.assetAt(path);
            if (asset != null) {
                return asset;
            }
        }
        return null;
    }
604158
function svgToImg(baseFolder, currentFile, $) {
    var currentDirectory = path.dirname(currentFile);

    return editHTMLElement($, 'svg', function($svg) {
        var content = '<?xml version="1.0" encoding="UTF-8"?>' +
            renderDOM($, $svg);

        // We avoid generating twice the same PNG
        var hash = crc.crc32(content).toString(16);
        var fileName = hash + '.svg';
        var filePath = path.join(baseFolder, fileName);

        // Write the svg to the file
        return fs.assertFile(filePath, function() {
            return fs.writeFile(filePath, content, 'utf8');
        })

        // Return as image
        .then(function() {
            var src = LocationUtils.relative(currentDirectory, fileName);
            $svg.replaceWith('<img src="' + src + '" />');
        });
    });
}
990484
@Override
    public boolean load(String graphHopperFolder) {
        if (isEmpty(graphHopperFolder))
            throw new IllegalStateException("GraphHopperLocation is not specified. Call setGraphHopperLocation or init before");

        if (fullyLoaded)
            throw new IllegalStateException("graph is already successfully loaded");

        File tmpFileOrFolder = new File(graphHopperFolder);

        if (!tmpFileOrFolder.isDirectory() && tmpFileOrFolder.exists()) {
            throw new IllegalArgumentException("GraphHopperLocation cannot be an existing file. Has to be either non-existing or a folder.");
        } else {
            File compressed = new File(graphHopperFolder + ".ghz");
            if (compressed.exists() && !compressed.isDirectory()) {
                try {
                    new Unzipper().unzip(compressed.getAbsolutePath(), graphHopperFolder, removeZipped);
                } catch (IOException ex) {
                    throw new RuntimeException("Couldn't extract file " + compressed.getAbsolutePath()
                            + " to " + graphHopperFolder, ex);
                }
            }
        }

        setGraphHopperLocation(graphHopperFolder);

        if (encodingManager == null)
            setEncodingManager(EncodingManager.create(flagEncoderFactory, ghLocation));

        if (!allowWrites && dataAccessType.isMMap())
            dataAccessType = DAType.MMAP_RO;

        GHDirectory dir = new GHDirectory(ghLocation, dataAccessType);
        GraphExtension ext = encodingManager.needsTurnCostsSupport()
                ? new TurnCostExtension() : new GraphExtension.NoOpExtension();

        if (lmFactoryDecorator.isEnabled())
            initLMAlgoFactoryDecorator();

        if (chFactoryDecorator.isEnabled()) {
            initCHAlgoFactoryDecorator();
            ghStorage = new GraphHopperStorage(chFactoryDecorator.getNodeBasedWeightings(), chFactoryDecorator.getEdgeBasedWeightings(),
                    dir, encodingManager, hasElevation(), ext);
        } else {
            ghStorage = new GraphHopperStorage(dir, encodingManager, hasElevation(), ext);
        }

        ghStorage.setSegmentSize(defaultSegmentSize);

        if (!new File(graphHopperFolder).exists())
            return false;

        GHLock lock = null;
        try {
            // create locks only if writes are allowed, if they are not allowed a lock cannot be created 
            // (e.g. on a read only filesystem locks would fail)
            if (ghStorage.getDirectory().getDefaultType().isStoring() && isAllowWrites()) {
                lockFactory.setLockDir(new File(ghLocation));
                lock = lockFactory.create(fileLockName, false);
                if (!lock.tryLock())
                    throw new RuntimeException("To avoid reading partial data we need to obtain the read lock but it failed. In " + ghLocation, lock.getObtainFailedReason());
            }

            if (!ghStorage.loadExisting())
                return false;

            postProcessing();
            fullyLoaded = true;
            return true;
        } finally {
            if (lock != null)
                lock.release();
        }
    }
1053713
private static void inlineSvgNodes(final Document doc, final String basePath) {
        try {
            // handle null inputs
            if (doc == null) return;

            final String fixedBasePath = basePath == null ? "" : basePath;

            final List<Node> nodes = XMLUtilities.getChildNodes(doc.getDocumentElement(), "object");
            for (final Node node : nodes) {
                final NamedNodeMap attributes = node.getAttributes();

                final Node typeAttribute = attributes.getNamedItem("type");
                final Node dataAttribute = attributes.getNamedItem("data");

                if (typeAttribute != null && typeAttribute.getTextContent().equals("image/svg+xml") && dataAttribute != null) {
                    final String data = dataAttribute.getTextContent();
                    final File dataFile = new File(fixedBasePath + "/" + data);
                    if (dataFile.exists()) {
                        final String fileString = FileUtilities.readFileContents(dataFile);
                        final Document svgDoc = XMLUtilities.convertStringToDocument(fileString);

                        if (svgDoc != null) {
                            final Element svgDocElement = svgDoc.getDocumentElement();
                            if (svgDocElement != null && svgDocElement.getNodeName().equals("svg")) {
                                final Node parent = node.getParentNode();
                                if (parent != null) {
                                    final Node importedNode = doc.importNode(svgDocElement, true);
                                    parent.replaceChild(importedNode, node);
                                }
                            }
                        }
                    }
                }
            }
        } catch (final Exception ex) {
            LOG.error("Unable to convert external SVG image to DOM Document", ex);
        }
    }
926032
@Override
    protected Asset readJson(final String assetId) throws IOException, BadVersionException {
        FileInputStream fis = null;
        try {
            fis = DirectoryUtils.createFileInputStream(createFromRelative(assetId + ".json"));
            Asset ass = processJSON(fis);
            return ass;
        } finally {
            if (fis != null) {
                fis.close();
            }
        }
    }
115283
private void doFilledPath(SvgElement obj, Path path)
   {
      // First check for pattern fill. It requires special handling.
      if (state.style.fill instanceof SVG.PaintReference)
      {
         SVG.SvgObject  ref = document.resolveIRI(((SVG.PaintReference) state.style.fill).href);
         if (ref instanceof SVG.Pattern) {
            SVG.Pattern  pattern = (SVG.Pattern)ref;
            fillWithPattern(obj, path, pattern);
            return;
         }
      }

      // Otherwise do a normal fill
      canvas.drawPath(path, state.fillPaint);
   }
374934
@Override
    public Asset getAsset(final String assetId) throws IOException, BadVersionException, RequestFailureException {
        HttpURLConnection connection = createHttpURLConnectionToMassive("/assets/"
                                                                        + assetId);
        connection.setRequestMethod("GET");
        testResponseCode(connection);
        return JSONAssetConverter.readValue(connection.getInputStream());
    }
759883
public GVRAndroidResource openResource(String filePath) throws IOException {
        // Error tolerance: Remove initial '/' introduced by file::///filename
        // In this case, the path is interpreted as relative to defaultPath,
        // which is the root of the filesystem.
        if (filePath.startsWith(File.separator)) {
            filePath = filePath.substring(File.separator.length());
        }

        filePath = adaptFilePath(filePath);
        String path;
        int resourceId;

        GVRAndroidResource resourceKey;
        switch (volumeType) {
        case ANDROID_ASSETS:
            // Resolve '..' and '.'
            path = getFullPath(defaultPath, filePath);
            path = new File(path).getCanonicalPath();
            if (path.startsWith(File.separator)) {
                path = path.substring(1);
            }
            resourceKey = new GVRAndroidResource(gvrContext, path);
            break;

            case ANDROID_RESOURCE:
            path = FileNameUtils.getBaseName(filePath);
            resourceId = gvrContext.getContext().getResources().getIdentifier(path, "raw", gvrContext.getContext().getPackageName());
            if (resourceId == 0) {
                throw new FileNotFoundException(filePath + " resource not found");
            }
            resourceKey = new GVRAndroidResource(gvrContext, resourceId);
            break;

        case LINUX_FILESYSTEM:
            resourceKey = new GVRAndroidResource(
                    getFullPath(defaultPath, filePath));
            break;

        case ANDROID_SDCARD:
            String linuxPath = Environment.getExternalStorageDirectory()
                    .getAbsolutePath();
            resourceKey = new GVRAndroidResource(
                    getFullPath(linuxPath, defaultPath, filePath));
            break;

        case INPUT_STREAM:
            resourceKey = new GVRAndroidResource(getFullPath(defaultPath, filePath), volumeInputStream);
            break;

        case NETWORK:
            resourceKey = new GVRAndroidResource(gvrContext,
                    getFullURL(defaultPath, filePath), enableUrlLocalCache);
            break;

        default:
            throw new IOException(
                    String.format("Unrecognized volumeType %s", volumeType));
        }
        return addResource(resourceKey);
    }
825949
SVG  parse(InputStream is, boolean enableInternalEntities) throws SVGParseException
   {
      // Transparently handle zipped files (.svgz)
      if (!is.markSupported()) {
         // We need a a buffered stream so we can use mark() and reset()
         is = new BufferedInputStream(is);
      }
      try
      {
         is.mark(3);
         int  firstTwoBytes = is.read() + (is.read() << 8);
         is.reset();
         if (firstTwoBytes == GZIPInputStream.GZIP_MAGIC) {
            // Looks like a zipped file.
            is = new BufferedInputStream( new GZIPInputStream(is) );
         }
      }
      catch (IOException ioe)
      {
         // Not a zipped SVG. Fall through and try parsing it normally.
      }

      try
      {
         // Mark the start in case we need to restart the parsing due to switching XML parser
         // 4096 chars is hopefully enough to capture most doctype declarations that have entities.
         is.mark(ENTITY_WATCH_BUFFER_SIZE);

         // Use XmlPullParser by default, which is faster, but doesn't support entity expansion.
         // In this parser we watch for capture doctype declarations, and then switch to the SAX
         // parser if any entities are defined in the doctype.
         parseUsingXmlPullParser(is, enableInternalEntities);
      }
      finally
      {
         try {
            is.close();
         } catch (IOException e) {
            Log.e(TAG, "Exception thrown closing input stream");
         }
      }
      return svgDocument;
   }
1057497
function loadSVGSuccess(text) {
        if (!destroyed && !unloaded) {
            if (!svgLoaded && text) {
                embedSVG(text);
                svgLoaded = true;
                if (!removeOnUnload) {
                    // cleanup the promise (abort will remove the svg text from
                    // the in-memory cache as well)
                    $loadSVGPromise.abort();
                    $loadSVGPromise = null;
                }
            }
            // always insert the svg el when load was successful
            if ($svg.parent().length === 0) {
                $svg.appendTo($svgLayer);
            }
        }
    }
360580
private final void readGlyf(FontFileReader in) throws IOException {
        TTFDirTabEntry dirTab = (TTFDirTabEntry)dirTabs.get("glyf");
        if (dirTab == null) {
            throw new IOException("glyf table not found, cannot continue");
        }
        for (int i = 0; i < (numberOfGlyphs - 1); i++) {
            if (mtxTab[i].getOffset() != mtxTab[i + 1].getOffset()) {
                in.seekSet(dirTab.getOffset() + mtxTab[i].getOffset());
                in.skip(2);
                final int[] bbox = {
                    in.readTTFShort(),
                    in.readTTFShort(),
                    in.readTTFShort(),
                    in.readTTFShort()};
                mtxTab[i].setBoundingBox(bbox);
            } else {
                mtxTab[i].setBoundingBox(mtxTab[0].getBoundingBox());
            }
        }


        long n = ((TTFDirTabEntry)dirTabs.get("glyf")).getOffset();
        for (int i = 0; i < numberOfGlyphs; i++) {
            if ((i + 1) >= mtxTab.length
                    || mtxTab[i].getOffset() != mtxTab[i + 1].getOffset()) {
                in.seekSet(n + mtxTab[i].getOffset());
                in.skip(2);
                final int[] bbox = {
                    in.readTTFShort(),
                    in.readTTFShort(),
                    in.readTTFShort(),
                    in.readTTFShort()};
                mtxTab[i].setBoundingBox(bbox);
            } else {
                /**@todo Verify that this is correct, looks like a copy/paste bug (jm)*/
                final int bbox0 = mtxTab[0].getBoundingBox()[0];
                final int[] bbox = {bbox0, bbox0, bbox0, bbox0};
                mtxTab[i].setBoundingBox(bbox);
                /* Original code
                mtxTab[i].bbox[0] = mtxTab[0].bbox[0];
                mtxTab[i].bbox[1] = mtxTab[0].bbox[0];
                mtxTab[i].bbox[2] = mtxTab[0].bbox[0];
                mtxTab[i].bbox[3] = mtxTab[0].bbox[0]; */
            }
            if (log.isTraceEnabled()) {
                log.trace(mtxTab[i].toString(this));
            }
        }
    }
1204411
@Override
    public InputStream getResourceAsStream(String name) {
        byte[] b = null;
        try {
            Asset resource = AssetCache.getAsset(mdwPackage.getName() + "/" + name);
            if (resource != null)
                b = resource.getRawContent();
            if (b == null)
                b = findInJarAssets(name);
            if (b == null)
                b = findInFileSystem(name);
        }
        catch (Exception ex) {
            logger.severeException(ex.getMessage(),  ex);
        }

        if (b == null)
            return super.getResourceAsStream(name);
        else
            return new ByteArrayInputStream(b);
    }
1229159
@GET
  @Path("/{asset: .+}")
  public Response getSwaggerUiAsset(@PathParam("asset") String assetPath) throws IOException {
    if (!ASSETS.contains(assetPath)) {
      return Response.status(404).build();
    }

    StreamingOutput streamingOutput = new StreamingOutput() {
      @Override
      public void write(OutputStream outputStream) throws IOException, WebApplicationException {
        try (InputStream inputStream = getClass().getResourceAsStream(WEBJAR_PATH + assetPath)) {
          int nextByte;
          while ((nextByte = inputStream.read()) != -1) {
            outputStream.write(nextByte);
          }
          outputStream.flush();
          outputStream.close();
        }
      }
    };
    return Response.ok(streamingOutput).build();
  }
163379
public LOADSTATUS loadFont(String path) throws VectorPrintException {
      try {
         File f = new File(path);
         LOADSTATUS stat = LOADSTATUS.NOT_LOADED;

         if (loadAWTFonts) {
            Font fo = Font.createFont(Font.TRUETYPE_FONT, f);
            GraphicsEnvironment.getLocalGraphicsEnvironment().registerFont(fo);
            stat = LOADSTATUS.LOADED_ONLY_AWT;
         }

         if (loadiText) {
            FontFactory.register(path);
            stat = (stat.equals(LOADSTATUS.LOADED_ONLY_AWT)) ? LOADSTATUS.LOADED_ITEXT_AND_AWT : LOADSTATUS.LOADED_ONLY_ITEXT;
            log.info(String.format("font loaded from %s", f.getAbsolutePath()));
         }

         return stat;
      } catch (FontFormatException | IOException ex) {
         log.log(Level.SEVERE, null, ex);

         throw new VectorPrintException("failed to load " + path, ex);
      }
   }
986637
@Override
    public <A extends BasicFileAttributes> A readAttributes(final Path path, final Class<A> type,
        final LinkOption... options) throws IOException {
        if (path == null) {
            throw new IllegalArgumentException("path must be specified");
        }
        if (type == null) {
            throw new IllegalArgumentException("type must be specified");
        }
        if (!type.isAssignableFrom(ShrinkWrapFileAttributes.class)) {
            throw new UnsupportedOperationException("Only supports " + ShrinkWrapFileAttributes.class.getSimpleName()
                + " type");
        }
        if (!(path instanceof ShrinkWrapPath)) {
            throw new IllegalArgumentException("Only " + ShrinkWrapPath.class.getSimpleName() + " is supported");
        }
        final ShrinkWrapPath swPath = (ShrinkWrapPath) path;
        if (!((ShrinkWrapFileSystem) swPath.getFileSystem()).getArchive().contains(path.toString())) {
            throw new NoSuchFileException(path.toString());
        }
        final A attributes = type.cast(new ShrinkWrapFileAttributes((ShrinkWrapPath) path, getArchive(path)));
        return attributes;
    }
1173005
public static PrototypeMeasurementFilter loadFromPath(String path) throws IOException {
    PrototypeMeasurementFilterSpecification spec =
        PrototypeMeasurementFilterSpecification.loadFromPath(path);
    return new PrototypeMeasurementFilter(spec);
  }