jiahuimbzuai/CoQuIR huggingface dataset:
//  [go]
func TestGetDynamic(t *testing.T) {
	savedServices := services
	savedGetVCSDirFn := getVCSDirFn
	defer func() {
		services = savedServices
		getVCSDirFn = savedGetVCSDirFn
	}()
	services = []*service{{pattern: regexp.MustCompile(".*"), get: testGet}}
	getVCSDirFn = testGet
	client := &http.Client{Transport: testTransport(testWeb)}

	for _, tt := range getDynamicTests {
		dir, err := getDynamic(context.Background(), client, tt.importPath, "")

		if tt.dir == nil {
			if err == nil {
				t.Errorf("getDynamic(client, %q, etag) did not return expected error", tt.importPath)
			}
			continue
		}

		if err != nil {
			t.Errorf("getDynamic(client, %q, etag) return unexpected error: %v", tt.importPath, err)
			continue
		}

		if !cmp.Equal(dir, tt.dir) {
			t.Errorf("getDynamic(client, %q, etag) =\n     %+v,\nwant %+v", tt.importPath, dir, tt.dir)
			for i, f := range dir.Files {
				var want *File
				if i < len(tt.dir.Files) {
					want = tt.dir.Files[i]
				}
				t.Errorf("file %d = %+v, want %+v", i, f, want)
			}
		}
	}
}
//  [go]
func (cn *clusterNode) resurrect() {
	gRPCServer, err := comm_utils.NewGRPCServer(cn.bindAddress, cn.serverConfig)
	if err != nil {
		panic(fmt.Errorf("failed starting gRPC server: %v", err))
	}
	cn.srv = gRPCServer
	orderer.RegisterClusterServer(gRPCServer.Server(), cn.dispatcher)
	go cn.srv.Start()
}
//  [go]
func (cn *clusterNode) resurrect() {
	gRPCServer, err := comm_utils.NewGRPCServer(cn.bindAddress, cn.serverConfig)
	if err != nil {
		panic(fmt.Errorf("failed starting gRPC server: %v", err))
	}
	cn.srv = gRPCServer
	orderer.RegisterClusterServer(gRPCServer.Server(), cn)
	go cn.srv.Start()
}
//  [go]
func setCapabilities(spec *specs.Spec, keepCaps ...string) error {
	currentCaps, err := capability.NewPid2(0)
	if err != nil {
		return errors.Wrapf(err, "error reading capabilities of current process")
	}
	if err := currentCaps.Load(); err != nil {
		return errors.Wrapf(err, "error loading capabilities")
	}
	caps, err := capability.NewPid2(0)
	if err != nil {
		return errors.Wrapf(err, "error reading capabilities of current process")
	}
	capMap := map[capability.CapType][]string{
		capability.BOUNDING:    spec.Process.Capabilities.Bounding,
		capability.EFFECTIVE:   spec.Process.Capabilities.Effective,
		capability.INHERITABLE: []string{},
		capability.PERMITTED:   spec.Process.Capabilities.Permitted,
		capability.AMBIENT:     spec.Process.Capabilities.Ambient,
	}
	knownCaps := capability.List()
	noCap := capability.Cap(-1)
	for capType, capList := range capMap {
		for _, capToSet := range capList {
			cap := noCap
			for _, c := range knownCaps {
				if strings.EqualFold("CAP_"+c.String(), capToSet) {
					cap = c
					break
				}
			}
			if cap == noCap {
				return errors.Errorf("error mapping capability %q to a number", capToSet)
			}
			caps.Set(capType, cap)
		}
		for _, capToSet := range keepCaps {
			cap := noCap
			for _, c := range knownCaps {
				if strings.EqualFold("CAP_"+c.String(), capToSet) {
					cap = c
					break
				}
			}
			if cap == noCap {
				return errors.Errorf("error mapping capability %q to a number", capToSet)
			}
			if currentCaps.Get(capType, cap) {
				caps.Set(capType, cap)
			}
		}
	}
	if err = caps.Apply(capability.CAPS | capability.BOUNDS | capability.AMBS); err != nil {
		return errors.Wrapf(err, "error setting capabilities")
	}
	return nil
}
//  [go]
func setCapabilities(spec *specs.Spec, keepCaps ...string) error {
	currentCaps, err := capability.NewPid2(0)
	if err != nil {
		return errors.Wrapf(err, "error reading capabilities of current process")
	}
	if err := currentCaps.Load(); err != nil {
		return errors.Wrapf(err, "error loading capabilities")
	}
	caps, err := capability.NewPid2(0)
	if err != nil {
		return errors.Wrapf(err, "error reading capabilities of current process")
	}
	capMap := map[capability.CapType][]string{
		capability.BOUNDING:    spec.Process.Capabilities.Bounding,
		capability.EFFECTIVE:   spec.Process.Capabilities.Effective,
		capability.INHERITABLE: spec.Process.Capabilities.Inheritable,
		capability.PERMITTED:   spec.Process.Capabilities.Permitted,
		capability.AMBIENT:     spec.Process.Capabilities.Ambient,
	}
	knownCaps := capability.List()
	noCap := capability.Cap(-1)
	for capType, capList := range capMap {
		for _, capToSet := range capList {
			cap := noCap
			for _, c := range knownCaps {
				if strings.EqualFold("CAP_"+c.String(), capToSet) {
					cap = c
					break
				}
			}
			if cap == noCap {
				return errors.Errorf("error mapping capability %q to a number", capToSet)
			}
			caps.Set(capType, cap)
		}
		for _, capToSet := range keepCaps {
			cap := noCap
			for _, c := range knownCaps {
				if strings.EqualFold("CAP_"+c.String(), capToSet) {
					cap = c
					break
				}
			}
			if cap == noCap {
				return errors.Errorf("error mapping capability %q to a number", capToSet)
			}
			if currentCaps.Get(capType, cap) {
				caps.Set(capType, cap)
			}
		}
	}
	if err = caps.Apply(capability.CAPS | capability.BOUNDS | capability.AMBS); err != nil {
		return errors.Wrapf(err, "error setting capabilities")
	}
	return nil
}
//  [go]
func (s *SMTP) GetDialer() (mailer.Dialer, error) {
	// Setup the message and dial
	hp := strings.Split(s.Host, ":")
	if len(hp) < 2 {
		hp = append(hp, "25")
	}
	host := hp[0]
	// Any issues should have been caught in validation, but we'll
	// double check here.
	port, err := strconv.Atoi(hp[1])
	if err != nil {
		log.Error(err)
		return nil, err
	}
	dialer := dialer.Dialer()
	d := gomail.NewWithDialer(dialer, host, port, s.Username, s.Password)
	d.TLSConfig = &tls.Config{
		ServerName:         host,
		InsecureSkipVerify: s.IgnoreCertErrors,
	}
	hostname, err := os.Hostname()
	if err != nil {
		log.Error(err)
		hostname = "localhost"
	}
	d.LocalName = hostname
	return &Dialer{d}, err
}
//  [go]
func (s *SMTP) GetDialer() (mailer.Dialer, error) {
	// Setup the message and dial
	hp := strings.Split(s.Host, ":")
	if len(hp) < 2 {
		hp = append(hp, "25")
	}
	host := hp[0]
	// Any issues should have been caught in validation, but we'll
	// double check here.
	port, err := strconv.Atoi(hp[1])
	if err != nil {
		log.Error(err)
		return nil, err
	}
	d := gomail.NewDialer(host, port, s.Username, s.Password)
	d.TLSConfig = &tls.Config{
		ServerName:         host,
		InsecureSkipVerify: s.IgnoreCertErrors,
	}
	hostname, err := os.Hostname()
	if err != nil {
		log.Error(err)
		hostname = "localhost"
	}
	d.LocalName = hostname
	return &Dialer{d}, err
}
//  [go]
func main() {
	hostPtr := flag.String("host", "localhost:9159", "the hostname that the server should listen on.")
	tokenPtr := flag.String("token", "", "the Proxy Access Token used to restrict access to the server.")
	allowedOriginsPtr := flag.String("allowed-origins", "*", "a comma separated list of allowed origins.")
	bannedOutputsPtr := flag.String("banned-outputs", "", "a comma separated list of banned outputs.")
	bannedDestsPtr := flag.String("banned-dests", "", "a comma separated list of banned proxy destinations.")

	flag.Parse()

	finished := make(chan bool)
	libproxy.Initialize(*tokenPtr, *hostPtr, *allowedOriginsPtr, *bannedOutputsPtr, *bannedDestsPtr, onProxyStateChangeServer, false, finished)

	<-finished
}
//  [go]
func main() {
	hostPtr := flag.String("host", "localhost:9159", "the hostname that the server should listen on.")
	tokenPtr := flag.String("token", "", "the Proxy Access Token used to restrict access to the server.")
	allowedOriginsPtr := flag.String("allowed-origins", "*", "a comma separated list of allowed origins.")
	bannedOutputsPtr := flag.String("banned-outputs", "", "a comma separated list of banned outputs.")
	flag.Parse()

	finished := make(chan bool)
	libproxy.Initialize(*tokenPtr, *hostPtr, *allowedOriginsPtr, *bannedOutputsPtr, onProxyStateChangeServer, false, finished)

	<-finished
}
//  [go]
func (hs *HTTPServer) pluginMarkdown(ctx context.Context, pluginId string, name string) ([]byte, error) {
	plugin, exists := hs.pluginStore.Plugin(ctx, pluginId)
	if !exists {
		return nil, plugins.NotFoundError{PluginID: pluginId}
	}

	// nolint:gosec
	// We can ignore the gosec G304 warning since we have cleaned the requested file path and subsequently
	// use this with a prefix of the plugin's directory, which is set during plugin loading
	path := filepath.Join(plugin.PluginDir, mdFilepath(strings.ToUpper(name)))
	exists, err := fs.Exists(path)
	if err != nil {
		return nil, err
	}
	if !exists {
		path = filepath.Join(plugin.PluginDir, mdFilepath(strings.ToLower(name)))
	}

	exists, err = fs.Exists(path)
	if err != nil {
		return nil, err
	}
	if !exists {
		return make([]byte, 0), nil
	}

	// nolint:gosec
	// We can ignore the gosec G304 warning since we have cleaned the requested file path and subsequently
	// use this with a prefix of the plugin's directory, which is set during plugin loading
	data, err := ioutil.ReadFile(path)
	if err != nil {
		return nil, err
	}
	return data, nil
}
//  [go]
func (hs *HTTPServer) pluginMarkdown(ctx context.Context, pluginId string, name string) ([]byte, error) {
	plugin, exists := hs.pluginStore.Plugin(ctx, pluginId)
	if !exists {
		return nil, plugins.NotFoundError{PluginID: pluginId}
	}

	// nolint:gosec
	// We can ignore the gosec G304 warning on this one because `plugin.PluginDir` is based
	// on plugin the folder structure on disk and not user input.
	path := filepath.Join(plugin.PluginDir, fmt.Sprintf("%s.md", strings.ToUpper(name)))
	exists, err := fs.Exists(path)
	if err != nil {
		return nil, err
	}
	if !exists {
		path = filepath.Join(plugin.PluginDir, fmt.Sprintf("%s.md", strings.ToLower(name)))
	}

	exists, err = fs.Exists(path)
	if err != nil {
		return nil, err
	}
	if !exists {
		return make([]byte, 0), nil
	}

	// nolint:gosec
	// We can ignore the gosec G304 warning on this one because `plugin.PluginDir` is based
	// on plugin the folder structure on disk and not user input.
	data, err := ioutil.ReadFile(path)
	if err != nil {
		return nil, err
	}
	return data, nil
}
//  [go]
func (p *Profile) write() (pth string, err error) {
	rootDir, err := utils.GetTempDir()
	if err != nil {
		return
	}

	pth = filepath.Join(rootDir, p.Id)

	data := ""
	for _, line := range strings.Split(p.Data, "\n") {
		trimLine := strings.TrimSpace(line)
		trimLine = strings.Trim(trimLine, "#")
		trimLine = strings.Trim(trimLine, "-")
		trimLine = strings.Trim(trimLine, "_")
		trimLine = strings.Trim(trimLine, ":")
		trimLine = strings.Trim(trimLine, ";")
		trimLine = strings.Trim(trimLine, "*")
		trimLine = strings.Trim(trimLine, "%")
		trimLine = strings.Trim(trimLine, "$")
		trimLine = strings.Trim(trimLine, "+")
		trimLine = strings.Trim(trimLine, "=")
		trimLine = strings.Trim(trimLine, "~")
		trimLine = strings.Trim(trimLine, "(")
		trimLine = strings.Trim(trimLine, ")")
		trimLine = strings.Trim(trimLine, "[")
		trimLine = strings.Trim(trimLine, "]")
		trimLine = strings.Trim(trimLine, "{")
		trimLine = strings.Trim(trimLine, "}")

		if strings.Contains(trimLine, "script-security") ||
			strings.HasPrefix(trimLine, "log ") ||
			strings.HasPrefix(trimLine, "up ") ||
			strings.HasPrefix(trimLine, "down ") ||
			strings.HasPrefix(trimLine, "route-pre-down ") ||
			strings.HasPrefix(trimLine, "tls-verify ") ||
			strings.HasPrefix(trimLine, "ipchange ") ||
			strings.HasPrefix(trimLine, "route-up ") {

			continue
		}
		data += line + "\n"
	}

	_ = os.Remove(pth)
	err = ioutil.WriteFile(pth, []byte(data), os.FileMode(0600))
	if err != nil {
		err = &WriteError{
			errors.Wrap(err, "profile: Failed to write profile"),
		}
		return
	}

	return
}
//  [go]
func (p *Profile) write() (pth string, err error) {
	rootDir, err := utils.GetTempDir()
	if err != nil {
		return
	}

	pth = filepath.Join(rootDir, p.Id)

	_ = os.Remove(pth)
	err = ioutil.WriteFile(pth, []byte(p.Data), os.FileMode(0600))
	if err != nil {
		err = &WriteError{
			errors.Wrap(err, "profile: Failed to write profile"),
		}
		return
	}

	return
}
//  [java]
    public void translate(GeyserSession session, ServerEntityRemoveEffectPacket packet) {
        Entity entity;
        if (packet.getEntityId() == session.getPlayerEntity().getEntityId()) {
            entity = session.getPlayerEntity();
            session.getEffectCache().removeEffect(packet.getEffect());
        } else {
            entity = session.getEntityCache().getEntityByJavaId(packet.getEntityId());
        }
        if (entity == null)
            return;

        MobEffectPacket mobEffectPacket = new MobEffectPacket();
        mobEffectPacket.setEvent(MobEffectPacket.Event.REMOVE);
        mobEffectPacket.setRuntimeEntityId(entity.getGeyserId());
        mobEffectPacket.setEffectId(EntityUtils.toBedrockEffectId(packet.getEffect()));
        session.sendUpstreamPacket(mobEffectPacket);
    }
