View a form to restore a specific {@link DataArchive}.
Permission checks are handled in {@link DataArchives()}.
Submissions are handled through {@link doDataTransfer()}, same as backup operations.
771820
public function restoresnapshot($request) {
		$dataArchive = DNDataArchive::get()->byId($request->param('DataArchiveID'));

		if(!$dataArchive) {
			throw new SS_HTTPResponse_Exception('Archive not found', 404);
		}

		// We check for canDownload because that implies access to the data.
		// canRestore is later checked on the actual restore action per environment.
		if(!$dataArchive->canDownload()) {
			throw new SS_HTTPResponse_Exception('Not allowed to access archive', 403);
		}

		$form = $this->getDataTransferRestoreForm($this->request, $dataArchive);

		// View currently only available via ajax
		return $form->forTemplate();
	}
912154
public boolean restoreBackupData(InputStream streamData) {
        // convert stream to string
        java.util.Scanner s = new java.util.Scanner(streamData).useDelimiter("\\A");
        String data = s.hasNext() ? s.next() : "";

        // parse JSON
        ObjectMapper mapper = new ObjectMapper();
        Backup backupData = null;
        try {
            backupData = mapper.readValue(data, Backup.class);
        } catch (Exception e) {
            logger.error("Could not parse input data: {}, {}", e.getClass(), e.getMessage());
            return false;
        }

        // TODO: validate json against a schema for safety

        // GROUPS
        try {
            logger.info("Number of groups: {}", backupData.getGroups().size());

            for (Group group : backupData.getGroups()) {
                // determine if group already exists.. if not then add it
                Integer groupId = PathOverrideService.getInstance().getGroupIdFromName(group.getName());
                if (groupId == null) {
                    groupId = PathOverrideService.getInstance().addGroup(group.getName());
                }

                // get all methods from the group.. we are going to remove ones that don't exist in the new configuration
                List<Method> originalMethods = EditService.getInstance().getMethodsFromGroupId(groupId, null);

                for (Method originalMethod : originalMethods) {
                    Boolean matchInImportGroup = false;

                    int importCount = 0;
                    for (Method importMethod : group.getMethods()) {
                        if (originalMethod.getClassName().equals(importMethod.getClassName()) &&
                            originalMethod.getMethodName().equals(importMethod.getMethodName())) {
                            matchInImportGroup = true;
                            break;
                        }
                        importCount++;
                    }

                    if (!matchInImportGroup) {
                        // remove it from current database since it is a delta to the current import
                        PathOverrideService.getInstance().removeOverride(originalMethod.getId());
                    } else {
                        // remove from import list since it already exists
                        group.getMethods().remove(importCount);
                    }
                }

                // add methods to groups
                for (Method method : group.getMethods()) {
                    PathOverrideService.getInstance().createOverride(groupId, method.getMethodName(), method.getClassName());
                }
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        // PROFILES
        try {
            logger.info("Number of profiles: {}", backupData.getProfiles().size());

            // remove all servers
            // don't care about deltas here.. we'll just recreate them all
            // removed default servers (belong to group id=0)
            ServerRedirectService.getInstance().deleteServerGroup(0);

            for (com.groupon.odo.proxylib.models.backup.Profile profile : backupData.getProfiles()) {
                // see if a profile with this name already exists
                Integer profileId = ProfileService.getInstance().getIdFromName(profile.getName());
                com.groupon.odo.proxylib.models.Profile newProfile;
                if (profileId == null) {
                    // create new profile
                    newProfile = ProfileService.getInstance().add(profile.getName());
                } else {
                    // get the existing profile
                    newProfile = ProfileService.getInstance().findProfile(profileId);
                }

                // add new servers
                if (profile.getServers() != null) {
                    for (ServerRedirect server : profile.getServers()) {
                        ServerRedirectService.getInstance().addServerRedirect(server.getRegion(), server.getSrcUrl(), server.getDestUrl(), server.getHostHeader(), newProfile.getId(), 0);
                    }
                }

                // remove all server groups
                for (ServerGroup group : ServerRedirectService.getInstance().tableServerGroups(newProfile.getId())) {
                    ServerRedirectService.getInstance().deleteServerGroup(group.getId());
                }

                // add new server groups
                if (profile.getServerGroups() != null) {
                    for (ServerGroup group : profile.getServerGroups()) {
                        int groupId = ServerRedirectService.getInstance().addServerGroup(group.getName(), newProfile.getId());
                        for (ServerRedirect server : group.getServers()) {
                            ServerRedirectService.getInstance().addServerRedirect(server.getRegion(), server.getSrcUrl(), server.getDestUrl(), server.getHostHeader(), newProfile.getId(), groupId);
                        }
                    }
                }

                // remove all paths
                // don't care about deltas here.. we'll just recreate them all
                for (EndpointOverride path : PathOverrideService.getInstance().getPaths(newProfile.getId(), Constants.PROFILE_CLIENT_DEFAULT_ID, null)) {
                    PathOverrideService.getInstance().removePath(path.getPathId());
                }

                // add new paths
                if (profile.getPaths() != null) {
                    for (EndpointOverride path : profile.getPaths()) {
                        int pathId = PathOverrideService.getInstance().addPathnameToProfile(newProfile.getId(), path.getPathName(), path.getPath());

                        PathOverrideService.getInstance().setContentType(pathId, path.getContentType());
                        PathOverrideService.getInstance().setRequestType(pathId, path.getRequestType());
                        PathOverrideService.getInstance().setGlobal(pathId, path.getGlobal());

                        // add groups to path
                        for (String groupName : path.getGroupNames()) {
                            int groupId = PathOverrideService.getInstance().getGroupIdFromName(groupName);
                            PathOverrideService.getInstance().AddGroupByNumber(newProfile.getId(), pathId, groupId);
                        }
                    }
                }

                // set active
                ClientService.getInstance().updateActive(newProfile.getId(), Constants.PROFILE_CLIENT_DEFAULT_ID, profile.getActive());
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        // SCRIPTS
        try {
            // delete all scripts
            for (Script script : ScriptService.getInstance().getScripts()) {
                ScriptService.getInstance().removeScript(script.getId());
            }

            // add scripts
            for (Script script : backupData.getScripts()) {
                ScriptService.getInstance().addScript(script.getName(), script.getScript());
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        // tell http/https proxies to reload plugins
        try {
            org.apache.http.conn.ssl.SSLSocketFactory sslsf = new org.apache.http.conn.ssl.SSLSocketFactory(new TrustStrategy() {
                @Override
                public boolean isTrusted(
                    final X509Certificate[] chain, String authType) throws CertificateException {
                    // ignore SSL cert issues
                    return true;
                }
            });
            HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
            sslsf.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
            for (String connectstring : getConnectorStrings("https_proxy")) {
                HttpGet request = new HttpGet(connectstring + "/proxy/reload");

                HttpClient httpClient = new org.apache.http.impl.client.DefaultHttpClient();
                String[] parts = connectstring.split(":");
                httpClient.getConnectionManager().getSchemeRegistry().register(new org.apache.http.conn.scheme.Scheme("https", Integer.parseInt(parts[parts.length - 1]), sslsf));
                HttpResponse response = httpClient.execute(request);
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("Exception caught during proxy reload.  Things may be in an inconsistent state.");
        }

        // restart plugin service for this process
        PluginManager.destroy();

        return true;
    }
820965
public static base_response restore(nitro_service client, appfwprofile resource) throws Exception {
		appfwprofile restoreresource = new appfwprofile();
		restoreresource.archivename = resource.archivename;
		return restoreresource.perform_operation(client,"restore");
	}
329483
@Override
	protected byte[] getData(Attributes attributes) {
        byte[] zip = null;
        Map<String, List<String>> filesMap = new HashMap<String, List<String>>();
        Map<String, List<byte[]>> contentsMap = new HashMap<String, List<byte[]>>();

        for (Report report : reports) {
            String folder = report.getName();
            List<String> files = new ArrayList<String>();
            List<byte[]> contents = new ArrayList<byte[]>();

            if (ReportConstants.NEXT.equals(report.getType())) {
                report = NextUtil.restoreImagesName(report);
                NextContent reportContent = (NextContent) report.getContent();
                files.add(reportContent.getNextFile().getName());
                contents.add(reportContent.getNextFile().getDataProvider().getBytes());
                if (reportContent.getImageFiles() != null) {
                    for (JcrFile entry : reportContent.getImageFiles()) {
                        files.add(entry.getName());
                        contents.add(entry.getDataProvider().getBytes());
                    }
                }
				if (reportContent.getTemplateFile() != null) {
					files.add(reportContent.getTemplateFile().getName());
					contents.add(reportContent.getTemplateFile().getDataProvider().getBytes());
				}

            } else {
                report = JasperUtil.restoreImagesName(report);
                report = JasperUtil.restoreSubreportsInMaster(report);

                JasperContent jrc = (JasperContent) report.getContent();
                List<JcrFile> entries = jrc.getJasperFiles();
                for (JcrFile entry : entries) {
                    files.add(entry.getName());
                    contents.add(entry.getDataProvider().getBytes());
                }

                JcrFile paramEntry = jrc.getParametersFile();
                if (paramEntry != null) {
                    files.add(paramEntry.getName());
                    contents.add(paramEntry.getDataProvider().getBytes());
                }

                if (jrc.getImageFiles() != null) {
                    for (JcrFile entry : jrc.getImageFiles()) {
                        files.add(entry.getName());
                        contents.add(entry.getDataProvider().getBytes());
                    }
                }
            }

            if (reports.size() == 1) {
                try {
                    zip = FileUtil.zip(files, contents);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else {
                filesMap.put(folder, files);
                contentsMap.put(folder, contents);
            }
        }

        if (reports.size() > 1) {
            try {
                zip = FileUtil.zip(filesMap, contentsMap);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return zip;
    }
734009
public void restore(BackupMetaData backup, File destinationFile) throws Exception
    {
        File tempFile = File.createTempFile("exhibitor-backup", ".tmp");
        OutputStream out = new FileOutputStream(tempFile);
        InputStream in = null;
        try {
            backupProvider.get().downloadBackup(exhibitor, backup, out, getBackupConfig());
            CloseableUtils.closeQuietly(out);
            out = null;

            out = new FileOutputStream(destinationFile);
            in = new GZIPInputStream(new FileInputStream(tempFile));

            ByteStreams.copy(in, out);
        }
        finally {
            CloseableUtils.closeQuietly(in);
            CloseableUtils.closeQuietly(out);
            if (!tempFile.delete()) {
                exhibitor.getLog().add(ActivityLog.Type.ERROR, "Could not delete temp file (for restore): " + tempFile);
            }
        }
    }
56754
function handlePermissionUpdate() {
            permissionArea.find("form").submit(function (e) {
                e.preventDefault();
                //console.log(e);
                var form = e.currentTarget;
                appendFormFields(form);
                Rocket.Util.submitFormAsync(form, function (responseData) {
                    //console.log(responseData);
                    if (responseData && responseData.status && responseData.status == "success") {
                        location.reload();
                    }
                });
            });
        }
738069
@Override
  public boolean undo() {
    if (destTopologyFile != null) {
      LOG.info("Clean uploaded jar");
      File file = new File(destTopologyFile);
      return file.delete();
    }
    return true;
  }
1282906
@Override
    public Data readBackupData(Data key) {
        Record record = getRecord(key);

        if (record == null) {
            return null;
        } else {
            if (partitionService.isPartitionOwner(partitionId)) {
                // set last access time to prevent
                // premature removal of the entry because
                // of idleness based expiry
                record.setLastAccessTime(Clock.currentTimeMillis());
            }
        }

        Object value = record.getValue();
        mapServiceContext.interceptAfterGet(name, value);
        // this serialization step is needed not to expose the object, see issue 1292
        return mapServiceContext.toData(value);
    }
82365
public void restore(ObjectInputStream dis, int dataVersion)
  throws SevereMessageStoreException
  {
    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
      SibTr.entry(
        tc, "restore", new Object[] { dis, new Integer(dataVersion) });

    itemStream = (ProtocolItemStream) getItemStream();
    
    persistent = true;    

    try
    {      
      //read back the cellule
      byte[] celluleBytes = new byte[9];
      dis.read(celluleBytes, 0, 9);
      remoteMEUuid = new MessagingEngine(celluleBytes).getUuid();
      
      //read back the streamID
      byte[] streamIDBytes = new byte[12];
      dis.read(streamIDBytes, 0, 12);
      streamID = new SIBUuid12(streamIDBytes);
      
      //read back the destID
      byte[] destIDBytes = new byte[12];
      dis.read(destIDBytes, 0, 12);
      destID = new SIBUuid12(destIDBytes);
      
      //read back the busID
      byte[] busIDBytes = new byte[8];
      dis.read(busIDBytes, 0, 8);
      busID = new SIBUuid8(busIDBytes);
            
      initialData = dis.readLong();
      type = Type.getType(dis.readInt());
      
      //read back the number of subset IDs we should expect
      int numberOfSubsets = dis.readInt();
      
      // Now we've restored our persistent data, we can initialise the set.
      initialize();
      
      ReliabilitySubset[] newSubsets = new ReliabilitySubset[numberOfSubsets];
      long[] newSubsetIDs = new long[numberOfSubsets];
      
      //now go find all of the stored subsets via their IDs
      for(int i=0;i<numberOfSubsets;i++)
      {
        //get the next ID
        long subsetID = dis.readLong();
        //get the next reliability
        Reliability reliability = Reliability.getReliability(dis.readInt());
        //if the subset was properly stored, we will have a valid ID
        if(subsetID != NO_ID)
        {
          //find the subset via it's ID
          ReliabilitySubset subset = (ReliabilitySubset) getItemStream().findById(subsetID);
          if(subset != null)
          {
            //set the reliability
            subset.setReliability(reliability);
            //store the subset in a temporary array
            newSubsets[getIndex(reliability)] = subset;
          }
          else
          {
            //if we didn't find it, set the ID to NO_ID so that it will get recreated below.
            subsetID = NO_ID;
          }
        }        
        newSubsetIDs[i] = subsetID;
      }
      
      int j = 0;
      while(j<numberOfSubsets && newSubsetIDs[j] == NO_ID)
      {
        j++;
      }

      //loop through the current array of subsets
      for(int i=0;i<maxReliabilityIndex+1;i++)
      {
        //get the next restored subset
        ReliabilitySubset subset = null;
        Reliability reliability = null;
        if(j<numberOfSubsets)
        {
          subset = newSubsets[j];
          reliability = subset.getReliability();
        }
        //if it's reliability matches that of the current entry of the array
        if( reliability == getReliability(i))
        {
          //store the restored subset in the array
          subsets[i] = subset;
          subsetIDs[i] = newSubsetIDs[j++];
          //find the next valid restored subset
          while(j<numberOfSubsets && newSubsetIDs[j] == NO_ID)
          {
            j++;
          }
        }
      }
      
      //SIB0105.mp.6
      if (dataVersion >= PERSISTENT_VERSION)
        linkTarget = (String)dis.readObject();
    }
    catch (Exception e)
    {
      FFDCFilter.processException(
        e,
        "com.ibm.ws.sib.processor.gd.StreamSet.restore",
        "1:680:1.67",
        this);

      SibTr.exception(tc, e);
      SibTr.error(tc, "INTERNAL_MESSAGING_ERROR_CWSIP0002",
        new Object[] {
          "com.ibm.ws.sib.processor.gd.StreamSet",
          "1:687:1.67",
          e });
      
      if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "restore", "SIErrorException");
      
      throw new SIErrorException(
        nls.getFormattedMessage(
          "INTERNAL_MESSAGING_ERROR_CWSIP0002",
          new Object[] {
            "com.ibm.ws.sib.processor.gd.StreamSet",
            "1:697:1.67",
            e },
          null),
        e);
    }

    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
      SibTr.exit(tc, "restore");
  }
894999
def _restoreDPFromArchive(self):
        """"""
        dp = self._dp_menu_on
        if dp and dp.archived:
            dp.restore_from_archive(parent=self)
889720
@Override
    @Transactional
    public Snapshot transferToStorageComplete(String snapshotId)
        throws SnapshotException {
        try {
            Snapshot snapshot = getSnapshot(snapshotId);
            snapshot = changeSnapshotStatus(snapshot, SnapshotStatus.CLEANING_UP, "");

            File snapshotDir = new File(
                ContentDirUtils.getDestinationPath(snapshot.getName(),
                                                   BridgeConfiguration.getContentRootDir()));

            File zipFile = zipMetadata(snapshotId, snapshotDir);

            DuracloudEndPointConfig source = snapshot.getSource();

            ContentStore store = getContentStore(source);

            ensureMetadataSpaceExists(store);

            String zipChecksum = createChecksumGenerator().generateChecksum(zipFile);

            try {
                new Retrier(4, 1000, 2).execute(new Retriable() {
                    public Object retry() throws Exception {
                        try (FileInputStream zipStream = new FileInputStream(zipFile)) {
                            return store.addContent(Constants.SNAPSHOT_METADATA_SPACE,
                                                    zipFile.getName(),
                                                    zipStream,
                                                    zipFile.length(),
                                                    "application/zip",
                                                    zipChecksum,
                                                    null);
                        }
                    }
                });
            } catch (Exception ex) {
                log.error("failed to upload snapshot zip ("
                          + zipFile.getAbsolutePath() + ") to duracloud: " + ex.getMessage(), ex);
                throw new Exception(ex);
            } finally {
                zipFile.delete();
            }

            FileUtils.deleteDirectory(snapshotDir);

            String spaceId = source.getSpaceId();
            // Call DuraCloud to clean up snapshot
            getSnapshotTaskClient(source).cleanupSnapshot(spaceId);
            log.info("successfully initiated snapshot cleanup on DuraCloud for snapshotId = "
                     + snapshotId + "; spaceId = " + spaceId);

            return snapshot;
        } catch (Exception e) {
            String message = "failed to initiate snapshot clean up: " + e.getMessage();
            log.error(message, e);
            throw new SnapshotManagerException(e.getMessage());
        }
    }
216270
def post(self, *args, **kwargs):
        
        # Look for a wizard_prev_step element in the posted data which
        # contains a valid step name. If one was found, render the requested
        # form. (This makes stepping back a lot easier).
        wizard_prev_step = self.request.POST.get('wizard_prev_step', None)
        if wizard_prev_step and wizard_prev_step in self.get_form_list():
            self.storage.current_step = wizard_prev_step
            form = self.get_form(
                data=self.storage.get_step_data(self.steps.current),
                files=self.storage.get_step_files(self.steps.current))
            return self.render(form)

        # Check if form was refreshed
        management_form = ManagementForm(self.request.POST, prefix=self.prefix)
        if not management_form.is_valid():
            raise ValidationError(
                'ManagementForm data is missing or has been tampered.')

        form_current_step = management_form.cleaned_data['current_step']
        if (form_current_step != self.steps.current and
                self.storage.current_step is not None):
            # form refreshed, change current step
            self.storage.current_step = form_current_step

        # get the form for the current step
        form = self.get_form(data=self.request.POST, files=self.request.FILES)

        # and try to validate
        if form.is_valid():
            # if the form is valid, store the cleaned data and files.
            self.storage.set_step_data(self.steps.current, self.process_step(form))
            self.storage.set_step_files(self.steps.current, self.process_step_files(form))

            # check if the current step is the last step
            if self.steps.current == self.steps.last:
                # no more steps, render done view
                return self.render_done(form, **kwargs)
            else:
                # proceed to the next step
                return self.render_next_step(form)
        return self.render(form)
347752
public void	
    doArchive(String logListURI, String archiveDirectory)
    throws IOException
  {
    String destURL = FileSystem.getDefaultUri(fsConfig) + archiveDirectory;
    DistCp.copy(new JobConf(fsConfig), logListURI, destURL, null, true, false);
  }
1277839
function( dataTransfer, callback ) {
                var results  = [],
                    promises = [],
                    items, files, file, item, i, len, canAccessFolder;
    
                items = dataTransfer.items;
                files = dataTransfer.files;
    
                canAccessFolder = !!(items && items[ 0 ].webkitGetAsEntry);
    
                for ( i = 0, len = files.length; i < len; i++ ) {
                    file = files[ i ];
                    item = items && items[ i ];
    
                    if ( canAccessFolder && item.webkitGetAsEntry().isDirectory ) {
    
                        promises.push( this._traverseDirectoryTree(
                                item.webkitGetAsEntry(), results ) );
                    } else {
                        results.push( file );
                    }
                }
    
                Base.when.apply( Base, promises ).done(function() {
    
                    if ( !results.length ) {
                        return;
                    }
    
                    callback( results );
                });
            }
1309928
public void restore(ObjectInputStream din, int dataVersion)
  {
    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
      SibTr.entry(
        tc, "restore", new Object[] { din, Integer.valueOf(dataVersion) });
    
    checkPersistentVersionId(dataVersion);

    try
    {
      remoteMEId = new SIBUuid8(din.readUTF());
      streamId = new SIBUuid12(din.readUTF()); 
      if (dataVersion > 1)
      {
        String id = din.readUTF();
        if (!id.equals(NULL))
          gatheringTargetDestUuid = new SIBUuid12(id);
      }
    }
    catch (Exception e)
    {
      // No FFDC code needed
      SIErrorException e2 = new SIErrorException(e);

      if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
        SibTr.exit(tc, "restore", e2);

      throw e2;
    }

    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
      SibTr.exit(tc, "restore");
  }
124585
@Override
	public void archive() {
		Log.info("Starting local archiving...");
		
		String fileName = FileHandlerUtil.generateAuditFileName(FileHandlerUtil.substractDate(new Date(),
				archiveDateDiff));
		String archiveFileName = FileHandlerUtil.generateAuditArchiveFileName(FileHandlerUtil.substractDate(new Date(),
				archiveDateDiff));

		String filePath = FileHandlerUtil.generateOutputFilePath(path, fileName);
		String archivePath = FileHandlerUtil.generateOutputFilePath(path, archiveFileName);

		if (FileHandlerUtil.isFileAlreadyExists(filePath)) {

			FileOutputStream fos = null;
			try {
				fos = new FileOutputStream(archivePath);
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			ZipOutputStream zos = new ZipOutputStream(fos);
			ZipEntry ze = new ZipEntry(fileName);
			try {
				zos.putNextEntry(ze);

				FileInputStream in = new FileInputStream(filePath);

				int len;
				while ((len = in.read(buffer)) > 0) {
					zos.write(buffer, 0, len);
				}

				in.close();
				zos.closeEntry();
				zos.close();
				System.out.println("Done");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
753060
public static void restoreFile(String sourceName,
                                   String destName) throws IOException {

        RandomAccessFile source = new RandomAccessFile(sourceName, "r");
        RandomAccessFile dest   = new RandomAccessFile(destName, "rw");

        while (source.getFilePointer() != source.length()) {
            int    size     = source.readInt();
            long   position = source.readLong();
            byte[] buffer   = new byte[size];

            source.read(buffer);
            dest.seek(position);
            dest.write(buffer);
        }

        dest.seek(DataFileCache.LONG_FREE_POS_POS);

        long length = dest.readLong();

        JavaSystem.setRAFileLength(dest, length);
        source.close();
        dest.close();
    }