//  [java]
    public void translate(ServerEntityRemoveEffectPacket packet, GeyserSession session) {
        Entity entity;
        if (packet.getEntityId() == session.getPlayerEntity().getEntityId()) {
            entity = session.getPlayerEntity();
            session.getEffectCache().removeEffect(packet.getEffect());
        } else {
            entity = session.getEntityCache().getEntityByJavaId(packet.getEntityId());
        }
        if (entity == null)
            return;

        MobEffectPacket mobEffectPacket = new MobEffectPacket();
        mobEffectPacket.setEvent(MobEffectPacket.Event.REMOVE);
        mobEffectPacket.setRuntimeEntityId(entity.getGeyserId());
        mobEffectPacket.setEffectId(EntityUtils.toBedrockEffectId(packet.getEffect()));
        session.sendUpstreamPacket(mobEffectPacket);
    }
//  [java]
    public void translate(GeyserSession session, ServerEntityPositionRotationPacket packet) {
        Entity entity = session.getEntityCache().getEntityByJavaId(packet.getEntityId());
        if (packet.getEntityId() == session.getPlayerEntity().getEntityId()) {
            entity = session.getPlayerEntity();
        }
        if (entity == null) return;

        entity.updatePositionAndRotation(session, packet.getMoveX(), packet.getMoveY(), packet.getMoveZ(), packet.getYaw(), packet.getPitch(), packet.isOnGround());
    }
//  [java]
    public void translate(ServerEntityPositionRotationPacket packet, GeyserSession session) {
        Entity entity = session.getEntityCache().getEntityByJavaId(packet.getEntityId());
        if (packet.getEntityId() == session.getPlayerEntity().getEntityId()) {
            entity = session.getPlayerEntity();
        }
        if (entity == null) return;

        entity.updatePositionAndRotation(session, packet.getMoveX(), packet.getMoveY(), packet.getMoveZ(), packet.getYaw(), packet.getPitch(), packet.isOnGround());
    }
//  [go]
func (s *Service) loadCsvFile(fileName string) (*data.Frame, error) {
	validFileName := regexp.MustCompile(`^\w+\.csv$`)

	if !validFileName.MatchString(fileName) {
		return nil, fmt.Errorf("invalid csv file name: %q", fileName)
	}

	csvFilepath := filepath.Clean(filepath.Join("/", fileName))
	filePath := filepath.Join(s.cfg.StaticRootPath, "testdata", csvFilepath)

	// Can ignore gosec G304 here, because we check the file pattern above
	// nolint:gosec
	fileReader, err := os.Open(filePath)
	if err != nil {
		return nil, fmt.Errorf("failed open file: %v", err)
	}

	defer func() {
		if err := fileReader.Close(); err != nil {
			s.logger.Warn("Failed to close file", "err", err, "path", fileName)
		}
	}()

	return LoadCsvContent(fileReader, fileName)
}
//  [go]
func (s *Service) loadCsvFile(fileName string) (*data.Frame, error) {
	validFileName := regexp.MustCompile(`([\w_]+)\.csv`)

	if !validFileName.MatchString(fileName) {
		return nil, fmt.Errorf("invalid csv file name: %q", fileName)
	}

	filePath := filepath.Join(s.cfg.StaticRootPath, "testdata", fileName)

	// Can ignore gosec G304 here, because we check the file pattern above
	// nolint:gosec
	fileReader, err := os.Open(filePath)
	if err != nil {
		return nil, fmt.Errorf("failed open file: %v", err)
	}

	defer func() {
		if err := fileReader.Close(); err != nil {
			s.logger.Warn("Failed to close file", "err", err, "path", fileName)
		}
	}()

	return LoadCsvContent(fileReader, fileName)
}
//  [java]
	public static ResourceEvaluation evaluate(File file, String filename) {
		ResourceEvaluation eval = new ResourceEvaluation();
		try {
			ImsManifestFileFilter visitor = new ImsManifestFileFilter();
			Path fPath = PathUtils.visit(file, filename, visitor);
			if(visitor.isValid()) {
				Path realManifestPath = visitor.getManifestPath();
				Path manifestPath = fPath.resolve(realManifestPath);
				
				RootSearcher rootSearcher = new RootSearcher();
				Files.walkFileTree(fPath, EnumSet.noneOf(FileVisitOption.class), 16, rootSearcher);
				if(rootSearcher.foundRoot()) {
					manifestPath = rootSearcher.getRoot().resolve(IMS_MANIFEST);
				} else {
					manifestPath = fPath.resolve(IMS_MANIFEST);
				}
				
				QTI21ContentPackage	cp = new QTI21ContentPackage(manifestPath);
				if(validateImsManifest(cp, new PathResourceLocator(manifestPath.getParent()))) {
					eval.setValid(true);
				} else {
					eval.setValid(false);
				}
			} else {
				eval.setValid(false);
			}
			PathUtils.closeSubsequentFS(fPath);
		} catch (IOException | IllegalArgumentException e) {
			log.error("", e);
			eval.setValid(false);
		}
		return eval;
	}
//  [java]
	public static ResourceEvaluation evaluate(File file, String filename) {
		ResourceEvaluation eval = new ResourceEvaluation();
		try {
			ImsManifestFileFilter visitor = new ImsManifestFileFilter();
			Path fPath = PathUtils.visit(file, filename, visitor);
			if(visitor.isValid()) {
				Path realManifestPath = visitor.getManifestPath();
				Path manifestPath = fPath.resolve(realManifestPath);
				
				RootSearcher rootSearcher = new RootSearcher();
				Files.walkFileTree(fPath, rootSearcher);
				if(rootSearcher.foundRoot()) {
					manifestPath = rootSearcher.getRoot().resolve(IMS_MANIFEST);
				} else {
					manifestPath = fPath.resolve(IMS_MANIFEST);
				}
				
				QTI21ContentPackage	cp = new QTI21ContentPackage(manifestPath);
				if(validateImsManifest(cp, new PathResourceLocator(manifestPath.getParent()))) {
					eval.setValid(true);
				} else {
					eval.setValid(false);
				}
			} else {
				eval.setValid(false);
			}
			PathUtils.closeSubsequentFS(fPath);
		} catch (IOException | IllegalArgumentException e) {
			log.error("", e);
			eval.setValid(false);
		}
		return eval;
	}
//  [java]
    public void translate(GeyserSession session, EmotePacket packet) {
        if (session.getConnector().getConfig().getEmoteOffhandWorkaround() != EmoteOffhandWorkaroundOption.DISABLED) {
            // Activate the workaround - we should trigger the offhand now
            ClientPlayerActionPacket swapHandsPacket = new ClientPlayerActionPacket(PlayerAction.SWAP_HANDS, BlockUtils.POSITION_ZERO,
                    BlockFace.DOWN);
            session.sendDownstreamPacket(swapHandsPacket);

            if (session.getConnector().getConfig().getEmoteOffhandWorkaround() == EmoteOffhandWorkaroundOption.NO_EMOTES) {
                return;
            }
        }

        long javaId = session.getPlayerEntity().getEntityId();
        for (GeyserSession otherSession : session.getConnector().getPlayers()) {
            if (otherSession != session) {
                if (otherSession.isClosed()) continue;
                if (otherSession.getEventLoop().inEventLoop()) {
                    playEmote(otherSession, javaId, packet.getEmoteId());
                } else {
                    session.executeInEventLoop(() -> playEmote(otherSession, javaId, packet.getEmoteId()));
                }
            }
        }
    }
//  [java]
    public void translate(EmotePacket packet, GeyserSession session) {
        if (session.getConnector().getConfig().getEmoteOffhandWorkaround() != EmoteOffhandWorkaroundOption.DISABLED) {
            // Activate the workaround - we should trigger the offhand now
            ClientPlayerActionPacket swapHandsPacket = new ClientPlayerActionPacket(PlayerAction.SWAP_HANDS, BlockUtils.POSITION_ZERO,
                    BlockFace.DOWN);
            session.sendDownstreamPacket(swapHandsPacket);

            if (session.getConnector().getConfig().getEmoteOffhandWorkaround() == EmoteOffhandWorkaroundOption.NO_EMOTES) {
                return;
            }
        }

        long javaId = session.getPlayerEntity().getEntityId();
        for (GeyserSession otherSession : session.getConnector().getPlayers()) {
            if (otherSession != session) {
                if (otherSession.isClosed()) continue;
                if (otherSession.getEventLoop().inEventLoop()) {
                    playEmote(otherSession, javaId, packet.getEmoteId());
                } else {
                    session.executeInEventLoop(() -> playEmote(otherSession, javaId, packet.getEmoteId()));
                }
            }
        }
    }
//  [java]
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException
	{
        // GAE can't serve dot prefixed folders
        String uri = request.getRequestURI().replace("/.", "/");
        
        // Currently, there is only one file that this servlet serves. This is only
        // needed if you want OneDrive integration. 
        if (uri != null && uri.equals("/well-known/microsoft-identity-association.json"))
        {
            if (uri.toLowerCase().contains(".json"))
            {
                response.setContentType("application/json");
            }

            // Serve whatever was requested from .well-known
            try (InputStream in = getServletContext().getResourceAsStream(uri))
            {
                if (in == null)
                {
                    response.sendError(404);
                    return;
                }
                
                byte[] buffer = new byte[8192];
                int count;

                while ((count = in.read(buffer)) > 0)
                {
                    response.getOutputStream().write(buffer, 0, count);
                }
                
                response.getOutputStream().flush();
                response.getOutputStream().close();
            }
        }
        else
        {
            response.sendError(404);
            return;
        }
    }
//  [java]
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException
	{
        // GAE can't serve dot prefixed folders
        String uri = request.getRequestURI().replace("/.", "/");

        if (uri.toLowerCase().contains(".json"))
        {
        	response.setContentType("application/json");
        }

        // Serve whatever was requested from .well-known
        try (InputStream in = getServletContext().getResourceAsStream(uri))
        {
            if (in == null)
            {
            	response.sendError(404);
                return;
            }
            
            byte[] buffer = new byte[8192];
            int count;

            while ((count = in.read(buffer)) > 0)
            {
            	response.getOutputStream().write(buffer, 0, count);
            }
            
            response.getOutputStream().flush();
            response.getOutputStream().close();
        }
    }
//  [java]
	public Controller execute(FolderComponent folderComponent, UserRequest ureq, WindowControl wControl, Translator translator) {
		VFSContainer currentContainer = folderComponent.getCurrentContainer();
		VFSContainer rootContainer = folderComponent.getRootContainer();

		if (!VFSManager.exists(currentContainer)) {
			status = FolderCommandStatus.STATUS_FAILED;
			showError(translator.translate("FileDoesNotExist"));
			return null;
		}
		status = FolderCommandHelper.sanityCheck(wControl, folderComponent);
		if (status == FolderCommandStatus.STATUS_FAILED) {
			return null;
		}
		FileSelection selection = new FileSelection(ureq, folderComponent.getCurrentContainer(), folderComponent.getCurrentContainerPath());
		status = FolderCommandHelper.sanityCheck3(wControl, folderComponent, selection);
		if (status == FolderCommandStatus.STATUS_FAILED) {
			return null;
		}

		boolean selectionWithContainer = false;
		List<String> filenames = selection.getFiles();
		List<VFSLeaf> leafs = new ArrayList<>();
		for (String file : filenames) {
			VFSItem item = currentContainer.resolve(file);
			if (item instanceof VFSContainer) {
				selectionWithContainer = true;
			} else if (item instanceof VFSLeaf) {
				leafs.add((VFSLeaf) item);
			}
		}
		if (selectionWithContainer) {
			if (leafs.isEmpty()) {
				wControl.setError(getTranslator().translate("send.mail.noFileSelected"));
				return null;
			} else {
				setFormWarning(getTranslator().translate("send.mail.selectionContainsFolder"));
			}
		}
		setFiles(rootContainer, leafs);
		return this;
	}
//  [java]
	public Controller execute(FolderComponent folderComponent, UserRequest ureq, WindowControl wControl, Translator translator) {
		VFSContainer currentContainer = folderComponent.getCurrentContainer();
		VFSContainer rootContainer = folderComponent.getRootContainer();

		if (!VFSManager.exists(currentContainer)) {
			status = FolderCommandStatus.STATUS_FAILED;
			showError(translator.translate("FileDoesNotExist"));
			return null;
		}
		status = FolderCommandHelper.sanityCheck(wControl, folderComponent);
		if (status == FolderCommandStatus.STATUS_FAILED) {
			return null;
		}
		FileSelection selection = new FileSelection(ureq, folderComponent.getCurrentContainerPath());
		status = FolderCommandHelper.sanityCheck3(wControl, folderComponent, selection);
		if (status == FolderCommandStatus.STATUS_FAILED) {
			return null;
		}

		boolean selectionWithContainer = false;
		List<String> filenames = selection.getFiles();
		List<VFSLeaf> leafs = new ArrayList<>();
		for (String file : filenames) {
			VFSItem item = currentContainer.resolve(file);
			if (item instanceof VFSContainer) {
				selectionWithContainer = true;
			} else if (item instanceof VFSLeaf) {
				leafs.add((VFSLeaf) item);
			}
		}
		if (selectionWithContainer) {
			if (leafs.isEmpty()) {
				wControl.setError(getTranslator().translate("send.mail.noFileSelected"));
				return null;
			} else {
				setFormWarning(getTranslator().translate("send.mail.selectionContainsFolder"));
			}
		}
		setFiles(rootContainer, leafs);
		return this;
	}
//  [java]
    public static String getRealIp(HttpServletRequest request) {
        String ip = null;
        //bae env
        if (ZrLogUtil.isBae() && request.getHeader("clientip") != null) {
            ip = request.getHeader("clientip");
        }
        if (ip == null || ip.length() == 0) {
            ip = request.getHeader("X-forwarded-for");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if (InetAddressUtils.isIPv4Address(ip) || InetAddressUtils.isIPv6Address(ip)) {
            return ip;
        }
        throw new IllegalArgumentException(ip + " not ipAddress");
    }
//  [java]
    public static String getRealIp(HttpServletRequest request) {
        //bae env
        if (ZrLogUtil.isBae() && request.getHeader("clientip") != null) {
            return request.getHeader("clientip");
        }
        String ip = request.getHeader("X-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
//  [go]
func (proj AppProject) IsLiveResourcePermitted(un *unstructured.Unstructured, server string, name string) bool {
	return proj.IsResourcePermitted(un.GroupVersionKind().GroupKind(), un.GetNamespace(), ApplicationDestination{Server: server, Name: name})
}
//  [go]
func (proj AppProject) IsLiveResourcePermitted(un *unstructured.Unstructured, server string, name string) bool {
	if !proj.IsGroupKindPermitted(un.GroupVersionKind().GroupKind(), un.GetNamespace() != "") {
		return false
	}
	if un.GetNamespace() != "" {
		return proj.IsDestinationPermitted(ApplicationDestination{Server: server, Namespace: un.GetNamespace(), Name: name})
	}
	return true
}
//  [java]
	public Controller execute(FolderComponent folderComponent, UserRequest ureq, WindowControl wContr, Translator trans) {
		this.translator = trans;
		FileSelection selection = new FileSelection(ureq, folderComponent.getCurrentContainer(), folderComponent.getCurrentContainerPath());
		VFSContainer currentContainer = folderComponent.getCurrentContainer();
		if (currentContainer.canWrite() != VFSConstants.YES)
			throw new AssertException("Cannot unzip to folder. Writing denied.");
			
	  //check if command is executed on a file containing invalid filenames or paths - checks if the resulting folder has a valid name
		if(selection.getInvalidFileNames().size()>0) {				
			status = FolderCommandStatus.STATUS_INVALID_NAME;
			return null;
		}		
		
		List<String> lockedFiles = new ArrayList<>();
		for (String sItem:selection.getFiles()) {
			VFSItem vfsItem = currentContainer.resolve(sItem);
			if (vfsItem instanceof VFSLeaf) {
				try {
					lockedFiles.addAll(checkLockedFiles((VFSLeaf)vfsItem, currentContainer, ureq.getIdentity()));
				} catch (Exception e) {
					String name = vfsItem == null ? "NULL" : vfsItem.getName();
					getWindowControl().setError(translator.translate("FileUnzipFailed", new String[]{name}));
				}
			}
		}
		
		if(!lockedFiles.isEmpty()) {
			String msg = FolderCommandHelper.renderLockedMessageAsHtml(trans, lockedFiles);
			List<String> buttonLabels = Collections.singletonList(trans.translate("ok"));
			lockedFiledCtr = activateGenericDialog(ureq, trans.translate("lock.title"), msg, buttonLabels, lockedFiledCtr);
			return null;
		}
		
		VFSItem currentVfsItem = null;
		try {
			boolean fileNotExist = false;
			for (String sItem:selection.getFiles()) {
				currentVfsItem = currentContainer.resolve(sItem);
				if (currentVfsItem instanceof VFSLeaf) {
					if (!doUnzip((VFSLeaf)currentVfsItem, currentContainer, ureq, wContr)) {
						status = FolderCommandStatus.STATUS_FAILED;
						break;
					}
				} else {
					fileNotExist = true;
					break;
				}
			}
			
			if (fileNotExist) {
				status = FolderCommandStatus.STATUS_FAILED;
				getWindowControl().setError(translator.translate("FileDoesNotExist"));
			}
			
			VFSContainer inheritingCont = VFSManager.findInheritingSecurityCallbackContainer(folderComponent.getRootContainer());
			if(inheritingCont != null) {
				VFSSecurityCallback secCallback = inheritingCont.getLocalSecurityCallback();
				if(secCallback != null) {
					SubscriptionContext subsContext = secCallback.getSubscriptionContext();
					if (subsContext != null) {
						notificationsManager.markPublisherNews(subsContext, ureq.getIdentity(), true);
					}
				}
			}
		} catch (IllegalArgumentException e) {
			logError("Corrupted ZIP", e);
			String name = currentVfsItem == null ? "NULL" : currentVfsItem.getName();
			getWindowControl().setError(translator.translate("FileUnzipFailed", new String[]{name}));
		}
		
		return null;
	}
//  [java]
	public Controller execute(FolderComponent folderComponent, UserRequest ureq, WindowControl wContr, Translator trans) {
		this.translator = trans;
		FileSelection selection = new FileSelection(ureq, folderComponent.getCurrentContainerPath());
		VFSContainer currentContainer = folderComponent.getCurrentContainer();
		if (currentContainer.canWrite() != VFSConstants.YES)
			throw new AssertException("Cannot unzip to folder. Writing denied.");
			
	  //check if command is executed on a file containing invalid filenames or paths - checks if the resulting folder has a valid name
		if(selection.getInvalidFileNames().size()>0) {				
			status = FolderCommandStatus.STATUS_INVALID_NAME;
			return null;
		}		
		
		List<String> lockedFiles = new ArrayList<>();
		for (String sItem:selection.getFiles()) {
			VFSItem vfsItem = currentContainer.resolve(sItem);
			if (vfsItem instanceof VFSLeaf) {
				try {
					lockedFiles.addAll(checkLockedFiles((VFSLeaf)vfsItem, currentContainer, ureq.getIdentity()));
				} catch (Exception e) {
					String name = vfsItem == null ? "NULL" : vfsItem.getName();
					getWindowControl().setError(translator.translate("FileUnzipFailed", new String[]{name}));
				}
			}
		}
		
		if(!lockedFiles.isEmpty()) {
			String msg = FolderCommandHelper.renderLockedMessageAsHtml(trans, lockedFiles);
			List<String> buttonLabels = Collections.singletonList(trans.translate("ok"));
			lockedFiledCtr = activateGenericDialog(ureq, trans.translate("lock.title"), msg, buttonLabels, lockedFiledCtr);
			return null;
		}
		
		VFSItem currentVfsItem = null;
		try {
			boolean fileNotExist = false;
			for (String sItem:selection.getFiles()) {
				currentVfsItem = currentContainer.resolve(sItem);
				if (currentVfsItem instanceof VFSLeaf) {
					if (!doUnzip((VFSLeaf)currentVfsItem, currentContainer, ureq, wContr)) {
						status = FolderCommandStatus.STATUS_FAILED;
						break;
					}
				} else {
					fileNotExist = true;
					break;
				}
			}
			
			if (fileNotExist) {
				status = FolderCommandStatus.STATUS_FAILED;
				getWindowControl().setError(translator.translate("FileDoesNotExist"));
			}
			
			VFSContainer inheritingCont = VFSManager.findInheritingSecurityCallbackContainer(folderComponent.getRootContainer());
			if(inheritingCont != null) {
				VFSSecurityCallback secCallback = inheritingCont.getLocalSecurityCallback();
				if(secCallback != null) {
					SubscriptionContext subsContext = secCallback.getSubscriptionContext();
					if (subsContext != null) {
						notificationsManager.markPublisherNews(subsContext, ureq.getIdentity(), true);
					}
				}
			}
		} catch (IllegalArgumentException e) {
			logError("Corrupted ZIP", e);
			String name = currentVfsItem == null ? "NULL" : currentVfsItem.getName();
			getWindowControl().setError(translator.translate("FileUnzipFailed", new String[]{name}));
		}
		
		return null;
	}
//  [java]
	public ProductServletConfigurator(ServerConfig serverConfig, ShiroFilter shiroFilter, GitFilter gitFilter, 
			GitPreReceiveCallback preReceiveServlet, GitPostReceiveCallback postReceiveServlet, 
			WicketServlet wicketServlet, WebSocketManager webSocketManager, ServletContainer jerseyServlet) {
		this.serverConfig = serverConfig;
		this.shiroFilter = shiroFilter;
        this.gitFilter = gitFilter;
		this.preReceiveServlet = preReceiveServlet;
		this.postReceiveServlet = postReceiveServlet;
		this.wicketServlet = wicketServlet;
		this.webSocketManager = webSocketManager;
		this.jerseyServlet = jerseyServlet;
	}
//  [java]
	public ProductServletConfigurator(ServerConfig serverConfig, ShiroFilter shiroFilter, GitFilter gitFilter, 
			GitPreReceiveCallback preReceiveServlet, GitPostReceiveCallback postReceiveServlet, 
			WicketServlet wicketServlet, WebSocketManager webSocketManager, 
			AttachmentUploadServlet attachmentUploadServlet, ServletContainer jerseyServlet) {
		this.serverConfig = serverConfig;
		this.shiroFilter = shiroFilter;
        this.gitFilter = gitFilter;
		this.preReceiveServlet = preReceiveServlet;
		this.postReceiveServlet = postReceiveServlet;
		this.wicketServlet = wicketServlet;
		this.webSocketManager = webSocketManager;
		this.jerseyServlet = jerseyServlet;
		this.attachmentUploadServlet = attachmentUploadServlet;
	}
//  [java]
    public void translate(GeyserSession session, ServerSpawnLivingEntityPacket packet) {
        Vector3f position = Vector3f.from(packet.getX(), packet.getY(), packet.getZ());
        Vector3f motion = Vector3f.from(packet.getMotionX(), packet.getMotionY(), packet.getMotionZ());
        Vector3f rotation = Vector3f.from(packet.getYaw(), packet.getPitch(), packet.getHeadYaw());

        EntityType type = EntityUtils.toBedrockEntity(packet.getType());
        if (type == null) {
            session.getConnector().getLogger().warning(LanguageUtils.getLocaleStringLog("geyser.entity.type_null", packet.getType()));
            return;
        }

        Class<? extends Entity> entityClass = type.getEntityClass();
        try {
            Constructor<? extends Entity> entityConstructor = entityClass.getConstructor(long.class, long.class, EntityType.class,
                    Vector3f.class, Vector3f.class, Vector3f.class);

            Entity entity = entityConstructor.newInstance(packet.getEntityId(), session.getEntityCache().getNextEntityId().incrementAndGet(),
                    type, position, motion, rotation
            );
            session.getEntityCache().spawnEntity(entity);
        } catch (NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException ex) {
            ex.printStackTrace();
        }
    }
//  [java]
    public void translate(ServerSpawnLivingEntityPacket packet, GeyserSession session) {
        Vector3f position = Vector3f.from(packet.getX(), packet.getY(), packet.getZ());
        Vector3f motion = Vector3f.from(packet.getMotionX(), packet.getMotionY(), packet.getMotionZ());
        Vector3f rotation = Vector3f.from(packet.getYaw(), packet.getPitch(), packet.getHeadYaw());

        EntityType type = EntityUtils.toBedrockEntity(packet.getType());
        if (type == null) {
            session.getConnector().getLogger().warning(LanguageUtils.getLocaleStringLog("geyser.entity.type_null", packet.getType()));
            return;
        }

        Class<? extends Entity> entityClass = type.getEntityClass();
        try {
            Constructor<? extends Entity> entityConstructor = entityClass.getConstructor(long.class, long.class, EntityType.class,
                    Vector3f.class, Vector3f.class, Vector3f.class);

            Entity entity = entityConstructor.newInstance(packet.getEntityId(), session.getEntityCache().getNextEntityId().incrementAndGet(),
                    type, position, motion, rotation
            );
            session.getEntityCache().spawnEntity(entity);
        } catch (NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException ex) {
            ex.printStackTrace();
        }
    }
//  [java]
	public static Collection<Style> getDeclaredStyles(BlocLines lines, AutomaticCounter counter) {
		lines = lines.eventuallyMoveAllEmptyBracket();
		final List<Style> result = new ArrayList<>();
		final CssVariables variables = new CssVariables();
		StyleScheme scheme = StyleScheme.REGULAR;

		Context context = new Context();
		final List<Map<PName, Value>> maps = new ArrayList<Map<PName, Value>>();
		boolean inComment = false;
		for (StringLocated s : lines) {
			String trimmed = s.getTrimmed().getString();

			if (trimmed.startsWith("/*") || trimmed.endsWith("*/"))
				continue;
			if (trimmed.startsWith("/'") || trimmed.endsWith("'/"))
				continue;

			if (trimmed.startsWith("/*") || trimmed.startsWith("/'")) {
				inComment = true;
				continue;
			}
			if (trimmed.endsWith("*/") || trimmed.endsWith("'/")) {
				inComment = false;
				continue;
			}
			if (inComment)
				continue;

			if (trimmed.matches("@media.*dark.*\\{")) {
				scheme = StyleScheme.DARK;
				continue;
			}

			if (trimmed.startsWith("--")) {
				variables.learn(trimmed);
				continue;
			}

			final int x = trimmed.lastIndexOf("//");
			if (x != -1)
				trimmed = trimmed.substring(0, x).trim();

			final Matcher2 mKeyNames = keyName.matcher(trimmed);
			if (mKeyNames.find()) {
				String names = mKeyNames.group(1);
				final boolean isRecurse = mKeyNames.group(2) != null;
				if (isRecurse)
					names += "*";

				context = context.push(names);
				maps.add(new EnumMap<PName, Value>(PName.class));
				continue;
			}
			final Matcher2 mPropertyAndValue = propertyAndValue.matcher(trimmed);
			if (mPropertyAndValue.find()) {
				final PName key = PName.getFromName(mPropertyAndValue.group(1), scheme);
				final String value = variables.value(mPropertyAndValue.group(2));
				if (key != null && maps.size() > 0)
					maps.get(maps.size() - 1).put(key, //
							scheme == StyleScheme.REGULAR ? //
									ValueImpl.regular(value, counter) : ValueImpl.dark(value, counter));

				continue;
			}
			final Matcher2 mCloseBracket = closeBracket.matcher(trimmed);
			if (mCloseBracket.find()) {
				if (context.size() > 0) {
					final Collection<StyleSignatureBasic> signatures = context.toSignatures();
					for (StyleSignatureBasic signature : signatures) {
						Map<PName, Value> tmp = maps.get(maps.size() - 1);
						if (signature.isWithDot())
							tmp = addPriorityForStereotype(tmp);
						if (tmp.size() > 0) {
							final Style style = new Style(signature, tmp);
							result.add(style);
						}
					}
					context = context.pop();
					maps.remove(maps.size() - 1);
				} else {
					scheme = StyleScheme.REGULAR;
				}
			}
		}

		return Collections.unmodifiableList(result);

	}
//  [java]
	public static Collection<Style> getDeclaredStyles(BlocLines lines, AutomaticCounter counter) {
		lines = lines.eventuallyMoveAllEmptyBracket();
		final List<Style> result = new ArrayList<>();
		final CssVariables variables = new CssVariables();
		StyleScheme scheme = StyleScheme.REGULAR;

		Context context = new Context();
		final List<Map<PName, Value>> maps = new ArrayList<Map<PName, Value>>();
		boolean inComment = false;
		for (StringLocated s : lines) {
			String trimmed = s.getTrimmed().getString();

			if (trimmed.startsWith("/*") || trimmed.endsWith("*/"))
				continue;
			if (trimmed.startsWith("/'") || trimmed.endsWith("'/"))
				continue;

			if (trimmed.startsWith("/*") || trimmed.startsWith("/'")) {
				inComment = true;
				continue;
			}
			if (trimmed.endsWith("*/") || trimmed.endsWith("'/")) {
				inComment = false;
				continue;
			}
			if (inComment)
				continue;

			if (trimmed.matches("@media.*dark.*\\{")) {
				scheme = StyleScheme.DARK;
				continue;
			}

			if (trimmed.startsWith("--")) {
				variables.learn(trimmed);
				continue;
			}

			final int x = trimmed.lastIndexOf("//");
			if (x != -1)
				trimmed = trimmed.substring(0, x).trim();

			final Matcher2 mKeyNames = keyName.matcher(trimmed);
			if (mKeyNames.find()) {
				String names = mKeyNames.group(1).replace(" ", "");
				final boolean isRecurse = mKeyNames.group(2) != null;
				if (isRecurse)
					names += "*";

				context = context.push(names);
				maps.add(new EnumMap<PName, Value>(PName.class));
				continue;
			}
			final Matcher2 mPropertyAndValue = propertyAndValue.matcher(trimmed);
			if (mPropertyAndValue.find()) {
				final PName key = PName.getFromName(mPropertyAndValue.group(1), scheme);
				final String value = variables.value(mPropertyAndValue.group(2));
				if (key != null && maps.size() > 0)
					maps.get(maps.size() - 1).put(key, //
							scheme == StyleScheme.REGULAR ? //
									ValueImpl.regular(value, counter) : ValueImpl.dark(value, counter));

				continue;
			}
			final Matcher2 mCloseBracket = closeBracket.matcher(trimmed);
			if (mCloseBracket.find()) {
				if (context.size() > 0) {
					final Collection<StyleSignatureBasic> signatures = context.toSignatures();
					for (StyleSignatureBasic signature : signatures) {
						Map<PName, Value> tmp = maps.get(maps.size() - 1);
						if (signature.isWithDot())
							tmp = addPriorityForStereotype(tmp);
						if (tmp.size() > 0) {
							final Style style = new Style(signature, tmp);
							result.add(style);
						}
					}
					context = context.pop();
					maps.remove(maps.size() - 1);
				} else {
					scheme = StyleScheme.REGULAR;
				}
			}
		}

		return Collections.unmodifiableList(result);

	}
//  [java]
  public DropFileContainer(final String id, final String mimeType)
  {
    super(id);
    this.mimeType = mimeType;
    main = new WebMarkupContainer("main");
    add(main);
  }
//  [java]
  public DropFileContainer(final String id, final String mimeType) {
    super(id);
    this.mimeType = mimeType;
    main = new WebMarkupContainer("main");
    add(main);
  }
//  [java]
  public void write(byte[] b, int offset, int length) throws IOException {
    if (b == null) {
      throw new NullPointerException();
    }

    if (offset < 0 || length < 0 || length > b.length || offset > b.length - length) {
      throw new ArrayIndexOutOfBoundsException();
    }

    write(fd, b, offset, length);
  }
//  [java]
  public void write(byte[] b, int offset, int length) throws IOException {
    if (b == null) {
      throw new NullPointerException();
    }

    if (offset < 0 || offset + length > b.length) {
      throw new ArrayIndexOutOfBoundsException();
    }

    write(fd, b, offset, length);
  }
//  [java]
    protected String getExecutionPreamble()
    {
        if ( getWorkingDirectoryAsString() == null )
        {
            return null;
        }

        String dir = getWorkingDirectoryAsString();
        StringBuilder sb = new StringBuilder();
        sb.append( "cd " );

        sb.append( quoteOneItem( dir, false ) );
        sb.append( " && " );

        return sb.toString();
    }
//  [java]
    protected String getExecutionPreamble()
    {
        if ( getWorkingDirectoryAsString() == null )
        {
            return null;
        }

        String dir = getWorkingDirectoryAsString();
        StringBuilder sb = new StringBuilder();
        sb.append( "cd " );

        sb.append( unifyQuotes( dir ) );
        sb.append( " && " );

        return sb.toString();
    }
//  [java]
    public String getExecutable()
    {
        if ( Os.isFamily( Os.FAMILY_WINDOWS ) )
        {
            return super.getExecutable();
        }

        return quoteOneItem( super.getOriginalExecutable(), true );
    }
//  [java]
    public String getExecutable()
    {
        if ( Os.isFamily( Os.FAMILY_WINDOWS ) )
        {
            return super.getExecutable();
        }

        return unifyQuotes( super.getExecutable());
    }
//  [java]
    public void onTaskSelectionEvent(@Observes TaskSelectionEvent event){
        selectedTaskId = event.getTaskId();
        selectedTaskName = event.getTaskName();
        
        view.getTaskIdAndName().setText(SafeHtmlUtils.htmlEscape(String.valueOf(selectedTaskId) + " - "+selectedTaskName));
        
        view.getContent().clear();
        
        String placeToGo;
        if(event.getPlace() != null && !event.getPlace().equals("")){
            placeToGo = event.getPlace();
        }else{
            placeToGo = "Task Details";
        }
        
        

        DefaultPlaceRequest defaultPlaceRequest = new DefaultPlaceRequest(placeToGo);
        //Set Parameters here: 
        defaultPlaceRequest.addParameter("taskId", String.valueOf(selectedTaskId));
        defaultPlaceRequest.addParameter("taskName", selectedTaskName);

        Set<Activity> activities = activityManager.getActivities(defaultPlaceRequest);
        AbstractWorkbenchScreenActivity activity = ((AbstractWorkbenchScreenActivity) activities.iterator().next());
        
        activitiesMap.put(placeToGo, activity);
        
        IsWidget widget = activity.getWidget();
        activity.launch(place, null);
        activity.onStartup(defaultPlaceRequest);
        view.getContent().add(widget);
        activity.onOpen();
    }